about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--ChangeLog1636
-rw-r--r--Completion/BSD/Command/_chflags25
-rw-r--r--Completion/BSD/Command/_freebsd-update1
-rw-r--r--Completion/BSD/Command/_fw_update6
-rw-r--r--Completion/BSD/Command/_ipfw137
-rw-r--r--Completion/BSD/Command/_jexec2
-rw-r--r--Completion/BSD/Command/_ldap4
-rw-r--r--Completion/BSD/Command/_pfctl5
-rw-r--r--Completion/BSD/Command/_rcctl4
-rw-r--r--Completion/BSD/Command/_sockstat8
-rw-r--r--Completion/Base/Completer/_approximate48
-rw-r--r--Completion/Base/Completer/_prefix9
-rw-r--r--Completion/Base/Core/_main_complete22
-rw-r--r--Completion/Base/Utility/_numbers2
-rw-r--r--Completion/Base/Utility/_shadow66
-rw-r--r--Completion/Base/Widget/_complete_debug2
-rw-r--r--Completion/Darwin/Command/_open8
-rw-r--r--Completion/Darwin/Command/_otool7
-rw-r--r--Completion/Darwin/Command/_shortcuts88
-rw-r--r--Completion/Darwin/Command/_softwareupdate151
-rw-r--r--Completion/Darwin/Command/_sw_vers7
-rw-r--r--Completion/Darwin/Command/_system_profiler12
-rw-r--r--Completion/Darwin/Command/_trash22
-rw-r--r--Completion/Debian/Command/_apt14
-rw-r--r--Completion/Debian/Command/_sbuild2
-rw-r--r--Completion/Linux/Command/_btrfs41
-rw-r--r--Completion/Linux/Command/_chcon24
-rw-r--r--Completion/Linux/Command/_chrt2
-rw-r--r--Completion/Linux/Command/_cpupower2
-rw-r--r--Completion/Linux/Command/_ethtool58
-rw-r--r--Completion/Linux/Command/_findmnt3
-rw-r--r--Completion/Linux/Command/_free1
-rw-r--r--Completion/Linux/Command/_fusermount2
-rw-r--r--Completion/Linux/Command/_gpasswd2
-rw-r--r--Completion/Linux/Command/_ionice2
-rw-r--r--Completion/Linux/Command/_iptables66
-rw-r--r--Completion/Linux/Command/_lsblk7
-rw-r--r--Completion/Linux/Command/_networkmanager20
-rw-r--r--Completion/Linux/Command/_pidof58
-rw-r--r--Completion/Linux/Command/_selinux796
-rw-r--r--Completion/Linux/Command/_setpriv4
-rw-r--r--Completion/Linux/Command/_strace15
-rw-r--r--Completion/Linux/Command/_sysstat6
-rw-r--r--Completion/Linux/Command/_valgrind4
-rw-r--r--Completion/Linux/Type/_selinux_contexts13
-rw-r--r--Completion/Linux/Type/_selinux_types16
-rw-r--r--Completion/Redhat/Command/_dnf2
-rw-r--r--Completion/Redhat/Command/_rpm13
-rw-r--r--Completion/Solaris/Command/_dumpadm2
-rw-r--r--Completion/Solaris/Command/_ipadm2
-rw-r--r--Completion/Solaris/Command/_pkg51
-rw-r--r--Completion/Unix/Command/_ansible112
-rw-r--r--Completion/Unix/Command/_ant19
-rw-r--r--Completion/Unix/Command/_awk1
-rw-r--r--Completion/Unix/Command/_cal129
-rw-r--r--Completion/Unix/Command/_cat3
-rw-r--r--Completion/Unix/Command/_chown7
-rw-r--r--Completion/Unix/Command/_chroot2
-rw-r--r--Completion/Unix/Command/_cmp14
-rw-r--r--Completion/Unix/Command/_column16
-rw-r--r--Completion/Unix/Command/_cp10
-rw-r--r--Completion/Unix/Command/_cut3
-rw-r--r--Completion/Unix/Command/_date23
-rw-r--r--Completion/Unix/Command/_dbus6
-rw-r--r--Completion/Unix/Command/_dd2
-rw-r--r--Completion/Unix/Command/_dig18
-rw-r--r--Completion/Unix/Command/_dmidecode1
-rw-r--r--Completion/Unix/Command/_du8
-rw-r--r--Completion/Unix/Command/_elfdump11
-rw-r--r--Completion/Unix/Command/_enscript2
-rw-r--r--Completion/Unix/Command/_env7
-rw-r--r--Completion/Unix/Command/_ffmpeg2
-rw-r--r--Completion/Unix/Command/_find4
-rw-r--r--Completion/Unix/Command/_flac1
-rw-r--r--Completion/Unix/Command/_gcc17
-rw-r--r--Completion/Unix/Command/_gcore1
-rw-r--r--Completion/Unix/Command/_gem34
-rw-r--r--Completion/Unix/Command/_getent3
-rw-r--r--Completion/Unix/Command/_git634
-rw-r--r--Completion/Unix/Command/_global9
-rw-r--r--Completion/Unix/Command/_gnutls13
-rw-r--r--Completion/Unix/Command/_gpg5
-rw-r--r--Completion/Unix/Command/_gprof2
-rw-r--r--Completion/Unix/Command/_gradle2
-rw-r--r--Completion/Unix/Command/_grep3
-rw-r--r--Completion/Unix/Command/_head1
-rw-r--r--Completion/Unix/Command/_iconv2
-rw-r--r--Completion/Unix/Command/_id4
-rw-r--r--Completion/Unix/Command/_ifconfig31
-rw-r--r--Completion/Unix/Command/_imagemagick2
-rw-r--r--Completion/Unix/Command/_install3
-rw-r--r--Completion/Unix/Command/_iostat2
-rw-r--r--Completion/Unix/Command/_java9
-rw-r--r--Completion/Unix/Command/_ldd3
-rw-r--r--Completion/Unix/Command/_less23
-rw-r--r--Completion/Unix/Command/_libvirt1
-rw-r--r--Completion/Unix/Command/_ln12
-rw-r--r--Completion/Unix/Command/_ls46
-rw-r--r--Completion/Unix/Command/_lsof6
-rw-r--r--Completion/Unix/Command/_lua1
-rw-r--r--Completion/Unix/Command/_make42
-rw-r--r--Completion/Unix/Command/_mktemp54
-rw-r--r--Completion/Unix/Command/_mosh4
-rw-r--r--Completion/Unix/Command/_mount14
-rw-r--r--Completion/Unix/Command/_mpc14
-rw-r--r--Completion/Unix/Command/_mutt9
-rw-r--r--Completion/Unix/Command/_mv12
-rw-r--r--Completion/Unix/Command/_mysql_utils1
-rw-r--r--Completion/Unix/Command/_netstat4
-rw-r--r--Completion/Unix/Command/_nice27
-rw-r--r--Completion/Unix/Command/_nkf8
-rw-r--r--Completion/Unix/Command/_nm16
-rw-r--r--Completion/Unix/Command/_objdump14
-rw-r--r--Completion/Unix/Command/_openldap222
-rw-r--r--Completion/Unix/Command/_pandoc68
-rw-r--r--Completion/Unix/Command/_perl1
-rw-r--r--Completion/Unix/Command/_perlbrew315
-rw-r--r--Completion/Unix/Command/_pgrep8
-rw-r--r--Completion/Unix/Command/_ping2
-rw-r--r--Completion/Unix/Command/_ps4
-rw-r--r--Completion/Unix/Command/_pv4
-rw-r--r--Completion/Unix/Command/_pydoc5
-rw-r--r--Completion/Unix/Command/_python8
-rw-r--r--Completion/Unix/Command/_qemu2
-rw-r--r--Completion/Unix/Command/_rake17
-rw-r--r--Completion/Unix/Command/_readelf13
-rw-r--r--Completion/Unix/Command/_ri46
-rw-r--r--Completion/Unix/Command/_rm6
-rw-r--r--Completion/Unix/Command/_route2
-rw-r--r--Completion/Unix/Command/_rsync15
-rw-r--r--Completion/Unix/Command/_ruby54
-rw-r--r--Completion/Unix/Command/_samba35
-rw-r--r--Completion/Unix/Command/_sccs2
-rw-r--r--Completion/Unix/Command/_scons4
-rw-r--r--Completion/Unix/Command/_screen2
-rw-r--r--Completion/Unix/Command/_script8
-rw-r--r--Completion/Unix/Command/_sed5
-rw-r--r--Completion/Unix/Command/_service5
-rw-r--r--Completion/Unix/Command/_split15
-rw-r--r--Completion/Unix/Command/_sqlite8
-rw-r--r--Completion/Unix/Command/_ssh193
-rw-r--r--Completion/Unix/Command/_stdbuf2
-rw-r--r--Completion/Unix/Command/_stgit52
-rw-r--r--Completion/Unix/Command/_strip102
-rw-r--r--Completion/Unix/Command/_subversion7
-rw-r--r--Completion/Unix/Command/_sudo56
-rw-r--r--Completion/Unix/Command/_sysctl8
-rw-r--r--Completion/Unix/Command/_tail1
-rw-r--r--Completion/Unix/Command/_tar2
-rw-r--r--Completion/Unix/Command/_tex2
-rw-r--r--Completion/Unix/Command/_tiff2
-rw-r--r--Completion/Unix/Command/_timeout2
-rw-r--r--Completion/Unix/Command/_tmux65
-rw-r--r--Completion/Unix/Command/_todo.sh8
-rw-r--r--Completion/Unix/Command/_touch2
-rw-r--r--Completion/Unix/Command/_tr1
-rw-r--r--Completion/Unix/Command/_trash57
-rw-r--r--Completion/Unix/Command/_truss6
-rw-r--r--Completion/Unix/Command/_uniq2
-rw-r--r--Completion/Unix/Command/_user_admin17
-rw-r--r--Completion/Unix/Command/_vmstat2
-rw-r--r--Completion/Unix/Command/_vorbis5
-rw-r--r--Completion/Unix/Command/_w4
-rw-r--r--Completion/Unix/Command/_watch5
-rw-r--r--Completion/Unix/Command/_wc1
-rw-r--r--Completion/Unix/Command/_wget3
-rw-r--r--Completion/Unix/Command/_xargs2
-rw-r--r--Completion/Unix/Command/_xfconf-query33
-rw-r--r--Completion/Unix/Command/_xmlsoft1
-rw-r--r--Completion/Unix/Command/_xxd14
-rw-r--r--Completion/Unix/Command/_xz17
-rw-r--r--Completion/Unix/Command/_zfs113
-rw-r--r--Completion/Unix/Type/_canonical_paths3
-rw-r--r--Completion/Unix/Type/_diff_options66
-rw-r--r--Completion/Unix/Type/_ldap_attributes27
-rw-r--r--Completion/Unix/Type/_ldap_filters91
-rw-r--r--Completion/Unix/Type/_ssh_hosts11
-rw-r--r--Completion/Unix/Type/_umountable3
-rw-r--r--Completion/X/Command/_evince1
-rw-r--r--Completion/X/Command/_qiv6
-rw-r--r--Completion/X/Command/_xdvi18
-rw-r--r--Completion/Zsh/Command/_cd11
-rw-r--r--Completion/Zsh/Command/_fc2
-rw-r--r--Completion/Zsh/Command/_kill8
-rw-r--r--Completion/Zsh/Command/_vared2
-rw-r--r--Completion/Zsh/Command/_zle1
-rw-r--r--Completion/Zsh/Context/_dynamic_directory_name30
-rw-r--r--Completion/Zsh/Context/_parameter5
-rw-r--r--Completion/Zsh/Context/_redirect3
-rw-r--r--Completion/Zsh/Type/_command_names10
-rw-r--r--Completion/Zsh/Type/_globquals1
-rw-r--r--Completion/Zsh/Type/_parameters7
-rw-r--r--Completion/Zsh/Type/_ps123423
-rw-r--r--Completion/compdump6
-rw-r--r--Completion/compinit4
-rw-r--r--Config/defs.mk.in3
-rw-r--r--Doc/Makefile.in8
-rw-r--r--Doc/Zsh/arith.yo5
-rw-r--r--Doc/Zsh/builtins.yo116
-rw-r--r--Doc/Zsh/compsys.yo55
-rw-r--r--Doc/Zsh/compwid.yo9
-rw-r--r--Doc/Zsh/contrib.yo104
-rw-r--r--Doc/Zsh/expn.yo284
-rw-r--r--Doc/Zsh/files.yo2
-rw-r--r--Doc/Zsh/func.yo37
-rw-r--r--Doc/Zsh/grammar.yo20
-rw-r--r--Doc/Zsh/mod_hlgroup.yo25
-rw-r--r--Doc/Zsh/mod_ksh93.yo243
-rw-r--r--Doc/Zsh/mod_parameter.yo11
-rw-r--r--Doc/Zsh/mod_pcre.yo19
-rw-r--r--Doc/Zsh/mod_private.yo15
-rw-r--r--Doc/Zsh/mod_zselect.yo2
-rw-r--r--Doc/Zsh/mod_zutil.yo7
-rw-r--r--Doc/Zsh/options.yo108
-rw-r--r--Doc/Zsh/params.yo129
-rw-r--r--Doc/Zsh/prompt.yo8
-rw-r--r--Doc/Zsh/restricted.yo4
-rw-r--r--Doc/Zsh/zle.yo37
-rw-r--r--Etc/BUGS13
-rw-r--r--Etc/FAQ.yo200
-rw-r--r--Etc/zsh-development-guide33
-rw-r--r--Functions/MIME/zsh-mime-handler2
-rw-r--r--Functions/Misc/add-zle-hook-widget4
-rw-r--r--Functions/Misc/colors2
-rw-r--r--Functions/Misc/is-at-least8
-rw-r--r--Functions/Misc/mkshadow11
-rw-r--r--Functions/Misc/run-help12
-rw-r--r--Functions/Misc/run-help-docker9
-rw-r--r--Functions/Misc/run-help-ip2
-rw-r--r--Functions/Misc/run-help-openssl8
-rw-r--r--Functions/Misc/run-help-perf1
-rw-r--r--Functions/Misc/run-help-podman9
-rw-r--r--Functions/Misc/run-help-ssh6
-rw-r--r--Functions/Misc/run-help-svk1
-rw-r--r--Functions/Misc/run-help-svnadmin1
-rw-r--r--Functions/Misc/zcalc4
-rw-r--r--Functions/Misc/zmv8
-rw-r--r--Functions/Misc/zslurp31
-rw-r--r--Functions/Prompts/prompt_sprint2_setup128
-rw-r--r--Functions/VCS_Info/Backends/VCS_INFO_get_data_git44
-rw-r--r--Functions/Zle/edit-command-line23
-rw-r--r--Functions/Zle/incarg322
-rw-r--r--Misc/vcs_info-examples2
-rw-r--r--NEWS29
-rw-r--r--README101
-rw-r--r--Src/Makemod.in.in23
-rw-r--r--Src/Modules/curses.c8
-rw-r--r--Src/Modules/files.c4
-rw-r--r--Src/Modules/hlgroup.c216
-rw-r--r--Src/Modules/hlgroup.mdd7
-rw-r--r--Src/Modules/ksh93.c287
-rw-r--r--Src/Modules/ksh93.mdd10
-rw-r--r--Src/Modules/mapfile.c10
-rw-r--r--Src/Modules/param_private.c149
-rw-r--r--Src/Modules/parameter.c28
-rw-r--r--Src/Modules/pcre.c327
-rw-r--r--Src/Modules/pcre.mdd2
-rw-r--r--Src/Modules/stat.c2
-rw-r--r--Src/Modules/terminfo.c4
-rw-r--r--Src/Modules/watch.c99
-rw-r--r--Src/Modules/zftp.c16
-rw-r--r--Src/Modules/zprof.c6
-rw-r--r--Src/Modules/zpty.c2
-rw-r--r--Src/Modules/zutil.c65
-rw-r--r--Src/Zle/compcore.c19
-rw-r--r--Src/Zle/complete.c6
-rw-r--r--Src/Zle/complist.c81
-rw-r--r--Src/Zle/compmatch.c8
-rw-r--r--Src/Zle/compresult.c12
-rw-r--r--Src/Zle/computil.c4
-rw-r--r--Src/Zle/textobjects.c6
-rw-r--r--Src/Zle/zle.h17
-rw-r--r--Src/Zle/zle_hist.c12
-rw-r--r--Src/Zle/zle_keymap.c64
-rw-r--r--Src/Zle/zle_main.c33
-rw-r--r--Src/Zle/zle_refresh.c500
-rw-r--r--Src/Zle/zle_thingy.c6
-rw-r--r--Src/Zle/zle_tricky.c71
-rw-r--r--Src/Zle/zle_utils.c55
-rw-r--r--Src/Zle/zle_vi.c9
-rw-r--r--Src/builtin.c354
-rw-r--r--Src/compat.c100
-rw-r--r--Src/exec.c232
-rw-r--r--Src/glob.c17
-rw-r--r--Src/hashtable.c28
-rw-r--r--Src/hist.c69
-rw-r--r--Src/init.c178
-rw-r--r--Src/input.c46
-rw-r--r--Src/jobs.c226
-rw-r--r--Src/lex.c125
-rw-r--r--Src/loop.c26
-rw-r--r--Src/makepro.awk6
-rw-r--r--Src/math.c44
-rw-r--r--Src/mem.c8
-rw-r--r--Src/mkbltnmlst.sh36
-rw-r--r--Src/modentry.c10
-rw-r--r--Src/module.c34
-rw-r--r--Src/options.c13
-rw-r--r--Src/params.c524
-rw-r--r--Src/parse.c36
-rw-r--r--Src/pattern.c104
-rw-r--r--Src/prompt.c392
-rw-r--r--Src/prototypes.h54
-rw-r--r--Src/signals.c100
-rw-r--r--Src/signals.h15
-rw-r--r--Src/signames2.awk18
-rw-r--r--Src/sort.c4
-rw-r--r--Src/subst.c358
-rw-r--r--Src/text.c2
-rw-r--r--Src/utils.c444
-rw-r--r--Src/zsh.h226
-rw-r--r--Src/zsh_system.h11
-rw-r--r--Src/ztype.h3
-rw-r--r--Test/A01grammar.ztst48
-rw-r--r--Test/A02alias.ztst7
-rw-r--r--Test/A04redirect.ztst5
-rw-r--r--Test/A05execution.ztst16
-rw-r--r--Test/A06assign.ztst21
-rw-r--r--Test/B02typeset.ztst28
-rw-r--r--Test/B03print.ztst5
-rw-r--r--Test/B04read.ztst10
-rw-r--r--Test/C01arith.ztst8
-rw-r--r--Test/C02cond.ztst8
-rw-r--r--Test/C03traps.ztst201
-rw-r--r--Test/D01prompt.ztst13
-rw-r--r--Test/D02glob.ztst26
-rw-r--r--Test/D04parameter.ztst107
-rw-r--r--Test/D06subscript.ztst14
-rw-r--r--Test/D07multibyte.ztst30
-rw-r--r--Test/D08cmdsubst.ztst8
-rw-r--r--Test/D09brace.ztst7
-rw-r--r--Test/D10nofork.ztst515
-rw-r--r--Test/E01options.ztst65
-rw-r--r--Test/K01nameref.ztst893
-rw-r--r--Test/K02parameter.ztst154
-rw-r--r--Test/README1
-rw-r--r--Test/V07pcre.ztst62
-rw-r--r--Test/V10private.ztst262
-rw-r--r--Test/X02zlevi.ztst18
-rw-r--r--Test/X03zlebindkey.ztst33
-rw-r--r--Test/X04zlehighlight.ztst18
-rw-r--r--Test/X05zleincarg.ztst562
-rw-r--r--Test/Y01completion.ztst90
-rw-r--r--Test/comptest8
-rw-r--r--Test/runtests.zsh1
-rwxr-xr-xTest/ztst.zsh31
-rwxr-xr-x[-rw-r--r--]Util/check-tmux-state16
-rw-r--r--Util/printdefines634
-rw-r--r--Util/ztst-syntax.vim4
-rw-r--r--aclocal.m450
-rw-r--r--aczsh.m464
-rw-r--r--configure.ac242
352 files changed, 15800 insertions, 3702 deletions
diff --git a/ChangeLog b/ChangeLog
index 0cdd632f9..df3f9b73c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,1631 @@
+2024-04-07  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52878: Src/subst.c: Fix ${foo:^bar} where bar is an associative
+	array
+
+2024-04-01  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52865: Doc/Zsh/expn.yo, Doc/Zsh/params.yo, Etc/FAQ.yo:
+	Documentation update for 52864
+
+	* 52864: Src/lex.c, Src/subst.c, Test/D10nofork.ztst,
+	Test/V10private.ztst: Change ${|var|...} to ${{var} ...},
+	limit local REPLY behavior to ${|...}, update tests.
+
+	* 52781 (and typo fix): Src/hashtable.c: HIST IGNORE_DUPS treats
+	whitespace as significant when HIST_REDUCE_BLANKS is also set.
+
+2024-04-01  Oliver Kiddle  <opk@zsh.org>
+
+	* github #115: OKURA Masafumi: Completion/Unix/Command/_ruby:
+	IRB now has `--regexp-completor` and `--type-completor` options
+
+	* 52859: Completion/Zsh/Command/_fc, Completion/Zsh/Command/_vared:
+	use _date_formats for fc and complete -m/-M for vared
+
+2024-03-25  Oliver Kiddle  <opk@zsh.org>
+
+	* 52798: Completion/Unix/Command/_ssh,
+	Completion/Unix/Type/_ssh_hosts: handle comments in ssh config
+
+2024-03-23  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52768: Completion/compdump, Completion/compinit: Handle
+	completer filenames with funny characters in them
+
+2024-03-21  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 52780: Src/Modules/hlgroup.c: remove unnecessary returns.
+
+2024-03-20  Oliver Kiddle  <opk@zsh.org>
+
+	* 52783: Src/Modules/hlgroup.c: allow for unset hash element
+
+	* unposted: configure.ac: remove reference to fp_PROG_CC_STDC
+	macro which was removed in 52750
+
+2024-03-18  Oliver Kiddle  <opk@zsh.org>
+
+	* 52770: Completion/Linux/Command/_selinux: handle newrole
+
+	* 52769: Completion/Unix/Command/_ansible: fix completion of
+	ansible keywords and --step option
+
+	* 52750: Config/defs.mk.in, Etc/zsh-development-guide,
+	Src/Makemod.in.in, Src/Modules/files.c, Src/Modules/watch.c,
+	Src/Modules/zftp.c, Src/Modules/zprof.c, Src/Zle/compcore.c,
+	Src/Zle/zle.h, Src/Zle/zle_keymap.c, Src/Zle/zle_thingy.c,
+	Src/exec.c, Src/glob.c, Src/hist.c, Src/makepro.awk, Src/mem.c,
+	Src/mkbltnmlst.sh, Src/modentry.c, Src/parse.c, Src/prototypes.h,
+	Src/signals.h, Src/utils.c, Src/zsh.h, Src/zsh_system.h, aclocal.m4,
+	configure.ac: remove ansi2knr support for old pre-ansi K&R compilers
+
+2024-03-14  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52759: Doc/Zsh/expn.yo, Etc/FAQ.yo, Src/subst.c,
+	Test/D10nofork.ztst: change ${ ... } substitution to trim one
+	trailing newline; instead "${ ... }" (with quotes) preserves that
+	newline.  All trailing newlines are still trimmed in emulations.
+
+	* unposted: Etc/BUGS: HIST_IGNORE_DUPS mishandles quoted whitespace.
+
+	* 52752: Src/params.c, Test/B02typeset.ztst: more typeset -p fixes
+	for local exports and improper "export -x" / "readonly -r" output.
+
+2024-03-13  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52753: Doc/Zsh/grammar.yo: Clarify "nocorrect" when introducing
+	precommand modifiers.
+
+	* unposted: Doc/Zsh/contrib.yo: update doc for "colors" to match
+	workers/47489,50212 (italic and bright)
+
+2024-03-12  Bart Schaefer  <schaefer@zsh.org>
+
+	* unposted: Src/Modules/ksh93.c: "typeset -p" has problems with
+	special parameters having NULL values, use a dummy static instead.
+
+	* 52742: Src/builtin.c: fix bad interactions of "typeset -p" with
+	GLOBAL_EXPORT, plus some other inconsistencies.
+
+2024-03-13  Oliver Kiddle  <opk@zsh.org>
+
+	* 52724: Src/Modules/hlgroup.c: fix .zle.sgr for empty sequences
+
+2024-03-09  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52725: Src/Modules/ksh93.c: updated named reference semantics
+
+2024-03-09  Stephane Chazelas  <stephane@chazelas.org>
+
+	* 52721: fix metafication and regexp/subject confusion in
+	pcre_match error message.
+
+2024-03-08  Stephane Chazelas  <stephane@chazelas.org>
+
+	* 52704: Doc/Zsh/params.yo, mention new ${ ... } and ${|...}
+	operators and fix process substitution terminology in
+	documentation of $zsh_eval_context.
+
+2024-03-05  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52692: Doc/Zsh/params.yo, Src/builtin.c, Src/params.c,
+	Test/K01nameref.ztst: local declaration (typeset) of the
+	name of a named reference hides the reference rather than
+	following it.  Also fix two related crash bugs.
+
+2024-03-05  Stephane Chazelas  <stephane@chazelas.org>
+
+	* 52685: Doc/Zsh/restricted.yo: fix typo in the name of bash's
+	BASH_ENV variable.
+
+2024-03-04  Bart Schaefer  <schaefer@zsh.org>
+
+	* unposted (cf. 52615): Src/builtin.c: use META_NOALLOC for 52591
+
+	* unposted (cf. 52617): Src/params.c: only scalars can instantiate
+	a declared named reference
+
+	* 52659: Src/builtin.c, Test/K01nameref.ztst: Fix crash when unset
+	was called on a named referece, add regression test
+
+	* 52650 plus minor fixes: Doc/Zsh/builtins.yo, Doc/Zsh/expn.yo,
+	Doc/Zsh/func.yo, Doc/Zsh/mod_ksh93.yo, Etc/FAQ.yo,
+	Src/Modules/ksh93.c, Src/builtin.c, Src/exec.c, Src/params.c,
+	Test/D04parameter.ztst, Test/K01nameref.ztst,
+	Test/V10private.ztst: add -u option for named references that
+	point to the "upper" scope, failed assignments have status 1
+
+2024-03-05  Oliver Kiddle  <opk@zsh.org>
+
+	* 52646: Completion/Zsh/Type/_ps1234, Doc/Zsh/compsys.yo,
+	Doc/Zsh/compwid.yo, Src/Modules/watch.c, Src/Zle/complist.c,
+	Src/Zle/zle_tricky.c, Src/prompt.c: extend support for highlight
+	groups to completion explanation strings and WATCHFMT
+
+	* 52641: midchildan: Doc/Zsh/contrib.yo, Functions/Zle/incarg,
+	Test/X05zleincarg.ztst: add a backward variant and make it repeatable
+
+2024-03-02  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52652: Src/params.c, Test/D04parameter.ztst: fix obscure bug
+	unsetting the array part of a tied parameter pair, update test
+
+	* JunT.: 52635: Test/runtests.zsh: show file name when crashed
+
+	* 52612: Src/parse.c, Src/subst.c, Src/utils.c: change the %l
+	replacment of zwarning() et al. to do literal string output;
+	change previous uses to %s and use new %l for ${var?$error}
+
+2024-03-01  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52645: Src/builtin.c: unset through a nameref keep up-scope
+	parameters declared, and not wipe out the entire parameter stack
+
+2024-02-28  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52619 (plus tests): Src/params.c, Test/A06assign.ztst: there
+	is no empty element when appending array to unset scalar
+
+2024-02-28  Oliver Kiddle  <opk@zsh.org>
+
+	* 52622 (tweaked, c.f. 52626): Src/jobs.c: adjust number of columns
+	and drop right-parenthesis in "kill -L" output
+
+	* 52623: Src/signames2.awk: add some Solaris signal descriptions
+
+	* 52594: Completion/Zsh/Command/_kill, Doc/Zsh/builtins.yo,
+	Doc/Zsh/params.yo, Src/Modules/parameter.c, Src/builtin.c,
+	Src/exec.c, Src/hashtable.c, Src/init.c, Src/jobs.c, Src/params.c,
+	Src/signals.c, Src/signals.h, Src/signames2.awk: support for
+	POSIX real-time signals with kill and trap and add -L option to
+	kill for more verbose listing of signals
+
+2024-02-24  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52597: Src/math.c: fix multibyte and metafied character counts
+	when providing context for operator and operand errors
+
+	* 52596: Src/exec.c: metafy interpreter name for error message
+
+	* Stephane: 52591: Src/builtin.c: printf builtin must pass
+	metafied strings to math evaluation
+
+2024-02-23  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52583: Src/params.c, Test/V10private.ztst: do an extra check
+	for proper scope and parameter existence when assigning to a
+	non-local name that resolves to a readonly special.
+
+2024-02-22  Oliver Kiddle  <opk@zsh.org>
+
+	* 52552: Completion/Unix/Command/_java: newer Java supports
+	passing source files directly to java
+
+2024-02-20  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52559: Doc/Zsh/builtins.yo, Doc/Zsh/mod_private.yo,
+	Src/Modules/param_private.c, Src/params.c, Test/B02typeset.ztst,
+	Test/K01nameref.ztst, Test/V10private.ztst: revise "typeset -p"
+	with respect to local readonly special parameters; update doc
+	and tests to describe handling of global readonly specials and
+	to account for side-effects on zsh/param/private.
+
+2024-02-19  Peter Stephenson  <p.w.stephenson@ntlworld.com>
+
+	* 52549: Doc/Zsh/builtins.yo: document that return already works
+	in a script.
+
+x2024-02-19  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52544: Completion/Unix/Type/_diff_options: support macOS Ventura
+	or newer
+
+2024-02-18  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52558: Etc/FAQ.yo: make note of word splitting differences
+	with nofork substitutions; update ToC; minor formatting fixes
+
+2024-02-18  Stephane Chazelas  <stephane@chazelas.org>
+
+	* 45837: Src/exec.c, Src/init.c, Src/options.c: fix issue whereby
+	original process group is not restored properly upon exit when
+	exec {var} redirs are used or MONITOR is temporarily disabled.
+
+2024-02-18  Stephane Chazelas  <stephane@chazelas.org>
+
+	* 52515: Src/exec.c (+ tests in 52527) avoid sh errors when
+	  running shebang-less scripts with paths starting with - or +
+
+2024-02-17  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52556: Test/K01nameref.ztst: regression test for unset referent
+
+	* 52556: Src/builtin.c: fix crash when applying a type change via
+	a named reference when the referent has been declared but unset
+
+2024-02-16  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52546: Functions/Zle/incarg: incarg: avoid unneeded subshell
+
+2024-02-15  Oliver Kiddle  <opk@zsh.org>
+
+	* 52520: midchildan: Doc/Zsh/contrib.yo, Functions/Zle/incarg,
+	Test/X05zleincarg.ztst: add new features and improvements to the
+	"incarg" ZLE widget
+
+	* github #112: Poncho: Completion/Unix/Command/_todo.sh:
+	Completion: todo.sh uses shorthelp and not showhelp
+
+	* 52535: Doc/Makefile.in, Doc/Zsh/prompt.yo, Doc/Zsh/zle.yo,
+	Doc/Zsh/mod_hlgroup.yo, NEWS: documentation for highlight groups
+
+	* 52533: Src/Modules/hlgroup.c, Src/Modules/hlgroup.mdd,
+	Src/prompt.c: add module to provide alternate readonly views of
+	the content of .zle.hlgroups
+
+2024-02-09  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52526: Src/Modules/terminfo.c: metafy terminfo capabilities
+
+2024-02-04  Bart Schaefer  <schaefer@zsh.org>
+
+	* unposted (cf. users/29635): Doc/Zsh/arith.yo: additional detail
+	of parameter expansion in math context.
+
+	* 52521: Etc/BUGS: mapfile handling of empty/unreadable files
+
+2024-02-04  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52516: Src/prompt.c: fix crash in %H when hlgroups is empty
+
+	* 52517: Src/prompt.c: ensure that %H is followed by {
+
+2024-02-03  Bart Schaefer  <schaefer@zsh.org>
+
+	* unposted: Util/printdefines: updates and fix omissions
+
+ 	* unposted: cf. Roman in users/29472: Functions/Misc/zslurp:
+	Efficient lossless read of stdin into $REPLY
+
+	* unposted: Src/Zle/zle_tricky.c, Src/parse.c, Src/pattern.c:
+	Record as comments some notes about namespace usage exceptions.
+
+	* 52513: Doc/Zsh/mod_private.yo, Src/Modules/param_private.c,
+	Src/params.c, Test/v10private.ztst: nofork substitutions can
+	use private parameters; fix crash bug on {privateFD}>&N; add
+	tests and documentation
+
+2024-01-28  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52510: Doc/Zsh/expn.yo, Doc/Zsh/mod_private.yo: document how
+	${ ... } et al. affect use of "private"; add index entries
+
+	* 52509: configure.ac, Src/utils.c: manage internals of stdio
+	objects when performing redirections.
+
+2024-01-28  Oliver Kiddle  <opk@zsh.org>
+
+	* 52500: Src/Zle/zle.h, Src/Zle/zle_refresh.c, Src/prompt.c:
+	add layer token to zle attributes to provide control over
+	the precedence of highlighting
+
+	* 52499: Src/prompt.c: support highlight groups defined in a
+	.zle.hlgroups associative array and referenced using %H in
+	prompt strings or hl= in zle_highlight/region_highlight
+
+	* unposted: Src/Modules/zutil.c: remove unused variable to silence
+	compiler warning
+
+	* Jörg Sommer: 52442: Src/zsh.h: Mark hookdef.name as const
+
+	* Jörg Sommer: 52444: Src/module.c: Mark name argument of some
+	functions const
+
+	* Jörg Sommer: 52441: Src/Zle/zle_vi.c: Mark variables as const
+
+	* Jörg Sommer: 52440: Src/Zle/textobjects.c: Mark variables as const
+
+2024-01-26  Oliver Kiddle  <opk@zsh.org>
+
+	* 52405, 52502: Src/Modules/pcre.c, Test/V07pcre.ztst:
+	add empty elements to $match for optional captures that don't match
+
+	* github #110: opensauce04: Completion/Redhat/Command/_dnf:
+	Fix incorrect completion for `dnf --showduplicates`
+
+	* github #108: Aurélien Olivier: Completion/Unix/Command/_perlbrew:
+	add perlbrew completion
+
+2024-01-25  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52385: Test/B03print.ztst: avoid "tr" in test output formatting
+
+2024-01-24  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52496 + 52377: Doc/Zsh/options.yo, Doc/Zsh/params.yo: clarify
+	SPROMPT behavior when CORRECT_ALL is set
+
+	* 52492: Src/math.c: prevent indexing error when using recursive
+	arithmetic in array subscript (operator stops on operand error)
+
+	* 52482: Src/subst.c: strip trailing newlines in emulation modes
+	of ${ command; }, for bash/ksh compatibility
+
+	* 52476 + cf. 52479: Etc/FAQ.yo: more about nofork substitution
+
+	* 52477: Src/Modules/curses.c: fix "zcurses mouse delay ..."
+
+	* 52473: Doc/Zsh/mod_zutil.yo, Src/Modules/zutil.c: zstyle -q
+
+	* 52468: Src/builtin.c, Src/utils.c: save and restore state of
+	correct TTY when using read -s / -d
+
+2024-01-14  Matthew Martin  <phy1729@gmail.com>
+
+	* github #109: Wu Zhenyu: Completion/Linux/Command/_valgrind: Fix
+	a typo
+
+2024-01-05  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52465: Doc/Zsh/contrib.yo, Functions/Misc/zmv: use NULL_GLOB
+	when expanding the input pattern to avoid NOMATCH exit
+
+2023-12-06  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52413: Completion/Unix/Command/_iconv: support Citrus version
+	on macOS, DragonFly and NetBSD
+
+2023-12-13  Oliver Kiddle  <opk@zsh.org>
+
+	* Florian Weimer: 52383: configure.ac: Avoid incompatible pointer
+	types in terminfo global variable checks
+
+	* 52394: configure.ac: alter form of /dev/fd test to work where
+	/bin/sh is ksh such as on Solaris 11
+
+	* 52393: Test/ztst.zsh: fix tests on Solaris by omitting -a option
+	to diff as it is not supported there
+
+	* 52392: Src/makepro.awk: use octal escape to match = without
+	error messages from either GNU awk or Solaris awk
+
+	* 52382: Src/Modules/ksh93.c, Src/Zle/zle_utils.c: avoid \e in C code
+
+2023-12-09  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52366 + fix typo: Completion/Unix/Command/_ant: rename
+	find_targets as _ant_targets, replace one sed with substitution
+
+	* 52365: Src/jobs.c, Src/signals.c: record state of exited
+	background jobs sooner so as to be visible in TRAPCHLD
+
+2023-12-05  Oliver Kiddle  <opk@zsh.org>
+
+	* 52326, 52372: configure.ac, Src/jobs.c, Doc/Zsh/builtins.yo,
+	Completion/Zsh/Command/_kill: add -q option to kill for sigqueue
+
+	* 52373: Completion/Base/Utility/_numbers,
+	Completion/Solaris/Command/_dumpadm, Completion/Unix/Command/_xz:
+	fix _numbers for suffixes containing % and update affected functions
+
+2023-12-04  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52356: (cf. 52327 Dennis Eriksen): Doc/Zsh/builtins.yo: add
+	missing function index entries
+
+2023-12-02  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52361: Completion/Unix/Command/_ant: fix quoting of target files
+	(derived from Germán Riaño: 52329)
+
+	* 52360: Test/A04redirect.ztst: Simplify bad-descriptor check in
+	%prep -- avoids accidentally using an open descriptor (derived
+	from Germán Riaño: 52328)
+
+2023-11-29  Bart Schaefer  <schaefer@zsh.org>
+
+	* Sebastian Gniazdowski: 52145: Functions/Prompts/prompt_sprint2_setup:
+	Contributed prompt theme with current time and abbreviated VCS_info.
+
+2023-11-23  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52325: Doc/Zsh/expn.yo, Doc/Zsh/mod_ksh93.yo, Doc/Zsh/params.yo:
+	Clarify side-effects of $argv and named references to specials,
+	update ksh93 feature compatibility.
+
+	unposted: Src/subst.c, Test/D10nofork.ztst: whitespace tweak to
+	avoid unexpected parse error when comments are used in ${ ... }
+
+2023-11-22  Oliver Kiddle  <opk@zsh.org>
+
+	* unposted: Completion/Unix/Command/_ri: fix missing closing brace
+
+	* 52315: Completion/...: completion options update
+
+2023-11-18  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52313: Src/exec.c: subshells implementing multio reads/writes
+	are not interactive and should check for write errors.
+
+2023-11-17  Oliver Kiddle  <opk@zsh.org>
+
+	* 52307: Completion/Linux/Command/_selinux,
+	Completion/Linux/Command/_chcon, Completion/Linux/Command/_setpriv,
+	Completion/Linux/Type/_selinux_contexts, Completion/Unix/Command/_cp,
+	Completion/Linux/Type/_selinux_types, Completion/Unix/Command/_find,
+	Completion/Unix/Command/_install, Completion/Unix/Command/_mount,
+	Completion/Unix/Command/_zfs: new completion for many SELinux tools
+
+	* 52303: Completion/Unix/Command/_ifconfig,
+	Completion/Unix/Command/_chown, Completion/Unix/Command/_cp,
+	Completion/Unix/Command/_cut, Completion/Unix/Command/_date,
+	Completion/Unix/Command/_du, Completion/Unix/Command/_env,
+	Completion/Unix/Command/_id, Completion/Unix/Command/_ln,
+	Completion/Unix/Command/_ls, Completion/Unix/Command/_make,
+	Completion/Unix/Command/_mount, Completion/Unix/Command/_mv,
+	Completion/Unix/Command/_rm, Completion/Unix/Command/_sed,
+	Completion/Unix/Command/_split, Completion/Unix/Command/_touch,
+	Completion/Unix/Command/_uniq, Completion/Unix/Command/_xargs:
+	updates to completions for macOS 13
+
+2023-11-15  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52309: Src/exec.c: suppress job control inside <<(substition)
+	to fix cases that hang with all signals blocked.  Similarly,
+	allow interrupt of multios reading from a terminal.
+
+	* 52308: Etc/FAQ.yo: mention new features, fix some old answers
+
+	* 52275: Src/compat.c: rationality in zgetdir() and zgetcwd() to
+	avoid silently wandering out of the current directory when path
+	parents are inaccessible.
+
+	* 52202: Src/lex.c, Src/subst.c, Test/D04parameter.ztst: improve
+	handling of quoting in ${var/pattern/replacement}.  Still not
+	perfect, e.g., deeply nested expansions	in the pattern may fail.
+
+2023-11-14  Oliver Kiddle  <opk@zsh.org>
+
+	* github #106: Matt Koscica: Completion/Unix/Command/_tmux,
+	Util/check-tmux-state: update tmux completion (20230919)
+
+	* unposted (cf. 52167): Completion/Unix/Command/_mutt:
+	mutt's -a takes a list of files terminated by --
+
+	* 52301: Completion/Unix/Command/_gem, Completion/Unix/Command/_ri,
+	Completion/Unix/Command/_ruby: update options in completions for
+	ruby 3.2, gem 3.4.10 and ri 6.5
+
+	* 52300: Completion/Unix/Command/_ansible: ansible 2.15.2 updates
+
+2023-11-09  Oliver Kiddle  <opk@zsh.org>
+
+	* 52280: Completion/Unix/Command/_git: update git completion for new
+	options in git through to version 2.42.0
+
+2023-11-08  Oliver Kiddle  <opk@zsh.org>
+
+	* github #105: Shotaro Aoyama: Completion/Zsh/Command/_zle:
+	add "-I" for "zle" completion
+
+	* Eric Cook: 52168: Completion/Unix/Command/_xfconf-query:
+	add completion for xfce's xfconf-query(1)
+
+	* 52271: Src/Modules/pcre.c: use correct form for unused parameter
+
+2023-11-02  Oliver Kiddle  <opk@zsh.org>
+
+	* 52268: Completion/Linux/Command/_networkmanager: update to 1.42.2
+
+	* 52266: Completion/Linux/Command/_strace: update to 2.6.5
+
+	* 52265: Completion/Linux/Command/_findmnt,
+	Completion/Linux/Command/_lsblk, Completion/Unix/Command/_column:
+	update completions for some util-linux tools to version 2.39.2
+
+	* 52253: Src/Modules/pcre.c: support pcre callouts with shell
+	evaluation of the callout string
+
+	* 52260: Completion/Unix/Command/_sudo: handle variable assignments
+	before the command in sudo completion
+
+2023-11-01  Oliver Kiddle  <opk@zsh.org>
+
+	* 52252: Src/Modules/pcre.c: Coverity defect 1547827
+
+	* Shohei YOSHIDA: 52179: Completion/Unix/Command/_gradle:
+	Fix gradlew completion when it isn't in PATH
+
+2023-10-29  Matthew Martin  <phy1729@gmail.com>
+
+	* github #102: Ulysse Buonomo: Completion/Unix/Command/_todo.sh:
+	Ensure todo.sh completion uses builtin commands
+
+2023-10-25  Bart Schaefer  <schaefer@zsh.org>
+
+	* Daniel Shahaf: 50569 (tweaked): README, Src/Zle/zle_keymap.c:
+	main keymap defaults to emacs
+
+	* Sebastian Gniazdowski: 52240: Functions/MIME/zsh-mime-handler:
+	use work-var $s not $suffix when setting flags
+
+	* 52244: Src/Modules/zutil.c, Src/Zle/compcore.c,
+	Src/Zle/compresult.c, Src/builtin.c, Src/glob.c, Src/hist.c,
+	Src/input.c, Src/params.c, Src/utils.c: Coverity defects 1547831,
+	1547826 (remove unused function), 1521551, 1500752, 1500747,
+	1401549, 1372423, 1270645, 1255799, 1255792, 1255789, 1255787,
+	1255782, 1255750
+
+2023-10-24  Matthew Martin  <phy1729@gmail.com>
+
+	* github #103: Christian Heusel: Completion/Unix/Command/_zfs: fix
+	completion for zpool upgrade
+
+	* github #104: ErrrorMaxx: Src/exec.c: fix small typo
+
+2023-10-16  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52056: Completion/Unix/Command/_sccs: _sccs: don't handle
+	subcommands in main namespace
+
+	* 51490: Src/Zle/computil.c: Use time_t for lastt which stores
+	result of time(0)
+
+	* 52222: Doc/Zsh/contrib.yo: Document bracketed-paste-url-magic
+
+2023-10-15  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52218: Etc/BUGS, NEWS, README: notes since 5.9 release
+
+2023-10-10  Oliver Kiddle  <opk@zsh.org>
+
+	* 52189: Completion/Unix/Type/_umountable, Src/Zle/complete.c:
+	ignore compadd -M if -U also specified as they don't make
+	sense together, this fixes df completion
+
+	* 52217: Completion/BSD/Command/_freebsd-update,
+	Completion/BSD/Command/_ipfw, Completion/BSD/Command/_pfctl,
+	Completion/BSD/Command/_sockstat, Completion/Unix/Command/_cmp,
+	Completion/Unix/Command/_date, Completion/Unix/Command/_elfdump,
+	Completion/Unix/Command/_gcore, Completion/Unix/Command/_mktemp,
+	Completion/Unix/Command/_iostat, Completion/Unix/Command/_ldd,
+	Completion/Unix/Command/_ls, Completion/Unix/Command/_ifconfig,
+	Completion/Unix/Command/_netstat, Completion/Unix/Command/_script,
+	Completion/Unix/Command/_service, Completion/Unix/Command/_split,
+	Completion/Unix/Command/_ssh, Completion/Unix/Command/_sysctl,
+	Completion/Unix/Type/_diff_options:
+	update completions for FreeBSD 14
+
+	* 52216: Src/Modules/watch.c: metafy usernames to allow for
+	them to be UTF-8 encoded
+
+	* 52214: Src/subst.c: allow extra byte for nul in allocation
+
+	* unposted (cf. 52166): Functions/Misc/run-help-svk:
+	remove obsolete helper for svk
+
+	* Jörg Sommer: 51812: Functions/Misc/run-help-docker,
+	Functions/Misc/run-help-perf, Functions/Misc/run-help-podman,
+	Functions/Misc/run-help-ssh, Functions/Misc/run-help-svnadmin:
+	run-help for docker, perf, podman, ssh, svnadmin
+
+2023-10-05  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52204: Src/parse.c: fix unmeta() thinko from 52193
+
+2023-10-03  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52198: Src/input.c: put back incorrectly removed zfree()
+
+2023-10-01  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52195: Src/params.c: cached_username is already metafied when
+	initializing LOGNAME
+
+	* 52193: Src/init.c, Src/params.c, Src/utils.c: metafy USERNAME
+	(mostly for Cygwin compatibilty with UTF8 encodings)
+
+	* 52193: Src/parse.c: unmetafy file paths in zcompile
+
+2023-09-27  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52188: Test/D04parameter.ztst: skip tests that fail if
+	multibyte is not available
+
+	* 52169: Src/subst.c, Src/utils.c: a few more improvemets of (#)
+
+2023-09-23  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52180: Doc/Zsh/expn.yo: clarify array behavior of ${|var|...}
+	and the REPLY parameter
+
+2023-09-22  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52176: Src/subst.c: metafy return from ${ ... } substitution
+	(adapted from Jun T.: 52172)
+
+2023-09-20  Oliver Kiddle  <opk@zsh.org>
+
+	* Jörg Sommer: 51747: Functions/Misc/run-help-ip:
+	ip accepts the reduction of link to l
+
+	* Jörg Sommer: 51776: Functions/Misc/run-help-openssl:
+	Reduce code and use new manpages
+
+	* Wim de With: 51857: Completion/Linux/Command/_fusermount:
+	Include fusermount3 in fusermount completions
+
+	* Atte Peltomäki: 51980: Completion/Zsh/Type/_globquals,
+	Doc/Zsh/expn.yo: Add glob qualifier grouping operator to completion
+
+	* Jörg Sommer: 52102: Completion/Debian/Command/_apt:
+	Add subcommand autopurge to apt completion
+
+	* Wesley Schwengle: 52141: Completion/Unix/Command/_git:
+	add trailer token completion for git commit --trailer
+
+	* 52163: Completion/Unix/Command/_zfs: completion update for
+	OpenZFS 2.2
+
+2023-09-16  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52156: Test/E01options.ztst: Test case for user/29160.
+
+	* users/29160: Src/subst.c: Fix repetition of substituion modifier.
+
+	* Christoffer Lundell: 52082: Functions/Zle/edit-command-line:
+	Enable linewise edit-command when in visual-line mode.
+
+	* 52155: Test/D10nofork.ztst: Tests for non-forking substitution.
+
+	* 52154: Doc/Zsh/expn.yo, Src/lex.c, Src/subst.c:  implement
+	and document non-forking command substitutions ${|...} and
+	${ ... }.  Based on Sebastian Gniazdowski: 51702.
+
+	* 52153: Src/input.c, Src/Modules/mapfile.c: $mapfile[fname]
+	should not trim newlines (only applies when not HAVE_MMAP)
+
+2023-09-15  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 52142: Completion/Zsh/Context/_parameter,
+	Completion/Zsh/Type/_parameters: Move _history_modifiers call
+	to _parameter
+
+2023-09-13  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52122 + 52129: Src/subst.c, Test/D04parameter.ztst: fix (#)
+	parameter expansion flag for bad math expressions and out-of-
+	range characters
+
+2023-09-10  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52125: Src/exec.c: getoutput() must not free() gettempname()
+
+2023-09-09  Bart Schaefer  <schaefer@zsh.org>
+
+	* unposted: Completion/Base/Utility/_shadow: quoting for safety
+
+2023-09-07  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52114: Completion/Unix/Command/_nice: improve _nice (support
+	-n option, complete only external commands)
+
+2023-09-05  Bart Schaefer  <schaefer@zsh.org>
+
+	* 52115: Src/Modules/param_private.c, Test/V10private.ztst: permit
+	repeated "private" declarations as long as types aren't changed
+
+2023-09-04  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52112: Completion/BSD/Command/_jexec,
+	Completion/Linux/Command/_chrt, Completion/Linux/Command/_cpupower,
+	Completion/Linux/Command/_ionice,Completion/Linux/Command/_setpriv,
+	Completion/Linux/Command/_sysstat, Completion/Unix/Command/_chroot,
+	Completion/Unix/Command/_mosh, Completion/Unix/Command/_route,
+	Completion/Unix/Command/_screen, Completion/Unix/Command/_script,
+	Completion/Unix/Command/_ssh, Completion/Unix/Command/_stdbuf,
+	Completion/Unix/Command/_timeout: use '_normal -p $service' to
+	complete only external commands
+
+2023-09-03  Bart Schaefer  <schaefer@zsh.org>
+
+	* users/29220: Src/Modules/param_private.c, Test/V10private.ztst:
+	fix bug with assignment to private following explicit unset
+
+2023-08-28  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* Shohei YOSHIDA: 52098(+comment), 52099, 52100, 52105(+52106):
+	Completion/Darwin/Command/_open, Completion/Darwin/Command/_otool,
+	Completion/Darwin/Command/_sw-vers,
+	Completion/Darwin/Command/_system_profiler:
+	update for latest macOS (with a few fixes)
+
+	* sergio: 51858 (+52073): Completion/Unix/Command/_libvirt:
+	virsh's edit subcommand accepts all domains
+
+2023-08-27  Bart Schaefer  <schaefer@zsh.org>
+
+	* Marlon Richert: 51861 (tweaked for 52028):
+	Completion/Base/Completer/_approximate: allow _approximate
+	to provide corrections even when compadd is overridden
+
+	* 52028: Completion/Base/Utility/_shadow, Doc/Zsh/compsys.yo,
+	Doc/Zsh/contrib.yo, Functions/Misc/mkshadow: improve _shadow
+	and _unshadow, add helper function and update documentation
+
+	* Robert Woods: 52053: Src/utils.c: whitelist capability
+	CAP_WAKE_ALARM in 'privasserted' function
+
+	* Shohei YOSHIDA: 52034: Completion/Unix/Command/_sqlite:
+	update for version 3.42.0
+
+2023-08-22  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* Nojus Gudinavičius: users/29175: Src/Zle/zle_hist.c: don't
+	need to forget edits if none were made, avoiding loop over
+	entire history.
+
+2023-08-21  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* Shohei YOSHIDA: 52059 (+52070): Completion/Unix/Command/_scons:
+	fix for options -j/--jobs and -q/--question
+
+2023-08-16  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 29130, 29131 (Ray): Doc/Zsh/builtins.yo: document what typeset
+	-t is for, not what it isn't for.
+
+2023-08-14  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 52037: Completion/Unix/Command/_date,
+	Completion/Unix/Command/_env, Completion/Unix/Command/_watch:
+	complete only external commands for env and watch, with a few
+	more minor fixes
+
+2023-08-06  Bart Schaefer  <schaefer@zsh.org>
+
+	* Shohei YOSHIDA: 52018: Completion/Unix/Command/_wc: latest
+	coreutils options
+
+	* Shohei YOSHIDA: 52017: Completion/Unix/Command/_tr: latest
+	coreutils options
+
+	* Shohei YOSHIDA: 52016: Completion/Unix/Command/_tail: latest
+	coreutils options
+
+	* Shohei YOSHIDA: 52015: Completion/Unix/Command/_env: latest
+	coreutils options
+
+	* Shohei YOSHIDA: 52014: Completion/Unix/Command/_date: latest
+	coreutils options
+
+	* Shohei YOSHIDA: 52013: Completion/Unix/Command/_head: latest
+	coreutils options
+
+2023-08-01  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 52008: Src/pattern.c, Test/D02glob.ztst: Fix bug with branches
+	in patterns followed by an exculsion, and add tests.
+
+2023-07-31  dana  <dana@dana.is>
+
+	* github #100: HexorCatZ: Completion/Unix/Command/_qemu:
+	add -enable-kvm and -bios suggestion
+
+2023-07-26  Bart Schaefer  <schaefer@zsh.org>
+
+	* unposted (cf. 51968): Doc/Zsh/builtins.yo: improve description
+	of typeset -gn and -r
+
+	* 51945: Doc/Zsh/builtins.yo, Doc/Zsh/expn.yo, Doc/Zsh/params.yo,
+	Src/builtin.c, Src/params.c, Test/K01nameref.ztst: improve named
+	references documentation, fixes for typeset -r and -g behavior,
+	fix unset reference behavior including scoping crash, more tests
+
+	* Shohei YOSHIDA: 51979: Completion/Linux/Command/_free: Update
+	free completion for procps-ng version 4.0.3
+
+	* Shohei YOSHIDA: 51964: Completion/Linux/Command/_pidof: support
+	pidof variants other than procps
+
+	* 51969: Src/builtin.c: read -d and -s should not reset terminal
+	state when stdin is redirected
+
+	* 51949 (tweak per 51950): Src/Zle/zle_main.c: correct Thingy
+	refcount in raw_getbyte()
+
+	* Shohei YOSHIDA: 51927: Completion/Unix/Command/_watch: Update
+	procps watch completion for version 4.0.3
+
+	* unposted (cf. 51899): Doc/Zsh/compsys.yo: document _shadow
+
+2023-07-20  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51977: Src/jobs.c, Test/E01options.ztst: Combination of
+	PIPEFAIL and ERRRETURN / ERREXIT options failed with complex
+	commands at end of pipeline.
+
+2023-07-19  dana  <dana@dana.is>
+
+	* github #99: mirsella: Completion/Darwin/Command/_trash,
+	Completion/Unix/Command/_trash: add completion for trash-d
+
+2023-07-10  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51897 (+ minor tweaks): Completion/Darwin/Command/_softwareupdate:
+	update _softwareupdate (based on 51895 by Shohei YOSHIDA)
+
+2023-07-09  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51890: Src/builtin.c: fix "whence -wa" for multiple arguments
+
+2023-06-26  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51889: Src/Modules/zftp.c, Src/mkbltnmlst.sh: enable loading a
+	module (e.g. zftp) that depends on other modules even if zsh is
+	built with the full RELRO
+
+	* 51884: Doc/Zsh/params.yo, Src/params.c, Src/utils.c,
+	Test/D04parameter.ztst: if MULTIBYTE option is on and IFS contains
+	invalid bytes in curret locale then reset it to default
+
+2023-06-22  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51887: Src/math.c, Src/params.c, Test/K02parameter.ztst:
+	namespaces recognized in math, incorrect usages rejected.
+
+	* Marlon Richert: 51860: Completion/Base/Completer/_prefix,
+	Test/Y01completion.ztst, Test/comptest: simplify suffix handling
+	in _prefix to remove longstanding and less accurate hack; tests.
+
+	* Stephane: 51813: Functions/Misc/is-at-least: differentiate empty
+	$2 from omitted $2 to avoid wrong comparisons against ZSH_VERSION.
+
+2023-06-20  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51877: Src/Modules/pcre.mdd, configure.ac: do not build pcre
+	module if pcre2-config is not available.
+
+2023-06-19  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51862: Doc/Makefile.in, configure.ac: support texinfo-7.0
+
+2023-06-08  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51826: Src/hist.c: correctly handle metafied null character
+	when reading history file
+
+	* Stephane: 51817: Completion/BSD/Command/_rcctl: protect ':'
+	in _rcctl (was in 51817 but missed in commit 0577daf)
+
+2023-06-06  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* Stephane: 51818: Protect another ':'.
+
+	* Stephane: 51817: Protect some use of ':' from history modifier
+	interpreation.
+
+	* 51816: Doc/Zsh/expn.yo, Src/hist.c, Src/subst.c,
+	Test/D04parameter.ztst: add :S history modifier with pattern
+	match.
+
+2023-06-06  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* Marlon Richert: 51779: Test/Y01completion.ztst: update
+	completion test for 51761
+
+2023-05-25  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51739: Src/hist.c: detect invalid history word beginning.
+
+2023-05-21  Oliver Kiddle  <opk@zsh.org>
+
+	* 51769: Src/jobs.c, Src/utils.c: fix compilation when
+	HAVE_GETRUSAGE is not defined
+
+	* Marlon Richert: 51761: Completion/Zsh/Type/_parameters:
+	Use zstyle verbose for _parameters descriptions
+
+	* Marlon Richert: 51682: Completion/Base/Core/_main_complete,
+	Test/Y01completion.ztst: Fix subscript completion bugs
+	inside ~[...]
+
+	* Marlon Richert: 51759: Completion/Zsh/Type/_command_names:
+	Show alias values in command completions
+
+	* Marlon Richert: 51760: Doc/Zsh/compwid.yo: r and R were listed
+	in the wrong order.
+
+	* Marlon Richert: 51758: Test/Y01completion.ztst, Doc/Zsh/expn.yo,
+	Completion/Zsh/Context/_dynamic_directory_name: Make dynamic dir
+	completion easier to implement
+
+2023-05-13  Peter Stephenson  <p.w.stephenson@ntlworld.com>
+
+	* 51722: Src/Modules/parameter.c: Add safety to extracting
+	elements of $historywords.
+
+2023-05-13  Oliver Kiddle  <opk@zsh.org>
+
+	* 51738: Doc/Zsh/mod_pcre.yo, Src/Modules/pcre.c,
+	Test/V07pcre.ztst: support pcre's DFA matching algorithm
+
+	* 51728: Doc/Zsh/mod_pcre.yo, Src/Modules/pcre.c,
+	Test/V07pcre.ztst: assign pcre named capture groups to a hash
+
+	* 51723: Src/Modules/pcre.c, Test/V07pcre.ztst, configure.ac:
+	migrate pcre module to pcre2
+
+	* Felipe Contreras: 50612: Misc/vcs_info-examples: fix typo
+
+	* github #98: Vidhan Bhatt: Completion/Darwin/Command/_shortcuts:
+	feat: add `shortcuts` completions
+
+2023-05-11  Bart Schaefer  <schaefer@zsh.org>
+
+	* users/29070: Src/Zle/zle_tricky.c: clean up tokens in cmdstr
+	before attempting completion (compctl only)
+
+	* Jim <linux.tech.guy@gmail.com>: 51609: Doc/Zsh/mod_zselect.yo:
+	fix reference to select(2)
+
+	* Shohei YOSHIDA: 51340: Completion/Unix/Command/_rake: update
+	for version 13
+
+	* Shohei YOSHIDA: 51331: Completion/Unix/Command/_pydoc: update
+	for version 3.11
+
+2023-05-10  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51593: Functions/Misc/run-help: improve search for original
+	command name after skipping prefix assignments
+
+2023-05-08  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51692: Test/C02cond.ztst: do not skip tests for [[ -r file ]]
+	and [[ -N file ]] on Cygwin
+
+2023-04-22  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51670: Src/text.c: prevent possible underflow in gettext()
+
+2023-04-18  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51663: Completion/Unix/Command/_ssh: fix a typo in 51582
+
+2023-04-17  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51652 (plus typo correction): Src/exec.c, Test/C03traps.ztst:
+	fix running of TRAPEXIT explicitly.
+
+2023-04-11  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51639: Doc/Zsh/params.yo, Src/init.c, configure.ac: add new
+	parameter ZSH_EXEPATH that is set to the full pathname of the
+	executable file of the current zsh
+
+2023-04-09  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51631: Doc/Zsh/params.yo, Src/init.c: initialize $_ by copying
+	it from environment
+
+	* 51632: Src/exec.c: unmetafy $_ when exporting it to child
+
+2023-04-03  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51597: Src/Zle/zle_utils.c: fix 'vared -c var' when var is unset
+
+2023-03-30  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51604: Src/jobs.c, configure.ac: %M in TIMEFMT should report
+	in kilobytes
+
+2023-03-29  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51608: Src/exec.c, Test/A01grammar.ztst: shouldn't be
+	executing commands after "continue &&" or "! continue ||".
+
+2023-03-28  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 51602: Src/jobs.c, Src/signames2.awk: Handle SIGIOT as an
+	alias to SIGABRT if they are the same signal number
+
+2023-03-27  Oliver Kiddle  <opk@zsh.org>
+
+	* Shohei YOSHIDA: 51589: Completion/Unix/Command/_nm:
+	Update nm options
+
+	* 51603: Completion/Unix/Command/_git: complete dates and times
+	in the form that git accepts
+
+2023-03-22  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51586: Src/builtin.c: When printf "%s" encounters a byte
+	that's not part of a valid multibyte character it should handle
+	it a single byte at a time.
+
+2023-03-16  Oliver Kiddle  <opk@zsh.org>
+
+	* 51583: Completion/Unix/Command/_git: update completion of
+	git attributes
+
+	* 51582: Completion/Unix/Command/_ssh: openssh 9.3 completion update
+
+	* 51581: Completion/BSD/Command/_fw_update,
+	Completion/BSD/Command/_rcctl, Completion/Unix/Command/_grep,
+	Completion/Unix/Command/_netstat, Completion/Unix/Command/_ps:
+	update completions to cover changes in OpenBSD 7.2
+
+2023-03-14  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51573: Src/builtin.c: additional "typset -p -m" fix for namespaces
+
+2023-03-13  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51572: Functions/Misc/run-help: fix error when running standalone
+
+	* Sven Joachim: 51563: Completion/Debian/Command/_sbuild: unmatched "
+
+2023-03-11  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51558: Doc/Zsh/grammar.yo: Clarify "for" loops + named refs.
+
+	* 51557: Doc/Zsh/mod_ksh93.yo, Src/Modules/ksh93.c: Clarify
+	availability of ksh-mode parameters, improve vi-mode detection.
+
+2023-03-11  Oliver Kiddle  <opk@zsh.org>
+
+	* 51539: Completion/Unix/Command/_git: don't complete diff
+	options to git blame
+
+2023-03-07  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51534: Util/printdefines: update for recent changes
+
+2023-03-06  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51512: Doc/Zsh/mod_ksh93.yo: More about unsupported features
+
+	* 51511: Doc/Zsh/expn.yo, Doc/Zsh/params.yo: Document namespaces
+
+	* 51510: Src/builtin.c, Src/params.c, Src/utils.c, Src/zsh.h,
+	Test/K02parameter.ztst: parameters with a leading namespace are
+	skipped in output of "set" and "typeset", add tests for ksh-like
+	parameter handling and fix a bug thus revealed
+
+	* 51509 (+ fix typo): Src/params.c, Src/subst.c, Src/zsh.h: Add
+	${(!)name} for the referred-to parameter of a named reference,
+	and extend ${!name} in ksh emulation for same
+
+	* 51524: Src/Modules/ksh93.mdd: dependency on zsh/zle for linkage
+
+2023-03-05  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51486: Etc/zsh-development-guide: clarify module section
+
+	* 51485: Doc/Makefile.in, Doc/Zsh/mod_ksh93.yo, Src/utils.c,
+	Src/Modules/ksh93.c, Src/Modules/ksh93.mdd: module for several
+	ksh93 features, mostly enabled only in ksh emulation.
+
+	* 51484: Src/builtins.yo Src/params.c: Extend named reference
+	handling for special parameters, improve doc.
+
+	* 51483: Src/Zle/compcore.c, Src/Zle/zle_tricky.c, Src/lex.c,
+	Src/params.c, Src/subst.c, Src/utils.c, Src/zsh.h, Src/ztype.h:
+	Enable assignment and expansion of parameters with ksh-like
+	namespace prefixes.
+
+	* unposted: Src/Modules/param_private.c: coverity memory leak
+
+2023-02-28  Mikael Magnusson  <mikachu@gmail.com>
+
+	* 51491: Src/Zle/zle_utils.c: Check should use zlemetacs instead
+	of zlecs
+
+2023-02-26  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51464: Util/printdefines: utility to interpret zsh.h constants
+
+	* unposted: Doc/Zsh/restricted.yo: fix typo
+
+	* 51460: Src/module.c: avoid crash on bad parameter autofeature
+
+2023-02-24  Oliver Kiddle  <opk@zsh.org>
+
+	* Shohei YOSHIDA: 51473: Completion/Unix/Command/_cal:
+	Update cal/ncal completion
+
+	* Sebastian Stark: 51470 (tweaked, c.f. 51476):
+	Completion/Zsh/Command/_cd: Separate cdpath elements in
+	path-directories completion
+
+	* 51474: Completion/Unix/Command/_ansible: make -e and --vault-id
+	options repeatable and update for new options to ansible 2.13.2
+
+2023-02-21  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51466: Src/params.c: fix access to autoloaded parameter.
+
+2023-02-20  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51431: Src/builtin.c: "typeset -p" shouldn't change parameter flags
+
+2023-02-19  Oliver Kiddle  <opk@zsh.org>
+
+	* 51456: Completion/Unix/Command/_git: complete only modified
+	files with git add -u
+
+	* 51455, 51461: Completion/Unix/Type/_ldap_attributes
+	Completion/BSD/Command/_ldap, Completion/Unix/Command/_openldap,
+	Completion/Unix/Type/_ldap_filters: new completion for the OpenLDAP
+	client tools including a helper function for LDAP search filters
+
+2023-02-17  Oliver Kiddle  <opk@zsh.org>
+
+	* 51447: Src/Zle/zle_keymap.c: silence compiler maybe-uninitialized
+	warning by combining a couple of variables
+
+	* Øystein Walle: 51391: Completion/Unix/Command/_git:
+	complete remote branch names respecting --delete for git push
+
+2023-02-14  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51437: Src/params.c, Test/K01nameref.ztst: Fix incorrectly-passed
+	test case, masked by unrelated bug.  Improve warnnestedvar message.
+
+2023-02-14  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51425: Src/exec.c, Test/E01OPTIONS: $(<...) shouldn't try to
+	open a file with NO_EXEC.
+
+2023-02-13  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51430: Src/Modules/parameter.c, Src/builtin.c, Src/params.c,
+	Test/K01nameref.ztst: Fix and test for regression of assignment
+	when using typeset command, fix output of typeset +m and
+	$parameters[ref], prevent segfault in typeset.
+
+2023-02-12  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51417: Src/params.c, Test/K01nameref.ztst: Check subscripts
+	in named reference values more rigorously.
+
+	* 51403: Doc/Zsh/builtins.yo, Doc/Zsh/expn.yo, Doc/Zsh/func.yo,
+	Doc/Zsh/grammar.yo, Doc/Zsh/params.yo, Test/K01nameref.ztst:
+	Tests and documentation for 51402, clean up some other tests.
+
+	* 51402: Src/builtin.c, Src/loop.c, Src/params.c, Src/zsh.h:
+	Add ksh/bash features (unset -n, for ref), readonly refs,
+	better error checking and messages, code injection safety,
+	allow references to $! $? $$ $- $0 $_
+
+	* 51375: Doc/Zsh/builtins.yo, Doc/Zsh/expn.yo, Doc/Zsh/params.yo,
+	Doc/Zsh/mod_parameter.yo: Clarify, fix typos, add indexing.
+
+	* 51374: Src/Modules/parameter.c, Src/params.c, Test/README,
+	Test/K01nameref.ztst: Expose named references in $parameters,
+	fix substitution error.
+
+	* 51362: Doc/Zsh/builtins.yo, Doc/Zsh/expn.yo, Doc/Zsh/params.yo,
+	Doc/Zsh/mod_parameter.yo: Begin documentation for named references.
+
+	* 51361: Test/K01nameref.ztst, Test/V10private.ztst: Tests
+	for 51360.
+
+	* 51360: Src/Modules/param_private.c, Src/Modules/parameter.c,
+	Src/builtin.c, Src/params.c, Src/subst.c, Src/zsh.h: Initial
+	implementation of named references.
+
+	* 51404: Src/jobs.c: Nullify filelist after deleting (fix segfault)
+
+2023-02-09  Oliver Kiddle  <opk@zsh.org>
+
+	* 51320, 51383: Src/Zle/zle_main.c, Src/Zle/complist.c,
+	Src/Zle/zle_tricky.c, Test/D01prompt.ztst,
+	Test/X04zlehighlight.ztst: fixes to prevent later reappearance
+	of old attributes
+
+2023-02-06  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51350: Src/subst.c, Test/D04parameter.ztst: the combination
+	${(S)...//#%...} needs to match as far as possible.
+
+2023-02-02  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* 51354: Doc/Zsh/params.yo: Fix markup in man page version
+
+2023-02-02  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51306: Doc/Zsh/expn.yo, Src/subst.c, Test/D04parameter.ztst:
+	error message in ${unset?...} should be expanded.
+
+	* 51307: Src/input.c, Src/parse.c, Test/A02alias.ztst: error
+	on attempt to expand alias in function definition name didn't
+	find the original alias and printed an extra error.
+
+2023-01-31  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51342: Etc/zsh-development-guide: update PARAMDEF description
+
+	* 51337: Doc/Zsh/expn.yo, Doc/Zsh/mod_parameter.yo: parameter
+	attributes cross-reference typeset equivalents (or lack thereof)
+
+2023-01-27  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* unposted (cribbed from users/28784 by Roman):
+	Test/D04parameter.ztst: Add XFail tests for substituting a
+	single-quoting backslash.
+
+2023-01-27  Shohei YOSHIDA  <syohex@gmail.com>
+
+	* 51330: Completion/Unix/Command/_python: Update python3
+	completion for version 3.11
+
+2023-01-24  Shohei YOSHIDA  <syohex@gmail.com>
+
+	* 51326: Completion/Unix/Command/_gcc: Improve -fsanitize
+	option completion
+
+2023-01-22  Shohei YOSHIDA  <syohex@gmail.com>
+
+	* 51322 (+ minor tweak): Completion/Unix/Command/_make: Update gnu
+	make completion for version 4.4
+
+2023-01-21  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51313: Completion/Unix/Command/_git: fix "git rerere forget"
+
+	* 51310: Src/Zle/zle_main.c: zle -F handlers preserve LASTWIDGET
+
+2023-01-16  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51278: Src/params.c, Test/D06subscript.ztst: result of (i)
+	subscript flag with zero-length string was inconsistent with
+	other cases.
+
+2023-01-11  Oliver Kiddle  <opk@zsh.org>
+
+	* 51297: Test/X04zlehighlight.ztst: update expected test results
+	to match more optimised escape sequences with recent changes
+
+	* Jörg Sommer: 51256: Completion/Unix/Command/_git:
+	Add --refetch to completions of git-fetch
+
+	* unposted: NEWS, Src/zsh.h, Completion/Zsh/Type/_ps1234: mention
+	attributes changes, fix renumbering mistake and allow completion
+	to offer prompt escapes for PROMPT_EOL_MARK
+
+	* 51295: Src/Zle/zle_utils.c: where the end of a region coincides
+	with the end of PREDISPLAY, don't extend it to include new text
+
+2023-01-10  Oliver Kiddle  <opk@zsh.org>
+
+	* 51292: Src/Zle/zle_utils.c: fix dynamic updates of
+	region_highlight to account for PREDISPLAY
+
+	* 51291: Doc/Zsh/zle.yo, Src/Zle/zle_refresh.c, Src/prompt.c:
+	support for highlighting ellipses in the line editor
+
+	* 51290: Src/Zle/zle_refresh.c: fix display of control
+	characters with SINGLE_LINE_ZLE set
+
+	* 51289: Src/Zle/zle_refresh.c, Src/prompt.c: don't disable
+	non-colour attributes in prompts for SINGLE_LINE_ZLE and remove
+	superfluous extra escapes to disable attributes
+
+	* 51281: Src/Zle/zle_main.c, Src/Zle/zle_refresh.c, Src/zsh.h:
+	keep track of attributes left on at the end of left and right
+	prompts and reapply them explicitly as appropriate
+
+	* 51280: Doc/Zsh/zle.yo, Src/Zle/zle_refresh.c, Src/init.c,
+	Src/prompt.c, Src/zsh.h: add support for italic and faint
+	fonts in the line editor
+
+	* 51258, 51272: Src/Modules/watch.c, Src/Zle/complist.c,
+	Src/Zle/zle.h, Src/Zle/zle_main.c, Src/Zle/zle_refresh.c,
+	Src/Zle/zle_tricky.c, Src/Zle/zle_utils.c, Src/builtin.c,
+	Src/init.c, Src/input.c, Src/loop.c, Src/prompt.c,
+	Src/subst.c, Src/utils.c, Src/zsh.h, Test/D01prompt.ztst,
+	Test/X04zlehighlight.ztst: refactor handling of terminal
+	attributes, removing OFF flags in zattr
+
+	* Nathan Houghton: 51276: Completion/Unix/Type/_diff_options:
+	Fix diff completion for non GNU / FreeBSD platforms
+
+2023-01-08  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* unposted: Src/Zle/zle_refresh.c: In a comment, replace a C
+	variables glob pattern with its matches, for greppability.
+
+2023-01-06  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* unposted (cf. users/28616):
+	Completion/Unix/Command/_subversion: _svnadmin: Add comment
+	noting a case that's not completed correctly.
+
+2022-12-31  Oliver Kiddle  <opk@zsh.org>
+
+	* Max Coplan: 51263: Doc/Zsh/files.yo: fix typo, an -> a
+
+	* Shohei YOSHIDA: 51255: Completion/Unix/Command/_ruby:
+	Update erb completion for version 4.0.2
+
+	* Shohei YOSHIDA: 51254: Completion/Unix/Command/_ruby:
+	Add irb completion for version 1.6.2
+
+	* Shohei YOSHIDA: 51253: Completion/Unix/Command/_ruby:
+	Update ruby completion for version 3.2.0
+
+	* Shohei YOSHIDA: 51233: Completion/Unix/Command/_gcc:
+	Update sanitizer list to GCC 12
+
+2022-12-30  Peter Stephenson  <p.w.stephenson@ntlworld.com>
+
+	* Daniel: 51249: Completion/Unix/Command/_tar: copy
+	--force-local option as needed for file names.
+
+2022-12-16  Oliver Kiddle  <opk@zsh.org>
+
+	* 51214: Doc/Zsh/builtins.yo, Src/builtin.c, Test/B04read.ztst,
+	Test/D07multibyte.ztst: with read -d and a delimiter that can't be
+	decoded into a character terminate input at the raw byte value
+
+	* Jun T.: 51207: Src/builtin.c, Test/B04read.ztst:
+	fix for read -d when the delimiter is a byte >= 0x80
+
+	* 51212: Etc/zsh-development-guide, Src/Modules/curses.c,
+	Src/Modules/stat.c, Src/Modules/zftp.c, Src/Modules/zpty.c,
+	Src/Modules/zutil.c, Src/Zle/compcore.c, Src/Zle/complete.c,
+	Src/Zle/complist.c, Src/Zle/zle.h, Src/Zle/zle_keymap.c,
+	Src/Zle/zle_main.c, Src/Zle/zle_thingy.c, Src/Zle/zle_utils.c,
+	Src/builtin.c, Src/exec.c, Src/glob.c, Src/hist.c, Src/init.c,
+	Src/input.c, Src/lex.c, Src/math.c, Src/module.c, Src/params.c,
+	Src/parse.c, Src/pattern.c, Src/prompt.c, Src/sort.c, Src/subst.c,
+	Src/utils.c, Src/zsh.h, Src/ztype.h, configure.ac: remove STOUC()
+	macro which served as a workaround for ancient compilers where
+	casts to unsigned char were broken
+
+	* 51215: Src/Zle/zle_keymap.c, Test/X03zlebindkey.ztst,
+	Test/X02zlevi.ztst: consume whole CSI sequences from the input
+	even where they aren't explicitly bound
+
+2022-12-15  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* unposted: Src/zsh.h: Follow-up to the last commit: Fix a typo
+	in a comment.
+
+	* unposted: Src/zsh.h: lextok: Add an explanatory comment with
+	a cross-reference.
+
+2022-12-13  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51210: Src/exec.c: Clear errflag before calling EXIT trap,
+	otherwise the trap is skipped for special-case errors in builtins
+
+	* Philippe Altherr: 51198: Doc/Zsh/options.yo: Clarify and expand
+	ERR_EXIT and ERR_RETURN documentation to include updated behavior
+
+	* Philippe Altherr: 51193: NEWS, README: Discuss ERR_EXIT changes
+
+2022-12-12  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 51134: Src/exec.c, Test/A01grammar.ztst: ! return doesn't
+	affect return status, only the (now irrelevant) local status
+	within the returning function.
+
+	* 51134: Doc/Zsh/options.yo: document interactions between
+	ERR_EXIT and ERR_RETURN and interactive shells.
+
+2022-12-09  Bart Schaefer  <schaefer@zsh.org>
+
+	* 51161: Src/exec.c: correct errno after closing xtrace FD
+
+	* Shohei YOSHIDA: 51111: Completion/Unix/Command/_global:
+	update completion for global to version 6.6.8
+
+	* 51047: Completion/Unix/Type/_canonical_paths: fix quoting
+	of completion matches when _canonical_paths -N option is used
+
+2022-12-09  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* 51144, 51146:
+	Functions/VCS_Info/Backends/VCS_INFO_get_data_git: vcs_info git:
+	stg: Extract patch descriptions
+
+2022-12-08  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* 51142: Functions/VCS_Info/Backends/VCS_INFO_get_data_git:
+	vcs_info git: Check the get-unapplied style as documented
+
+2022-12-08  Peter Grayson  <pete@jpgrayson.net>
+
+	* 51138: Functions/VCS_Info/Backends/VCS_INFO_get_data_git:
+	Updated StGit patch detection in vcs_info
+
+2022-12-06  Bart Schaefer  <schaefer@zsh.org>
+
+	* Shohei YOSHIDA: 51108: Completion/Unix/Command/_nkf: single
+	letter forms of Shift-JIS / EUC-JP options were reversed
+
+	* Atte Peltomäki: 51088: Functions/Misc/colors: typo in comment
+
+2022-12-03  Bart Schaefer  <schaefer@zsh.org>
+
+	* Philippe Altherr: 51094: Src/exec.c, Src/loop.c: consistent
+	use of bit-manipulation for noerrexit flag value changes
+
+	* Philippe Altherr: 51098: Src/exec.c, Src/loop.c, Src/zsh.h:
+	remove unreachable NOERREXIT_UNTIL_EXEC code and effects
+
+	* Philippe Altherr: 51076: Src/exec.c, Test/C03traps.ztst: fix
+	ERR_EXIT when used with "eval" or "source"; documentary comments
+
+	* Philippe Altherr: 51071: Src/exec.c, Test/C03traps.ztst: fix
+	ERR_RETURN when a function using && / || is called within another
+	statement using && / ||
+
+	* Philippe Altherr: 51001: Src/exec.c, Src/loop.c,
+	Test/C03traps.ztst: adjust handling of ERR_EXIT to more closely
+	align with POSIX and with other shells; add corresponding tests
+
+2022-12-02  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 51080: Src/glob.c: allow multibyte characters in glob qualifier
+	(u:uname:)
+
+	* 51079: Src/params.c, Test/D06subscript.ztst: metafy sep in the
+	array subscript flag (s:sep:) so that sep can contain \0 etc.
+
+2022-11-23  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* unposted (cf. 51016): Test/C01arith.ztst: Add a test case
+	for underscore-followed-by-digits in math context.
+
+2022-11-17  Oliver Kiddle  <opk@zsh.org>
+
+	* unposted (c.f. Norikatsu Shigemura: github #96):
+	Completion/Unix/Command/_cut: add missing local declaration
+
+	* github #87: Matt Koscica: Completion/Unix/Command/_tmux:
+	update options tmux 3.4
+
+	* github #95: Wu Zhenyu: Completion/Unix/Command/_mutt:
+	Add completions for neomutt
+
+	* unposted (c.f. Denis Bitouzé: users/28405):
+	Completion/Unix/Command/_tex: handle also lualatex
+
+	* 50934: Doc/Zsh/zle.yo, Src/Zle/zle.h, Src/Zle/zle_utils.c,
+	Src/Zle/zle_vi.c: use OSC 52 escape sequence when copying to
+	"* or "+ vi buffers
+
+2022-11-09  Bart Schaefer  <schaefer@zsh.org>
+
+	* 50928: Test/C03traps.ztst: scoping of ERR_RETURN in test
+	(most of this patch was not retained)
+
+	* 50922: Src/exec.c, Src/jobs.c: fix additional cases of signals
+	for current shell jobs on the right of a pipeline.  Backs out
+	part of 50874.
+
+2022-11-08  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* users/28338: Src/lex.c, Test/D08cmdsubst.ztst: edge case of an
+	edge case in command expansion of alias.
+
+2022-11-06  Bart Schaefer  <schaefer@zsh.org>
+
+	* 50874: Src/jobs.c: fix handling of tty signals for jobs in
+	the current shell when waiting for the right side of a pipeline.
+
+2022-11-02  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 50851: Doc/Zsh/options.yo, Src/exec.c, Src/options.c: restore
+	state (such as typtab) when returning from a function with
+	localoptions (but do not take care of EMACS/VI options).
+
+2022-10-31  Bart Schaefer  <schaefer@zsh.org>
+
+	* 50855: Doc/Zsh/builtins.yo, Doc/Zsh/params.yo: Clarify how
+	commands are hashed, and searched-for by "whence".
+
+2022-10-31  Peter Grayson  <pete@jpgrayson.net>
+
+	* 50844: Completion/Unix/Command/_stgit: Remove _stgit completion
+	script
+
+2022-10-25  Axel Beckert  <abe@deuxchevaux.org.org>
+
+	* 50840: Doc/Zsh/grammar.yo: Correct NO_MATCH to NOMATCH.
+
+2022-10-23  Bart Schaefer  <schaefer@zsh.org>
+
+	* users/28243: Doc/Zsh/builtins.yo: update "typeset +" doc
+
+2022-10-22  Bart Schaefer  <schaefer@zsh.org>
+
+	* 50714: Completion/Unix/Command/_git (_git-diff): also complete
+	in the 2nd argument position anything that could be in the 1st.
+
+2022-10-17  Peter Stephenson  <p.stephenson@samsung.com>
+
+	* 50786: Functions/Misc/add-zle-hook-widget: make match
+	etc. local when used in styles.
+
+2022-10-17  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* Wesley Schwengle: 50736: Src/Zle/compmatch.c: silence
+	use-after-free waring (gcc-12.2)
+
+2022-09-29  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 50671: Util/ztst-syntax.vim: enable spell check in *.ztst
+
+2022-09-28  Eric Cook  <llua@gmx.com>
+	* Bart Schaefer: 50399: Completion/Base/Widget/_complete_debug
+	Properly local scope PS4 change
+
+	* 50695: Completion/Unix/Command/_mysql_utils add --protocol
+	option
+
+2022-09-27  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 50668: Src/utils.c, Test/D09brace.ztst: treat 8bit characters
+	in charcter range correctly when multibyte is unset
+
+2022-09-26  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 50662: Test/ztst.zsh: unset LC_* for all the tests
+
+	* 50658 + test: Src/Modules/pcre.c, Test/V07pcre.ztst: Enable to
+	switch between C/UTF-8 locales in PCRE
+
+2022-09-25  Peter Stephenson  <p.w.stephenson@ntlworld.com>
+
+	* 50648: Functions/Misc/zcalc: Julian Prein: Use ZCALC_HISTFILE
+	where defined for zcalc history.
+
+2022-09-21  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* Nicholas Vinson: 50641: aczsh.m4, configure.ac: use 'int main()'
+	in test C-codes in configure
+
+2022-09-15  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 50629: Test/D07multibyte.ztst, Test/E01options.ztst,
+	Test/V07pcre.ztst, Test/X02zlevi.ztst, Test/X03zlebindkey.ztst,
+	Test/Y01completion.ztst, Test/ztst.zsh: do not use egrep in tests
+
+2022-08-28  Daniel Shahaf  <d.s@daniel.shahaf.name>
+
+	* unposted: Completion/Unix/Command/_imagemagick: Add *.svg
+	and *.webp files.
+
+2022-08-05  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* Felipe Contreras: 50435+50436 (+50444):
+	Completion/Unix/Command/_make: do not actually build anything.
+	Also include some performance improvements.
+
+2022-07-24  Jun-ichi Takimoto  <takimoto-j@kba.biglobe.ne.jp>
+
+	* 50421: Completion/Zsh/Context/_redirect: add missing context
+	as the 1st argument to _dispatch
+
+	* 50418: Src/zsh_system.h, configure.ac: use setenv(3)/getenv(3)
+	on newer macOS
+
+2022-07-16  Bart Schaefer  <schaefer@zsh.org>
+
+	* users/27852: Completion/Unix/Command/_python: Make a local copy
+	of $_compskip to avoid propagating outward any changes by _normal
+
 2022-06-21  Bart Schaefer  <schaefer@zsh.org>
 
+	* 50379 (tweaked per 50380): Src/jobs.c: fix off-by-one
+	side-effect of workers/49906 that broke $(jobs -l)
+
 	* 50368: Src/Modules/db_gdbm.c: adjust bitflags so local copies of
 	variables cannot mess with database file contents
 
@@ -281,7 +1907,7 @@
 
 	* 49960: Doc/Zsh/compsys.yo: Sort lists in zshcompsys.
 
-2022-04-05  Bart Schaefer  <schaefer@toltec-ubuntu>
+2022-04-05  Bart Schaefer  <schaefer@zsh.org>
 
 	* 49994: Src/glob.c: Single-byte equivalence of users/22601 and
 	workers/40891 for matching against zero-length strings
@@ -2182,7 +3808,7 @@
 	* github #53: James Pike: Completion/Unix/Type/_remote_files:
 	allow specifying directory name.
 
-2020-07-07  Bart Schaefer  <schaefer@brasslantern.com>
+2020-07-07  Bart Schaefer  <schaefer@zsh.org>
 
 	* 46189: Test/comptest: Ignore exit status of final zpty_flush
 
@@ -3741,7 +5367,7 @@
 	* 44779: Completion/Unix/Command/_git: completion for new
 	git switch and git restore commands
 
-2019-09-24  Bart Schaefer  <schaefer@brasslantern.com>
+2019-09-24  Bart Schaefer  <schaefer@zsh.org>
 
 	* unposted (see 44772): Functions/Zle/bracketed-paste-magic:
 	quote the string argument to zle -U
@@ -3878,7 +5504,7 @@
 	* unposted: Etc/FAQ.yo: typo. also updates to outdated notes on
 	multibyte support.
 
-2019-07-08  Bart Schaefer  <schaefer@brasslantern.com>
+2019-07-08  Bart Schaefer  <schaefer@zsh.org>
 
 	* 43755: Functions/Zle/smart-insert-last-word: (Belated commit)
 	Fix state management for repeat uses to avoid clobbering command
@@ -8408,7 +10034,7 @@ g
 
 2016-12-10  Barton E. Schaefer  <schaefer@zsh.org>
 
-	* 40134: Src/builtin.c, Src/Zle/compmatch.c: silence spurious
+	* 40143: Src/builtin.c, Src/Zle/compmatch.c: silence spurious
 	compiler warnings.
 
 2016-12-10  Daniel Shahaf  <d.s@daniel.shahaf.name>
diff --git a/Completion/BSD/Command/_chflags b/Completion/BSD/Command/_chflags
index 924b09acd..905aa0645 100644
--- a/Completion/BSD/Command/_chflags
+++ b/Completion/BSD/Command/_chflags
@@ -1,22 +1,31 @@
 #compdef chflags
 
-local args own='-g *(-u$EUID)'
+local own='-g *(-u$EUID)'
+local -a args recurse
 
 (( ! EUID || $+_comp_priv_prefix )) && own=
 
-if [[ $OSTYPE = (darwin|dragonfly|freebsd)* ]]; then
-  args=(
-    "-f[don't display diagnostic messages]"
-    '-v[verbose output]'
-  )
-fi
+case $OSTYPE in
+  (darwin|dragonfly|freebsd)*)
+    args=(
+      "-f[don't display diagnostic messages]"
+      '-v[verbose output]'
+    )
+  ;|
+  darwin*|freebsd*)
+    recurse=( "-x[don't cross mount points]" )
+  ;|
+  netbsd*)
+    args=( '-d[if the change requested would not alter the flags, attempt no change]' )
+  ;|
+esac
 
 _arguments -s -A "-*" : $args \
   ': :_file_flags' \
   '*:file:_files "$own"' \
   - opth \
   '-h[act on symlinks]' \
-  - optR \
+  - optR $recurse \
   '-R[recurse directories]' \
   '(-L -P)-H[follow symlinks on the command line (specify with -R)]' \
   '(-H -P)-L[follow all symlinks (specify with -R)]' \
diff --git a/Completion/BSD/Command/_freebsd-update b/Completion/BSD/Command/_freebsd-update
index 7dd907298..af37641e4 100644
--- a/Completion/BSD/Command/_freebsd-update
+++ b/Completion/BSD/Command/_freebsd-update
@@ -17,6 +17,7 @@ _arguments \
   '-d[store working files in workdir]:workdir:_files -/' \
   '-f[read configuration options from conffile]:conf file:_files' \
   '-F[force freebsd-update fetch to proceed where it normally would not]' \
+  '-j[operate on specified jail]: :_jails' \
   '-k[trust an RSA key with SHA256 of KEY]:RSA key' \
   '-r[specify the new release]:new release' \
   '-s[fetch files from the specified server or server pool]:server:_hosts' \
diff --git a/Completion/BSD/Command/_fw_update b/Completion/BSD/Command/_fw_update
index b01749f3f..84b5f808d 100644
--- a/Completion/BSD/Command/_fw_update
+++ b/Completion/BSD/Command/_fw_update
@@ -3,8 +3,10 @@
 _arguments -s -S -A "-*" \
   '(*)-a[install or update firmware for all drivers]' \
   '-d[delete drivers instead of adding them]' \
-  '-i[display information]' \
+  '-F[download firmware only]' \
   '-n[dry run]' \
-  '-p[use the firmware at specified path]:path:' \
+  '-p+[use the firmware at specified path]: : _alternative
+    "urls\:url\:_urls"
+    "directories\:path\:_directories"' \
   '*-v[verbose output]' \
   '(-a)*:driver:'
diff --git a/Completion/BSD/Command/_ipfw b/Completion/BSD/Command/_ipfw
index 49d0ef1e8..b910aa34d 100644
--- a/Completion/BSD/Command/_ipfw
+++ b/Completion/BSD/Command/_ipfw
@@ -1,7 +1,7 @@
-#compdef ipfw
+#compdef ipfw dnctl
 
 local word=$'/[^ \t\0]#[ \t\0]/' comma next pqs nat
-local -a actions address pathname ropts ca
+local -a actions address dummynet args ropts ca
 local -A opt_args nat_options
 
 _ipfw_tables() {
@@ -80,6 +80,46 @@ address=(
   \| \)
 )
 
+dummynet=(
+  $'/(pipe|queue|sched)[ \t\0]/' -'pqs=${match%?}' ':dummynet-commands:dummynet configuration:$ca pipe queue sched'
+  $word ': _message -e numbers number'
+  $word ':options:config:$ca config'
+  \( $'/bw[ \t\0]/'
+    \( $word ':bandwidths: :_numbers -M "m:{a-z}={A-Z}" bandwidth {K,M,G}{bit,Byte}/s'
+    \| $word ':devices:device:_net_interfaces -qS " "' \)
+  \| $'/delay[ \t\0]/' $word ': _message -e numbers "propagation delay (ms)"'
+  \| $'/burst[ \t\0]/' $word ': _message -e numbers "size (bytes)"'
+  \| $'/profile[ \t\0]/' $word ':files:file:_files -qS " "'
+  \| $'/pipe[ \t\0]/' $word ': _message -e pipes pipe'
+  \| $'/weight[ \t\0]/' $word ': _message -e weights "weight (1-100) [1]"'
+  \| $'/type[ \t\0]/-'
+    \( $'/fq_(pie|codel)[ \t\0]/'
+      \( $'/limit[ \t\0]/' $word ': _message -e numbers "limit (packets) [10240]"'
+      \| $'/flows[ \t\0]/' $word ': _message -e numbers "flow queues [1024]"'
+      \| $'/quantum[ \t\0]/' ':parameters:parameter:$ca -F line quantum limit flows' \) \#
+      '/[]/'
+    \| $word ':types:scheduling algorithm:$ca fifo wf2q+ rr qfq fq_codel fq_pie fq_codel' \)
+  \| $'/buckets[ \t\0]/' $word ': _message -e sizes "hash table size (16-65536)"'
+  \| $'/mask[ \t\0]/' $word ':mask-specifiers:mask specifier:$ca dst-ip dst-ip6 src-ip src-ip6 dst-port src-port flow-id proto all'
+  \| $'/plr[ \t\0]/' $word ': _message -e numbers "packet loss rate (0.0-1.0)"'
+  \| $'/queue[ \t\0]/' $word ': _message -e sizes "queue size"'
+  \| $'/(red|gred)[ \t\0]/' $word ': _message -e thresholds thresholds'
+  \| $'/codel[ \t\0]/'
+    \( $'/(target|interval)[ \t\0]/' $word ': _message -e times "time (ms)"'
+    \| $'/(ecn|noecn)[ \t\0]/' ':options:option:$ca -F line target interval ecn noecn' \) \#
+    '/[]/'
+  \| $'/pie[ \t\0]/'
+    \( $'/(target|tupdate|max_burst)[ \t\0]/' $word ': _message -e times "time"'
+    \| $'/(alpha|beta)[ \t\0]/' $word ': _message -e weights weight'
+    \| $'/max_ecnth[ \t\0]/' $word ': _message -e probabilities probability'
+    \| $word ':options:option:$ca -F line alpha beta max_burst max_ecnth {,no}{ecn,capdrop,drand} onoff dre ts' \) \#
+    '/[]/'
+  \| // '-[[ $pqs = pipe ]]' $'/noerror[ \t\0]/' ':options:option:$ca -F line bw delay burst profile buckets mask noerror plr queue red gred codel pie'
+  \| // '-[[ $pqs = queue ]]' $'/noerror[ \t\0]/' ':options:option:$ca -F line pipe weight buckets mask noerror plr queue red gred codel pie'
+  \| // '-[[ $pqs = sched ]]' $'/[]/' ':options:option:$ca -F line type bw delay burst profile'
+  \) \#
+)
+
 actions=(
   $'/[^\0]##\0(-[a-zA-Z0-9]##[ \t]#)#/' # skip over options, completed by _arguments but can
   \(                                    # be quoted in one argument which that doesn't handle
@@ -241,48 +281,14 @@ actions=(
         \| $'/redirect_proto[ \t\0]/' $word ':protocols:protocol:$ca sctp tcp udp'
           $word ': _message -e ip-addresses "IP address"'
           $word ': _message -e ip-addresses "IP address"'
-        \| $word ':parameters:config parameter:$ca ip if log deny_in same_ports unreg_only unreg_cgn reset reverse proxy_only skip_global redirect_port redirect_addr redirect_proto'
+        \| $'/port_range[ \t\0]/'
+          '/[0-9]#-/' ': _message -e ports lower'
+          $word ': _message -e ports upper'
+        \| $word ':parameters:config parameter:$ca ip if log deny_in same_ports unreg_only unreg_cgn reset reverse proxy_only skip_global redirect_port redirect_addr redirect_proto port_range'
         \) \#
       \| $'/show[ \t\0]/' $word ':actions:action:(config log)'
       \| '/[]/' ':commands:command:$ca config show' \)
-  \| # dummynet configuration
-    $'/(pipe|queue|sched)[ \t\0]/' -'pqs=${match%?}' ':dummynet-commands:dummynet configuration:$ca pipe queue sched'
-    $word ': _message -e numbers number'
-    $word ':options:config:$ca config'
-    \( $'/bw[ \t\0]/'
-      \( $word ':bandwidths: :_numbers -M "m:{a-z}={A-Z}" bandwidth {K,M,G}{bit,Byte}/s'
-      \| $word ':devices:device:_net_interfaces -qS " "' \)
-    \| $'/delay[ \t\0]/' $word ': _message -e numbers "propagation delay (ms)"'
-    \| $'/burst[ \t\0]/' $word ': _message -e numbers "size (bytes)"'
-    \| $'/profile[ \t\0]/' $word ':files:file:_files -qS " "'
-    \| $'/pipe[ \t\0]/' $word ': _message -e pipes pipe'
-    \| $'/weight[ \t\0]/' $word ': _message -e weights "weight (1-100) [1]"'
-    \| $'/type[ \t\0]/-'
-      \( $'/fq_(pie|codel)[ \t\0]/'
-        \( $'/limit[ \t\0]/' $word ': _message -e numbers "limit (packets) [10240]"'
-        \| $'/flows[ \t\0]/' $word ': _message -e numbers "flow queues [1024]"'
-        \| $'/quantum[ \t\0]/' ':parameters:parameter:$ca -F line quantum limit flows' \) \#
-        '/[]/'
-      \| $word ':types:scheduling algorithm:$ca fifo wf2q+ rr qfq fq_codel fq_pie fq_codel' \)
-    \| $'/buckets[ \t\0]/' $word ': _message -e sizes "hash table size (16-65536)"'
-    \| $'/mask[ \t\0]/' $word ':mask-specifiers:mask specifier:$ca dst-ip dst-ip6 src-ip src-ip6 dst-port src-port flow-id proto all'
-    \| $'/plr[ \t\0]/' $word ': _message -e numbers "packet loss rate (0.0-1.0)"'
-    \| $'/queue[ \t\0]/' $word ': _message -e sizes "queue size"'
-    \| $'/(red|gred)[ \t\0]/' $word ': _message -e thresholds thresholds'
-    \| $'/codel[ \t\0]/'
-      \( $'/(target|interval)[ \t\0]/' $word ': _message -e times "time (ms)"'
-      \| $'/(ecn|noecn)[ \t\0]/' ':options:option:$ca -F line target interval ecn noecn' \) \#
-      '/[]/'
-    \| $'/pie[ \t\0]/'
-      \( $'/(target|tupdate|max_burst)[ \t\0]/' $word ': _message -e times "time"'
-      \| $'/(alpha|beta)[ \t\0]/' $word ': _message -e weights weight'
-      \| $'/max_ecnth[ \t\0]/' $word ': _message -e probabilities probability'
-      \| $word ':options:option:$ca -F line alpha beta max_burst max_ecnth {,no}{ecn,capdrop,drand} onoff dre ts' \) \#
-      '/[]/'
-    \| // '-[[ $pqs = pipe ]]' $'/noerror[ \t\0]/' ':options:option:$ca -F line bw delay burst profile buckets mask noerror plr queue red gred codel pie'
-    \| // '-[[ $pqs = queue ]]' $'/noerror[ \t\0]/' ':options:option:$ca -F line pipe weight buckets mask noerror plr queue red gred codel pie'
-    \| // '-[[ $pqs = sched ]]' $'/[]/' ':options:option:$ca -F line type bw delay burst profile'
-    \) \#
+  \| $dummynet
   \| # sysctl shortcuts
     $'/(en|dis)able[ \t\0]/' ':sysctl-shortcuts:sysctl shortcut:$ca enable disable'
     $word ':values:value:(firewall altq one_pass debug verbose dyn_keepalive)'
@@ -292,11 +298,36 @@ actions=(
   \)
 )
 
-if (( $words[(I)-p*] )); then
-  pathname=( ':path:_files -P / -W /' )
-fi
+case $service in
+  ipfw)
+    _regex_arguments _ipfw_actions "$actions[@]"
+    args=(
+      '!-e' # nop for compatibility
+      '(-p)-a[show counter values when listing rules (implied by show)]'
+      '(-p)-b[show only the action and the comment]'
+      '-c[show rules in compact form]'
+      '(-p)-d[show dynamic rules in addition to static ones]'
+      '(-p)-D[act on dynamic states only]'
+      '-f[run without confirmation]'
+      '(-p)-i[format values as IP addresses in table listings]'
+      '-N[resolve addresses and service names in output]'
+      '-q[quiet output]'
+      '-S[show the set each rule belongs to]'
+      '(-p -T)-t[show timestamp of last match, ctime() format]'
+      '(-p -t)-T[show timestamp of last match as seconds since epoch]'
+      '(-a -b -d -D -i -s -t -T *)-p+[specify preprocessor]:preprocessor:_command_names -e'
+    )
+    if (( $words[(I)-p*] )); then
+      args+=( ':path:_files -P / -W /' )
+    fi
+  ;;
+  dnctl)
+    _regex_arguments _ipfw_actions \
+      $'/[^\0]##\0(-[a-zA-Z0-9]##[ \t]#)#/' \
+      "$dummynet[@]"
+  ;;
+esac
 
-_regex_arguments _ipfw_actions "$actions[@]"
 
 if [[ -prefix *[$' \t']* ]]; then
   # This allows from things like ipfw "-n add..."
@@ -304,22 +335,10 @@ if [[ -prefix *[$' \t']* ]]; then
   return
 fi
 
-_arguments -s $pathname \
-  '(-p)-a[show counter values when listing rules (implied by show)]' \
-  '(-p)-b[show only the action and the comment]' \
-  '-c[show rules in compact form]' \
-  '(-p)-d[show dynamic rules in addition to static ones]' \
-  '(-p)-D[act on dynamic states only]' \
-  '-f[run without confirmation]' \
+_arguments -s $args \
   '(- *)-h[display syntax summary]' \
-  '(-p)-i[format values as IP addresses in table listings]' \
   '-n[only check syntax, make no changes]' \
-  '-N[resolve addresses and service names in output]' \
-  '-q[quiet output]' \
-  '-S[show the set each rule belongs to]' \
   '(-p)-s+[sort pipes by field]:field (negative reverses):((0\:unsorted 1\:packets 2\:bytes 3\:total\ packets 4\:total\ bytes))' \
-  '(-p -T)-t[show timestamp of last match, ctime() format]' \
-  '(-p -t)-T[show timestamp of last match as seconds since epoch]' \
-  '(-a -b -d -D -i -s -t -T *)-p+[specify preprocessor]:preprocessor:_command_names -e' \
+  '-v[verbose]' \
   '*:::actions:= _ipfw_actions'
 
diff --git a/Completion/BSD/Command/_jexec b/Completion/BSD/Command/_jexec
index 6a2d05a81..cd99ebe91 100644
--- a/Completion/BSD/Command/_jexec
+++ b/Completion/BSD/Command/_jexec
@@ -6,7 +6,7 @@ _jexec_normal() {
   # relative paths are relative to the jail's root
   path=( "$(_call_program paths jls -j $words[1] path)"/$^path )
   shift 1 words; (( CURRENT-- ))
-  _normal
+  _normal -p $service
 }
 
 _jexec() {
diff --git a/Completion/BSD/Command/_ldap b/Completion/BSD/Command/_ldap
index 8fa17e2f8..181e6b0d0 100644
--- a/Completion/BSD/Command/_ldap
+++ b/Completion/BSD/Command/_ldap
@@ -80,8 +80,8 @@ else
         '-x[use simple authentication]' \
         '-Z[use StartTLS]' \
         '-z+[specify maximum number of results or 0 for no limit]:size limit [0]:' \
-        '::filter:' \
-        '*:attribute:'
+        '1: :_ldap_filters' \
+        '*: :_ldap_attributes'
       ;;
   esac
 fi
diff --git a/Completion/BSD/Command/_pfctl b/Completion/BSD/Command/_pfctl
index 812e52bdb..8063eb504 100644
--- a/Completion/BSD/Command/_pfctl
+++ b/Completion/BSD/Command/_pfctl
@@ -91,7 +91,10 @@ case $OSTYPE in
     )
   ;|
   freebsd*)
-    args+=( '-P[display ports numerically]' )
+    args+=(
+      '-M[kill matching states in the opposite direction]'
+      '-P[display ports numerically]'
+    )
   ;;
 esac
 
diff --git a/Completion/BSD/Command/_rcctl b/Completion/BSD/Command/_rcctl
index 6cfebf420..457c3eb85 100644
--- a/Completion/BSD/Command/_rcctl
+++ b/Completion/BSD/Command/_rcctl
@@ -3,7 +3,7 @@
 local context state line
 local -a actions lsarg subcmds variables
 
-actions=(check reload restart start stop)
+actions=(configtest check reload restart start stop)
 subcmds=(disable enable get getdef ls order set)
 variables=(class flags status timeout user)
 lsarg=(
@@ -46,6 +46,6 @@ case $service in
       '*:argument:'
     ;;
   ${(~j:|:)actions}|disable|enable)
-    _arguments "*:service to $words[2]:_services"
+    _arguments "*:service to ${words[2]}:_services"
     ;;
 esac
diff --git a/Completion/BSD/Command/_sockstat b/Completion/BSD/Command/_sockstat
index 1d7973db7..f372fe1b3 100644
--- a/Completion/BSD/Command/_sockstat
+++ b/Completion/BSD/Command/_sockstat
@@ -21,6 +21,14 @@ case $OSTYPE in
       '-w[use wider field size for displaying addresses]'
     )
   ;|
+  freebsd<13->.*)
+    args+=(
+      '-C[display the congestion control module]'
+      '-i[display the inp_gencnt]'
+      "-n[don't resolve numeric UIDs to user names]"
+      '-q[quiet mode, do not print the header line]'
+    )
+  ;|
   freebsd*)
     for proto in ${${(M)${(f)"$(</etc/protocols)"}##[a-z0-9]*}}; do
       case $proto in
diff --git a/Completion/Base/Completer/_approximate b/Completion/Base/Completer/_approximate
index dcd8b2776..96860b5a7 100644
--- a/Completion/Base/Completer/_approximate
+++ b/Completion/Base/Completer/_approximate
@@ -12,7 +12,6 @@
 
 local _comp_correct _correct_expl _correct_group comax cfgacc match
 local oldcontext="${curcontext}" opm="$compstate[pattern_match]"
-local dounfunction
 integer ret=1
 
 if [[ "$1" = -a* ]]; then
@@ -44,34 +43,31 @@ fi
 
 _tags corrections original
 
-# Otherwise temporarily define a function to use instead of
-# the builtin that adds matches. This is used to be able
-# to stick the `(#a...)' in the right place (after an
-# ignored prefix).
+# Otherwise temporarily define a function to use instead of the builtin that
+# adds matches. This is used to be able to stick the `(#a...)' in the right
+# place (after an ignored prefix).
 #
-# Current shell structure for use with "always", to make sure
-# we unfunction the compadd.
+# Current shell structure for use with "always", to make sure we unfunction our
+# compadd and restore any compadd function defined previously.
 {
-if (( ! $+functions[compadd] )); then
-  dounfunction=1
-  compadd() {
-    local ppre="$argv[(I)-p]"
-
-    [[ ${argv[(I)-[a-zA-Z]#U[a-zA-Z]#]} -eq 0 &&
-       "${#:-$PREFIX$SUFFIX}" -le _comp_correct ]] && return
-
-    if [[ "$PREFIX" = \~* && ( ppre -eq 0 || "$argv[ppre+1]" != \~* ) ]]; then
-      PREFIX="~(#a${_comp_correct})${PREFIX[2,-1]}"
-    else
-      PREFIX="(#a${_comp_correct})$PREFIX"
-    fi
+_shadow -s _approximate compadd
+compadd() {
+  local ppre="$argv[(I)-p]"
 
-    (( $_correct_group && ${${argv[1,(r)-(|-)]}[(I)-*[JV]]} )) &&
-        _correct_expl[_correct_group]=${argv[1,(r)-(-|)][(R)-*[JV]]}
+  [[ ${argv[(I)-[a-zA-Z]#U[a-zA-Z]#]} -eq 0 &&
+      "${#:-$PREFIX$SUFFIX}" -le _comp_correct ]] && return
 
-    builtin compadd "$_correct_expl[@]" "$@"
-  }
-fi
+  if [[ "$PREFIX" = \~* && ( ppre -eq 0 || "$argv[ppre+1]" != \~* ) ]]; then
+    PREFIX="~(#a${_comp_correct})${PREFIX[2,-1]}"
+  else
+    PREFIX="(#a${_comp_correct})$PREFIX"
+  fi
+
+  (( $_correct_group && ${${argv[1,(r)-(|-)]}[(I)-*[JV]]} )) &&
+      _correct_expl[_correct_group]=${argv[1,(r)-(-|)][(R)-*[JV]]}
+
+  compadd@_approximate "$_correct_expl[@]" "$@"
+}
 
 _comp_correct=1
 
@@ -115,7 +111,7 @@ while [[ _comp_correct -le comax ]]; do
 done
 
 } always {
-    [[ -n $dounfunction ]] && (( $+functions[compadd] )) && unfunction compadd
+  _unshadow
 }
 
 (( ret == 0 )) && return 0
diff --git a/Completion/Base/Completer/_prefix b/Completion/Base/Completer/_prefix
index 74be5f47d..aea2f7863 100644
--- a/Completion/Base/Completer/_prefix
+++ b/Completion/Base/Completer/_prefix
@@ -49,13 +49,8 @@ for tmp in "$comp[@]"; do
     fi
 
     if [[ "$tmp" != _prefix ]] && "$tmp"; then
-      [[ compstate[nmatches] -gt 1 ]] && return 0
-      compadd -U -i "$IPREFIX" -I "$ISUFFIX" - "${compstate[unambiguous]%$suf}x"
-      compstate[list]=
-      if [[ -n $compstate[unambiguous] ]]; then
-        compstate[insert]=unambiguous
-      else
-        compstate[insert]=0
+      if [[ -n $compstate[old_list] || ${compstate[unambiguous]%$suf} == $PREFIX ]]; then
+        compstate[to_end]=match
       fi
       return 0
     fi
diff --git a/Completion/Base/Core/_main_complete b/Completion/Base/Core/_main_complete
index 169ca1f40..408a66ee3 100644
--- a/Completion/Base/Core/_main_complete
+++ b/Completion/Base/Core/_main_complete
@@ -93,19 +93,15 @@ fi
 if [[ -z "$compstate[quote]" ]]; then
   if [[ -o equals ]] && compset -P 1 '='; then
     compstate[context]=equal
-  elif [[ "$PREFIX" != */* && "$PREFIX[1]" = '~' ]]; then
-    if [[ "$PREFIX" = '~['[^\]]# ]]; then
-      # Inside ~[...] should be treated as a subscript.
-      compset -p 2
-      # To be consistent, we ignore all but the contents of the square
-      # brackets.
-      compset -S '\]*'
-      compstate[context]=subscript
-      [[ -n $_comps[-subscript-] ]] && $_comps[-subscript-] && return
-    else
-      compset -p 1
-      compstate[context]=tilde
-    fi
+  elif [[ "$PREFIX" = \~\[[^]]# ]]; then
+    # Inside ~[...] should be treated as a subscript.
+    compset -p 2
+    # To be consistent, we ignore all but the contents of the square brackets.
+    compset -S '\]*'
+    compstate[context]=subscript
+  elif [[ "$PREFIX" = \~[^/]# ]]; then
+    compset -p 1
+    compstate[context]=tilde
   fi
 fi
 
diff --git a/Completion/Base/Utility/_numbers b/Completion/Base/Utility/_numbers
index 97bb8b4c8..069fc75a4 100644
--- a/Completion/Base/Utility/_numbers
+++ b/Completion/Base/Utility/_numbers
@@ -73,7 +73,7 @@ elif [[ -prefix $~pat || $PREFIX = $~partial ]]; then
     zformat -f suffix "$suffixfmt" "x:${${argv[i+1]#:}%%:*}" \
         "X:${${argv[i+1]#:}#*:}" "d:${#${argv[i+1]}[1]#:}" \
 	i:i r:$(( $# - i - 1))
-    suffixes+="$suffix"
+    suffixes+="${suffix//\%/%%}"
   done
   [[ -n $suffixes ]] && formats+=( x:$suffixes )
 
diff --git a/Completion/Base/Utility/_shadow b/Completion/Base/Utility/_shadow
index 5b0f79c36..9e78af38f 100644
--- a/Completion/Base/Utility/_shadow
+++ b/Completion/Base/Utility/_shadow
@@ -8,7 +8,7 @@
 #    }
 #    # Invoke callers of fname
 #  } always {
-#    _unshadow fname
+#    _unshadow
 #  }
 ## Alternate usage:
 # {
@@ -19,7 +19,7 @@
 #   }
 #   # Invoke callers of fname
 # } always {
-#   _unshadow -s suffix fname
+#   _unshadow
 # }
 ##
 
@@ -33,36 +33,62 @@ zmodload zsh/parameter # Or what?
 # This probably never comes up, but protect ourself from recursive call
 # chains that may duplicate the top elements of $funcstack by creating
 # a counter of _shadow calls and using it to make shadow names unique.
-typeset -gHi _shadowdepth=0
+builtin typeset -gHi .shadow.depth=0
+builtin typeset -gHa .shadow.stack
 
 # Create a copy of each fname so that a caller may redefine
 _shadow() {
-  local -A fsfx=( -s ${funcstack[2]}:${functrace[2]}:$((_shadowdepth+1)) )
-  local fname
+  emulate -L zsh
+  local -A fsfx=( -s ${funcstack[2]}:${functrace[2]}:$((.shadow.depth+1)) )
+  local fname shadowname
+  local -a fnames
   zparseopts -K -A fsfx -D s:
   for fname; do
-    local shadowname=${fname}@${fsfx[-s]}
-    (( ${+functions[$fname]} )) &&
-      builtin functions -c $fname $shadowname
+    shadowname=${fname}@${fsfx[-s]}
+    if (( ${+functions[$shadowname]} ))
+    then
+      # Called again with the same -s, just ignore it
+      continue
+    elif (( ${+functions[$fname]} ))
+    then
+      builtin functions -c -- $fname $shadowname
+      fnames+=(f@$fname)
+    elif (( ${+builtins[$fname]} ))
+    then
+      eval "function -- ${(q-)shadowname} { builtin ${(q-)fname} \"\$@\" }"
+      fnames+=(b@$fname)
+    else
+      eval "function -- ${(q-)shadowname} { command ${(q-)fname} \"\$@\" }"
+      fnames+=(c@$fname)
+    fi
   done
-  ((_shadowdepth++))
+  [[ -z $REPLY ]] && REPLY=${fsfx[-s]}
+  builtin set -A .shadow.stack ${fsfx[-s]} $fnames -- ${.shadow.stack}
+  ((.shadow.depth++))
 }
 
 # Remove the redefined function and shadowing name
 _unshadow() {
-  local -A fsfx=( -s ${funcstack[2]}:${functrace[2]}:${_shadowdepth} )
-  local fname
-  zparseopts -K -A fsfx -D s:
-  for fname; do
-    local shadowname=${fname}@${fsfx[-s]}
-    if (( ${+functions[$shadowname]} )); then
-      builtin functions -c $shadowname $fname
-      builtin unfunction $shadowname
-    elif (( ${+functions[$fname]} )); then
-      builtin unfunction $fname
+  emulate -L zsh
+  local fname shadowname fsfx=${.shadow.stack[1]}
+  local -a fnames
+  [[ -n $fsfx ]] || return 1
+  shift .shadow.stack
+  while [[ ${.shadow.stack[1]?no shadows} != -- ]]; do
+    fname=${.shadow.stack[1]#?@}
+    shadowname=${fname}@${fsfx}
+    if (( ${+functions[$fname]} )); then
+      builtin unfunction -- $fname
     fi
+    case ${.shadow.stack[1]} in
+      (f@*) builtin functions -c -- $shadowname $fname ;&
+      ([bc]@*) builtin unfunction -- $shadowname ;;
+    esac
+    shift .shadow.stack
   done
-  ((_shadowdepth--))
+  [[ -z $REPLY ]] && REPLY=$fsfx
+  shift .shadow.stack
+  ((.shadow.depth--))
 }
 
 # This is tricky.  When we call _shadow recursively from autoload,
diff --git a/Completion/Base/Widget/_complete_debug b/Completion/Base/Widget/_complete_debug
index 94fd4accd..d8b1bd837 100644
--- a/Completion/Base/Widget/_complete_debug
+++ b/Completion/Base/Widget/_complete_debug
@@ -19,7 +19,7 @@ integer debug_fd=-1
     setopt localoptions no_ignorebraces
     debug_indent=( '%'{3..20}'(e. .)' )
   }
-  local PROMPT4 PS4="${(j::)debug_indent}+%N:%i> "
+  local PROMPT4="$PROMPT4" PS4="${(j::)debug_indent}+%N:%i> "
   setopt xtrace
   : $ZSH_NAME $ZSH_VERSION
   ${1:-_main_complete}
diff --git a/Completion/Darwin/Command/_open b/Completion/Darwin/Command/_open
index 2563e5eb5..1c693dfb8 100644
--- a/Completion/Darwin/Command/_open
+++ b/Completion/Darwin/Command/_open
@@ -25,14 +25,20 @@ _open() {
     '(: * -)--args[pass remaining arguments to application]:*:::argument' \
     '(-a -b -e -f -R -t)-b+[specify application bundle identifier]: :->bundle-ids' \
     '(-a -b -e -f -R -t)-e[open with TextEdit]' \
+    '*--env[add the environment variable of the launched application]:env_var=value:_parameters -g "*export*" -qS=' \
     '(-h)-f[open standard input with TextEdit or specified application]' \
     '(-R)-F[open application with fresh state]' \
-    '-g[do not bring application to foreground]' \
+    '(-j)-g[do not bring application to foreground]' \
     '(-f)-h[open library header file]' \
+    '(-g)-j[launch the app hidden]' \
     '(-R)-n[always open new instance of application]' \
     '(-a -b -e -f -F -n -s -t -W --args)-R[reveal in Finder]' \
     '(-R)-s+[specify SDK name/version]: :->sdks' \
+    '--stdin[launch the application with stdin connected to the given file]:file:_files' \
+    '--stdout[launch the application with stdout connected to the given file]:file:_files' \
+    '--stderr[launch the application with stderr connected to the given file]:file:_files' \
     '(-a -b -e -f -R -t)-t[open with default text editor]' \
+    '-u[open URL with whatever application claims the url scheme]:url:_urls' \
     '(-R)-W[wait for application to exit]' \
     '(-f)*: :->files' \
   && ret=0
diff --git a/Completion/Darwin/Command/_otool b/Completion/Darwin/Command/_otool
index c3fc70b91..b6a30a730 100644
--- a/Completion/Darwin/Command/_otool
+++ b/Completion/Darwin/Command/_otool
@@ -13,6 +13,7 @@ _arguments \
   '-D[display just the internal name of shared lib]' \
   '-s[display the contents of the specified section]:segment name: :section name: ' \
   '-t[display the contents of (__TEXT,__text) section]' \
+  '-x[display the content of every __text section found in the file]' \
   '-d[display the contents of (__DATA,__data) section]' \
   '-o[display the contents of __OBJC segment]' \
   '-r[display the relocation entries]' \
@@ -25,6 +26,9 @@ _arguments \
   '-G[display the data in code table]' \
   '-C[display the linker optimization hints]' \
   '-P[print the info_plist section as strings]' \
+  '-dyld_info[print bind and rebase information used by dyld]' \
+  '-dyld_opcodes[print raw dyld bind and rebase opcodes present in a final linked binary]' \
+  '-chained_fixups[print raw chained fixup data present in a final linked binary]' \
   '-p[with -t and -v/V: start disassembly from the specified symbol]:symbol name: ' \
   '-v[display verbosely (symbolically) when possible]' \
   '-V[display disassembled operands symbolically]' \
@@ -34,7 +38,8 @@ _arguments \
   '-function_offsets[with disassembly, print decimal offset from the last label]' \
   '-j[with disassembly, print opcode bytes]' \
   "-Q[use otool's disassembler]" \
-  '-arch[select the specified architecture from a universal file]:arch:(i386 x86_64)' \
+  '-addr_slide=[add an arbitrary slide to each pointer value when it is displayed]:slide size' \
+  '-arch[select the specified architecture from a universal file]:arch:(i386 x86_64 x86_64h arm64 arm64e all)' \
   '-m[object file names are not assumed to be in archive(member) syntax]' \
   '(- *)--version[print version of otool]' \
   '*:file:_object_files' && return 0
diff --git a/Completion/Darwin/Command/_shortcuts b/Completion/Darwin/Command/_shortcuts
new file mode 100644
index 000000000..5e15f0a07
--- /dev/null
+++ b/Completion/Darwin/Command/_shortcuts
@@ -0,0 +1,88 @@
+#compdef shortcuts
+
+_shortcuts() {
+  local curcontext="$curcontext"
+  local -a line state
+
+  _arguments -C \
+    "1: :->subcommand" \
+    "*:: :->args"
+
+  case $state in
+  subcommand)
+    _values "subcommand" \
+      "run[run a shortcut]" \
+      "list[list your shortcuts]" \
+      "view[view a shortcut in shortcuts]" \
+      "sign[sign a shortcut file]" \
+      "help[show subcommand help information]"
+    ;;
+  args)
+    case ${line[1]} in
+    run)
+      _shortcuts-run
+      ;;
+    list)
+      _shortcuts-list
+      ;;
+    view)
+      _shortcuts-view
+      ;;
+    sign)
+      _shortcuts-sign
+      ;;
+    help)
+      _shortcuts-help
+      ;;
+    esac
+    ;;
+  esac
+}
+
+_shortcuts-run() {
+  _arguments \
+    ":shortcut name or identifier:$(_shortcut_options)" \
+    {-i,--input-path}'[specify input to provide to the shortcut]:input path:_files' \
+    {-o,--output-path}'[specify where to write the shortcut output, if applicable]:output path:_files' \
+    '--output-type[specify type to output data in]:output type (Universal Type Identifier format)' \
+    {-h,--help}'[show help information]'
+}
+
+_shortcuts-list() {
+  _arguments \
+    {-f,--folder-name}"[specify folder name or identifier to list shortcuts in, or \"none\" to list shortcuts not in a folder]:folder name:$(_shortcut_folder_options)" \
+    '--folders[list folders instead of shortcuts]' \
+    '--show-identifiers[show identifiers with each result]' \
+    {-h,--help}'[show help information]'
+}
+
+_shortcuts-view() {
+  _arguments \
+    ":shortcut name:$(_shortcut_options)" \
+    {-h,--help}'[show help information]'
+}
+
+_shortcuts-sign() {
+  _arguments \
+    {-m,--mode}'[specify signing mode]:mode [people-who-know-me]:(anyone people-who-know-me)' \
+    {-i,--input}'[specify shortcut file to sign]:input:_files -g "*.shortcut(-.)"' \
+    {-o,--output}'[specify output path for the signed shortcut file]:output:_files -g "*.shortcut(-.)"' \
+    {-h,--help}'[show help information]'
+}
+
+_shortcuts-help() {
+  _arguments \
+    ":subcommand:(run list view sign help)"
+}
+
+# utilities
+
+_shortcut_options() {
+  echo "($(shortcuts list | sed 's/ /\\ /g'))"
+}
+
+_shortcut_folder_options() {
+  echo "($(shortcuts list --folders | sed 's/ /\\ /g') none)"
+}
+
+_shortcuts "$@"
diff --git a/Completion/Darwin/Command/_softwareupdate b/Completion/Darwin/Command/_softwareupdate
index 6054fd768..9ac9b9cd2 100644
--- a/Completion/Darwin/Command/_softwareupdate
+++ b/Completion/Darwin/Command/_softwareupdate
@@ -1,75 +1,110 @@
 #compdef softwareupdate
 
-_softwareupdate_ignored_update_name() {
-  if [[ -z "$_softwareupdate_ignored_updates" ]]; then
-    local res="$(_call_program pkgs softwareupdate --ignored)"
-    _softwareupdate_ignored_updates=("${(Qs/, /)${${res#Current ignored updates: \(}%\)}}")
-  fi
-  if (( ${#_softwareupdate_ignored_updates} > 0 )); then
-    _wanted pkgs expl "ignored package" compadd -a _softwareupdate_ignored_updates && return 0
-  fi
-  return 1
+# rebuild cache for available updates everyday (ad hoc)
+_softwareupdate_caching_policy() {
+  local -a newer=( "$1"(Nmd-1) )
+  return $#newer
 }
 
-_softwareupdate_update_name() {
-  local name line
-  if [[ -z "$_softwareupdate_updates" ]]; then
+# completes available updates (with description)
+
+_softwareupdate_update_names () {
+  local name line update_policy ret=1
+  local cache_id=softwareupdate-updates
+  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
+  if [[ -z "$update_policy" ]]; then
+    zstyle ":completion:${curcontext}:" cache-policy \
+                                      _softwareupdate_caching_policy
+ fi
+ if { [[ ! -v _softwareupdate_updates ]] || _cache_invalid $cache_id } &&
+    ! _retrieve_cache $cache_id; then
+    # Output format of 'softwareupdate --list' seems to be not stable,
+    # but at least on macOS 12 and 13 it contains the following two lines
+    # for each update:
+    #* Label: update name (may contain spaces)
+    #        Title: description of the update (single TAB before Title:)
+    # softwareupdate(1) manpage says the '*' before the Label: is replaced
+    # by '-' for non-recommended updates (but I've never seen it).
     _softwareupdate_updates=()
-    for line in ${(f)"$(_call_program pkgs softwareupdate --list)"}; do
-      if [[ $line == '   '* ]]; then
-        name="${line#   ? }"
-      elif [[ -n "$name" ]]; then
-        _softwareupdate_updates+=("$name:${line#	}")
-        name=""
+    for line in ${(f)"$(_call_program updates softwareupdate --list)"}; do
+      if [[ $line = [-\*]\ Label:\ (#b)(*) ]]; then
+        # add '*' or '-' in front of the name; this will be removed later
+        name=$line[1]$match[1]
+      elif [[ -n $name && $line = $'\t'Title:\ (#b)(*) ]]; then
+        _softwareupdate_updates+=( $name:$match[1] )
+        name=
       fi
     done
+    _store_cache $cache_id _softwareupdate_updates
   fi
-  if (( ${#_softwareupdate_updates} > 0 )); then
-    _describe -t pkgs "update name" _softwareupdate_updates && return 0
-  fi
-  return 1
+  # recommended and non-recommended updates
+  local rec=( ${${_softwareupdate_updates:#-*}#\*} )
+  local non=( ${${(M)_softwareupdate_updates:#-*}#-} )
+  _describe -t updates "update" rec && ret=0
+  _describe -t non-recommended-updates "non-recommended update" non && ret=0
+  return ret
+}
+
+# completes versions of available macOS full installer (with description)
+
+_softwareupdate_installer_versions () {
+  local versions=()
+  for line in ${(f)"$(_call_program installer-versions
+                        softwareupdate --list-full-installers 2>/dev/null)"}; do
+    if [[ $line = \*\ Title:\ *\ Version:\ (#b)([0-9.]##)* ]]; then
+      versions+=( ${match[1]}:${line#*Title: } )
+    fi
+  done
+  _describe -t insteller-versions "version" versions
 }
 
+# main completion script
+
 _softwareupdate() {
-  local context state line expl
-  typeset -A opt_args
+  local -a specs
 
-  _arguments -R \
-    '(-h --help -l --list)-q[quiet mode]' \
-    {-l,--list}'[list all available updates]:*:' \
-    {-d,--download}'[download to directory set in InternetConfig]:*:' \
-    {-i,--install}'[install (requires root)]:*: :->install' \
-    '--ignored[show or manage ignored updates list (per-user)]:*:: :->ignored' \
-    '--schedule[scheduler preferences (per-user)]:automatic checking:(on off)' \
-    {-h,--help}'[print command usage]:*:' && return 0
+  if (( ${words[(I)(-i|--install)]} == 0 )); then
+    specs=(
+      '--no-scan[do not scan when listing or installing updates]'
+      '--product-types[limit a scan to a particular product type only]:list of product types'
+      '--products[a comma separated list of product keys to operate on]:list of product keys'
+      '--force[force an operation to complete]'
+      '--agree-to-license[agree to the software license agreement without user interaction]'
+      '--verbose[enable verbose output]'
+      '(* -)'{-h,--help}'[print command usage]:*:'
 
-  case "$state" in
-    install)
-      _arguments \
-        '(* -a --all)'{-a,--all}'[all available active updates]' \
-        '(* -r --req)'{-r,--req}'[all required active updates]' \
-        '*:update name:_softwareupdate_update_name' && return 0
-      ;;
-    ignored)
-      local -a ignored_subcmd
-      ignored_subcmd=(add remove)
+      + '(operation)'
 
-      if (( CURRENT == 1 )); then
-        _describe -t commands "subcommand" ignored_subcmd && return 0
-      fi
-      case $words[1] in
-        add)
-          _softwareupdate_update_name && return 0
-          ;;
-        remove)
-          _arguments \
-            '(* -a --all)'{-a,--all}'[all available active updates]' \
-            '*:update name:_softwareupdate_ignored_update_name' && return 0
-          ;;
-      esac
-      ;;
-  esac
-  return 1
+      {-l,--list}'[list all available updates]'
+      {-d,--download}'[download but not install specified updates]:*: : _softwareupdate_update_names'
+      {-i,--install}'[download and install specified updates]'
+      '(* -)--list-full-installers[list the available macOS installers]'
+      '(* -)--fetch-full-installer[install the latest recommended macOS installer]: :(--full-installer-version): : _softwareupdate_installer_versions'
+      '--install-rosetta[install Rosetta 2 (Apple Silicon only)]'
+      '(* -)--schedule[returns the per-machine automatic check preference]'
+      '--background[trigger a background scan and update operation]'
+      '(* -)--dump-state[log the internal state of the SU daemon to /var/log/install.log]'
+      '--evaluate-products[evaluate a list of product keys specified by the --products option]'
+      '--history[show the install history]'
+    )
+  else    # if -i/--install is already on the command line
+    specs=(
+      !{-i,--install}
+      '(-R --restart)'{-R,--restart}'[automatically restart if required to complete installation]'
+      '--stdinpass[password to authenticate as an owner (Apple Silicon only)]'
+      '--user[local username to authenticate as an owner (Apple Silicon only)]'
+      '*: : _softwareupdate_update_names'
+
+      + '(select-updates)'
+
+      '(*)'{-a,--all}'[all updates that are applicable to your system]'
+      '(*)'{-r,--recommended}'[all updates recommended for your system]'
+      '(*)--os-only[only macOS updates]'
+      '(*)--safari-only[only Safari updates]'
+    )
+  fi
+
+  _arguments -s : $specs
 }
 
 _softwareupdate "$@"
diff --git a/Completion/Darwin/Command/_sw_vers b/Completion/Darwin/Command/_sw_vers
index 11814e0b0..415d3a05c 100644
--- a/Completion/Darwin/Command/_sw_vers
+++ b/Completion/Darwin/Command/_sw_vers
@@ -1,6 +1,11 @@
 #compdef sw_vers
 
+# Only options with a single dash '-' are accepted on Monterey or older,
+# but both a single and double dashes are accepted on Ventura (or newer).
+# We may replace '-' by '--' when Monterey fades out.
+
 _arguments : \
   '(-)-buildVersion[display build version only]' \
   '(-)-productName[display product name only]' \
-  '(-)-productVersion[display product version only]'
+  '(-)-productVersion[display product version only]' \
+  '(-)-productVersionExtra[display rapid security response version only]'
diff --git a/Completion/Darwin/Command/_system_profiler b/Completion/Darwin/Command/_system_profiler
index fe197579d..0fd8b473b 100644
--- a/Completion/Darwin/Command/_system_profiler
+++ b/Completion/Darwin/Command/_system_profiler
@@ -4,17 +4,13 @@ typeset -A opt_args
 local context state state_descr line
 local -a _data_types
 
-# TODO: Should this be static?  Calling `system_profiler -listDataTypes` takes
-# about 0.07-0.08 secs on my machine.  Does this list ever change (between
-# different versions of OS X)?
-_data_types=( SP{AirPort,Applications,Audio,Bluetooth,Camera,CardReader,Component,ConfigurationProfile,DeveloperTools,Diagnostics,DisabledSoftware,DiscBurning,Displays,Ethernet,Extensions,FibreChannel,FireWire,Firewall,Fonts,Frameworks,Hardware,HardwareRAID,InstallHistory,Logs,ManagedClient,Memory,Network,NetworkLocation,NetworkVolume,PCI,ParallelATA,ParallelSCSI,Power,PrefPane,Printers,PrintersSoftware,SAS,SPI,SerialATA,Software,StartupItem,Storage,SyncServices,Thunderbolt,USB,UniversalAccess,WWAN}DataType )
-# the dynamic alternative is:
-#_data_types=( ${${(f)"$(_call_program path system_profiler -listDataTypes 2>/dev/null)"}[2,-1]} )
+_data_types=( ${${(f)"$(_call_program data-types system_profiler -listDataTypes 2>/dev/null)"}[2,-1]} )
 
 _arguments \
   '(- *)-usage' \
   '(- *)-listDataTypes[lists the available datatypes]' \
-  '(-listDataTypes -usage)-xml[generate xml output]' \
+  '(-listDataTypes -usage -json)-xml[generate xml output]' \
+  '(-listDataTypes -usage -xml)-json[generate json output]' \
   '(-listDataTypes -usage)-detailLevel[level of detail for the report]:detail level:(mini basic full)' \
-  '(-listDataTypes -usage)-timeout+[maximum time to wait in seconds]' \
+  '(-listDataTypes -usage)-timeout+[maximum time to wait in seconds(0 means no timeout)]:timeout seconds' \
   '(-listDataTypes -usage)*:data type:'"($_data_types)"
diff --git a/Completion/Darwin/Command/_trash b/Completion/Darwin/Command/_trash
deleted file mode 100644
index 658716432..000000000
--- a/Completion/Darwin/Command/_trash
+++ /dev/null
@@ -1,22 +0,0 @@
-#compdef trash
-
-# We only provide completion for Ali Rantakari's trash utility. There are/were a
-# few others floating around with that name, but this is the one available as
-# `trash` in Homebrew and MacPorts
-_pick_variant ali='(Rantakari|hasseg)' other --version && {
-  # The hidden options here are options to rm that trash silently (and
-  # undocumentedly) ignores. Some options are not made mutually exclusive where
-  # they technically could be, for compatibility with aliases, etc.
-  _arguments -s -S -A '-*' : \
-    '!-'{d,f,i,r,P,R,W} \
-    '(: * -F -l -v)-e[empty trash]' \
-    '-F[use Finder instead of system API]' \
-    '(: * -e -F -s -y)-l[list items in trash]' \
-    '(: * -F -l -v)-s[securely empty trash]' \
-    '-v[increase output verbosity]' \
-    '-y[skip confirmation prompts (with -e or -s)]' \
-    '*: :_files'
-  return
-}
-
-_default
diff --git a/Completion/Debian/Command/_apt b/Completion/Debian/Command/_apt
index 494d3bf82..19f818c27 100644
--- a/Completion/Debian/Command/_apt
+++ b/Completion/Debian/Command/_apt
@@ -422,15 +422,14 @@ _apt-cmd () {
 	/$'[^\0/=]#='/ /'[]'/ ':apt-package-versions:package version:_apt_versions_of_binary_package' \| \
       \) \
     \) \| \
-    /$'(remove|reinstall|purge)\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
+    /$'((|auto)(remove|purge)|reinstall)\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
     /$'upgrade\0'/ \| \
     /$'autoclean\0'/ \| \
     /$'changelog\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" avail' \# \| \
-    /$'autoremove\0'/ \| \
     /$'full-upgrade\0'/ \| \
     /$'dist-upgrade\0'/ \| \
     /$'edit-sources\0'/ \| \
-    /"[]"/ ':argument-1::compadd "$expl_action[@]" list search showsrc show depends rdepends policy update install reinstall download source build-dep remove upgrade full-upgrade dist-upgrade edit-sources autoclean changelog autoremove purge'
+    /"[]"/ ':argument-1::compadd "$expl_action[@]" list search showsrc show depends rdepends policy update install reinstall download source build-dep remove upgrade full-upgrade dist-upgrade edit-sources autoclean changelog autopurge autoremove purge'
 
   _apt-cmd () {
     local expl_action expl_packages subcmd
@@ -487,19 +486,16 @@ _apt-get () {
 	/$'[^\0/=]#='/ /'[]'/ ':apt-package-versions:package version:_apt_versions_of_binary_package' \
       \) \
     \) \| \
-    /$'remove\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
-    /$'purge\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
+    /$'(|auto)(purge|remove)\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
     /$'dist-upgrade\0'/ \| \
     /$'dselect-upgrade\0'/ \| \
     /$'clean\0'/ \| \
     /$'autoclean\0'/ \| \
     /$'changelog\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" avail' \# \| \
     /$'check\0'/ \| \
-    /$'autoremove\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
     /$'help\0/' \| \
-    /$'markauto\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
-    /$'unmarkauto\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
-    /"[]"/	':argument-1::compadd "$expl_action[@]" update upgrade install remove purge dist-upgrade dselect-upgrade clean autoclean changelog check source build-dep autoremove help markauto unmarkauto download'
+    /$'(|un)markauto\0'/ /$'[^\0]#\0'/ ':packages::_deb_packages "$expl_packages[@]" installed' \# \| \
+    /"[]"/	':argument-1::compadd "$expl_action[@]" update upgrade install remove purge dist-upgrade dselect-upgrade clean autoclean changelog check source build-dep autopurge autoremove help markauto unmarkauto download'
 
   _apt-get () {
     local expl_action expl_packages
diff --git a/Completion/Debian/Command/_sbuild b/Completion/Debian/Command/_sbuild
index a32b5e8c5..459738d5d 100644
--- a/Completion/Debian/Command/_sbuild
+++ b/Completion/Debian/Command/_sbuild
@@ -124,7 +124,7 @@ _sbuild() {
     '--aspcud-criteria=[Optimization for aspcud]:criteria' \
     '(--resolve-alternatives --no-resolve-alternatives)--resolve-alternatives[allow alternatives in Build-Depends*]' \
     '(--resolve-alternatives --no-resolve-alternatives)--no-resolve-alternatives[disallow alternatives in Build-Depends*]' \
-    '--extra-package=[make a package or directory available to the resolver]:package:_files -g "*deb(-.)' \
+    '--extra-package=[make a package or directory available to the resolver]:package:_files -g "*deb(-.)"' \
     '--extra-repository=[add a repository to the resolver]:url' \
     '--extra-repository-key=[add key to the resolver]:key:_files -g "*.asc(-.)"' \
     '--build-path=[place to build the package inside chroot]:path:_files -/' \
diff --git a/Completion/Linux/Command/_btrfs b/Completion/Linux/Command/_btrfs
index 1d87fd83a..d8b97a200 100644
--- a/Completion/Linux/Command/_btrfs
+++ b/Completion/Linux/Command/_btrfs
@@ -8,16 +8,16 @@ groups=( subvolume filesystem device scrub balance inspect-internal property
          quota qgroup replace rescue check restore send receive
          help version )
 cmds_1=( create delete list snapshot get-default set-default find-new show sync help )
-cmds_2=( df du show sync defragment resize label usage help )
+cmds_2=( df du show sync defragment resize label mkswapfile usage help )
 cmds_3=( add delete remove ready scan stats usage help )
 cmds_4=( start cancel resume status help )
 cmds_5=( start pause cancel resume status )
-cmds_6=( dump-{super,tree} {inode,logical,subvolid}-resolve min-dev-size rootid tree-stats help )
+cmds_6=( dump-{super,tree} {inode,logical,subvolid}-resolve map-swapfile min-dev-size rootid tree-stats help )
 cmds_7=( get set list )
 cmds_8=( enable disable rescan help )
-cmds_9=( assign remove create destroy show limit help )
+cmds_9=( assign remove create clear-stale destroy show limit help )
 cmds_10=( start status cancel help )
-cmds_11=( chunk-recover fix-device-size super-recover zero-log create-control-device )
+cmds_11=( chunk-recover clear-uuid-tree fix-device-size super-recover zero-log create-control-device )
 
 _arguments -C -A "-*" "$args[@]" \
   '(- *)--help[print help information]' \
@@ -25,6 +25,7 @@ _arguments -C -A "-*" "$args[@]" \
   '(-v --verbose -q --quiet --help --version)'{-v,--verbose}'[verbose output of operation]' \
   '(-v --verbose -q --quiet --help --version)'{-q,--quiet}'[suppress all messages except errors]' \
   '(--help --version)--format=[specify output format]:format:(text json)' \
+  '(--help --version)--log=[set log level]:level:(default info verbose debug quiet)' \
   '(--version)1: :->groups' \
   '2: :->cmds' \
   '*:: :->args' && ret=0
@@ -151,7 +152,7 @@ while (( $#state )); do
         filesystem:defragment)
           args+=( '!-v'
             '-r[defragment files recursively]'
-            '-c+[compress files while defragmenting]::compression algorithm:(zlib lzo zstd)'
+            '-c-[compress files while defragmenting]::compression algorithm:(zlib lzo zstd)'
             '-r[defragment files recursively]'
             '-f[flush after defragmenting]'
             '-s[start position]: :_numbers -u bytes -d "beginning of file" offset K M G T P E'
@@ -171,6 +172,13 @@ while (( $#state )); do
             '1: :_guard "^-*" uuid or label'
           )
         ;;
+        filesystem:mkswapfile)
+          args+=(
+            '-s[size]: :_numbers -d "2GiB" size K M G T P E'
+            '(-u --uuid)'{-u,--uuid}'[specify a uuid to use]:uuid:(clear random time)'
+            ':file:_files'
+          )
+        ;;
         filesystem:usage) args+=( '-T[show data in tabular format]' );;
         device:(add|delete|ready|remove))
           args+=(
@@ -194,6 +202,7 @@ while (( $#state )); do
           args+=(
             '(-c --check)'{-c,--check}'[return non-zero if any stat counter is not zero]'
             '(-z --reset)'{-z,--reset}'[reset stats when done]'
+            '-T[show current stats in tabular format]'
             "1:device or mountpoint:_files -g '*(-%,/)'"
           )
         ;;
@@ -233,7 +242,7 @@ while (( $#state )); do
         ;;
         balance:status) args+=( '!-v' '!--verbose' '1:path:_files -/' );;
         balance:(pause|cancel|resume)) args+=( '1:path:_files -/' );;
-        property:set) args+=( '3:value' );&
+        property:set) args+=( '-f[force the change]' '3:value' );&
         property:get) args+=( '2:property:(ro label compression)' );&
         property:list)
           args+=(
@@ -244,8 +253,9 @@ while (( $#state )); do
         quota:(enable|disable)) args+=( '1:path:_files -/' );;
         quota:rescan)
           args+=(
-            '-s[show status of currently running rescan]'
-            '-w[wait for rescan to finish]'
+            '(-s --status)'{-s,--status}'[show status of currently running rescan]'
+            '(-w --wait -W --wait-norescan)'{-w,--wait}'[wait for rescan to finish]'
+            '(-w --wait -W --wait-norescan)'{-w,--wait-norescan}'[wait for rescan to finish without starting it]'
             '1:path:_files -/'
           )
         ;;
@@ -268,11 +278,14 @@ while (( $#state )); do
             '-F[list impacted qgroups \(include ancestral qgroups\)]'
             '-f[list impacted qgroups \(exclude ancestral qgroups\)]'
             '--sort=-[sort qgroups]:sort:_values -s , sort \
-              qgroupid rfer excl max_rfer max_excl'
+              qgroupid rfer excl max_rfer max_excl path'
             '--sync[do filesystem sync before getting information]'
             '1:path:_files -/'
           )
         ;;
+        qgroup:clear-stale)
+          args+=( '(-q --quiet)'{-q,--quiet}'[print only errors]' '1:path:_files -/' )
+        ;;
         qgroup:limit)
           args+=(
             '-c[limit amount of data after compression]'
@@ -287,6 +300,7 @@ while (( $#state )); do
             '-r[read from specified source device only]:srcdev:_files'
             '-f[force overwriting of target]'
             "-B[don't background]"
+            '(-K --nodiscard)'{-K,--nodiscard}"[don't perform whole device TRIM]"
             ':srcdev or devid:_files'
             ':target:_files'
             ':path:->mounts'
@@ -332,6 +346,12 @@ while (( $#state )); do
             '2:filesystem path:_files -/'
           )
         ;;
+        inspect*:map-swapfile)
+          args+=(
+            '(-r --resume-offset)'{-r,--resume-offset}'[print only the value suitable as resume offset for file /sys/power/resume_offset]'
+            ':file:_files'
+          )
+        ;;
         inspect*:min*) args+=( '--id[specify the device id to query]:device id [1]' );;
         inspect*:rootid) args+=( '1:path:_files -/' );;
         inspect*:tree*) args+=( '-b[print raw numbers in bytes]' );;
@@ -395,6 +415,8 @@ while (( $#state )); do
             '*-c[use snapshot as clone source]:clone:_files -/'
             '-f[specify output file]:file:_files'
             '--no-data[send in NO_FILE_DATA mode]'
+            '--proto[specify protocol version]:version'
+            '--compressed-data[send data that is compressed on the filesystem directly without decompressing it]'
             '1:subvolume:_files -/'
           )
         ;;
@@ -405,6 +427,7 @@ while (( $#state )); do
             '(-C --chroot)'{-C,--chroot}'[confine the process to destination path using chroot(1)]'
             '(-E --max-errors)'{-E,--max-errors}'[terminate as soon as specified number of errors occur]:errors [1]'
             '(--dump)-m[specify root mount point of the destination filesystem]:mount point:_directories'
+            '--force-decompress[if the stream contains compressed data, always decompress it]'
             '(-m)--dump[dump stream metadata, one line per operation]'
             '1:mount:->mounts'
           )
diff --git a/Completion/Linux/Command/_chcon b/Completion/Linux/Command/_chcon
deleted file mode 100644
index 2d523f287..000000000
--- a/Completion/Linux/Command/_chcon
+++ /dev/null
@@ -1,24 +0,0 @@
-#compdef chcon
-
-local ign
-
-(( $#words > 2 )) && ign='!'
-_arguments -C -s -S \
-  '(-h --no-dereference)--dereference[dereference symlinks]' \
-  '(-h --no-dereference --dereference)'{-h,--no-dereference}'[operate on symlinks themselves]' \
-  '(1 -u --user -r --role  -l --range -t --type)--reference=[copy security context of specified file]:file:_files' \
-  '(1 --reference -u --user)'{-u+,--user=}'[set user in the target security context]: :_selinux_users' \
-  '(1 --reference -r --role)'{-r+,--role=}'[set role in the target security context]: :_selinux_roles' \
-  '(1 --reference -t --type)'{-t+,--type=}'[set type in the target security context]: :_selinux_types' \
-  '(1 --reference -l --range)'{-l+,--range=}'[set range in the target security context]:selinux range' \
-  '(--recursive -R)'{--recursive,-R}'[recurse subdirectories]' \
-  '(-v --verbose)'{-v,--verbose}'[output a diagnostic for every file processed]' \
-  '(-H -L -P)-H[follow symlinks on the command line]' \
-  '(-H -L -P)-L[follow all symlinks]' \
-  "(-H -L -P)-P[don't follow symlinks (default)]" \
-  '!(--preserve-root)--no-preserve-root' \
-  "--preserve-root[fail to operate recursively on '/']" \
-  '(--reference -u --user -r --role  -l --range -t --type)1:security context:_selinux_contexts' \
-  "${ign}--help[display help information]" \
-  "${ign}--version[display version information]" \
-  '*:file:_files'
diff --git a/Completion/Linux/Command/_chrt b/Completion/Linux/Command/_chrt
index 6789b66cf..5431b0799 100644
--- a/Completion/Linux/Command/_chrt
+++ b/Completion/Linux/Command/_chrt
@@ -62,7 +62,7 @@ elif (( CURRENT == 1 )); then
 else
   shift words
   (( CURRENT-- ))
-  _normal && ret=0
+  _normal -p $service && ret=0
 fi
 
 return ret
diff --git a/Completion/Linux/Command/_cpupower b/Completion/Linux/Command/_cpupower
index 6763bdd12..d342b69d9 100644
--- a/Completion/Linux/Command/_cpupower
+++ b/Completion/Linux/Command/_cpupower
@@ -95,7 +95,7 @@ case $state in
           '-i+[measurement interval]:interval (seconds)'
           '-c[schedule on every core]'
           '-v[increase verbosity]'
-          '*:::command: _normal'
+          '*:::command: _normal -p $service'
         )
       ;;
     esac
diff --git a/Completion/Linux/Command/_ethtool b/Completion/Linux/Command/_ethtool
index 95a8bbfb6..3e3fc0b1d 100644
--- a/Completion/Linux/Command/_ethtool
+++ b/Completion/Linux/Command/_ethtool
@@ -4,7 +4,7 @@ local curcontext="$curcontext"
 local -a state line expl cmds
 local -A opt_args
 
-_arguments -C \
+_arguments -C -A "-*" \
   '--debug[turn on debugging messages]:mask:((1\:parser\ information))' \
   '--json[output results in JSON]' \
   '(-I --include-statistics)'{-I,--include-statistics}'[include command-related statistics in the output]' \
@@ -59,12 +59,21 @@ _arguments -C \
   '--cable-test[perform cable test and report the results]' \
   '--cable-test-tdr[perform cable test and report Time Domain Reflectometer data]' \
   '--show-tunnels[show tunnel-related device capabilities and state]' \
+  '--show-module[show transceiver module settings]' \
+  '--set-module[set transceiver module settings]' \
+  '--get-plca-cfg[get PLCA configuration]' \
+  '--set-plca-cfg[set PLCA configuration]' \
+  '--get-plca-status[get PLCA status information]' \
+  '--show-mm[show MAC merge layer state]' \
+  '--set-mm[set MAC merge layer parameters]' \
+  '--show-pse[show settings for power sourcing equipment]' \
+  '--set-pse[set power sourcing equipment settings]' \
   '--monitor[listen to netlink notifications and displays them]::command:(
     --all -s --change -k --show-features --show-offload -K
     --features --offload  --show-priv-flags --set-priv-flags -g --show-ring
     -G --set-ring -l --show-channels -L --set-channels -c --show-coalesce
     -C --coalesce -a --show-pause -A --pause --show-eee --set-eee
-    --cable-test --cable-test-tdr
+    --cable-test --cable-test-tdr --show-module --set-module
   )' && return
 
 if [[ -n $state ]]; then
@@ -79,22 +88,30 @@ if [[ -n $state ]]; then
     fi
   ;;
   autoneg|adaptive-[rt]x|raw|hex|sg|tso|ufo|gso|lro|eee|tx-lpi|downshift) ;&
-  fast-link-down|energy-detect-power-down|mode)
+  cqe-mode-[rt]x|fast-link-down|energy-detect-power-down|mode) ;&
+  [tr]x-push|enable|*-enabled)
     _wanted onoff expl 'enabled' compadd off on
   ;;
   rx-usecs|rx-frames|rx-usecs-irq|rx-frames-irq|tx-usecs|tx-frames) ;&
   tx-usecs-irq|tx-frames-irq|stats-block-usecs|pkt-rate-low|rx-usecs-low) ;&
   rx-frames-low|tx-usecs-low|tx-frames-low|pkt-rate-high|rx-usecs-high) ;&
-  rx-frames-high|tx-usecs-high|tx-frames-high|sample-interval|dmac|rx-mini) ;&
-  rx-jumbo|offset|length|magic|value|phyad|proto|tos|tclass|l4proto|src-port) ;&
+  rx-frames-high|tx-usecs-high|tx-frames-high|sample-interval|dmac) ;&
+  tx-aggr-max-bytes|tx-aggr-max-frame|tx-aggr-time-usec) ;&
+  rx-mini|rx-jumbo|rx-buf-len|cqe-size|tx-push-buf-len) ;&
+  offset|length|magic|value|phyad|proto|tos|tclass|l4proto|src-port) ;&
   dst-port|spi|l4data|vlan-etype|vlan|user-def|action|vf|queue|loc) ;&
   page|bank|i2c|first|last|step|pair|lanes) ;&
-  rx-copybreak|tx-copybreak|pfc-prevention-tout) ;&
-  other|combined|tx-timer|count|msecs)
+  rx-copybreak|tx-copybreak|tx-buf-size|pfc-prevention-tout) ;&
+  other|combined|tx-timer|count|msecs) ;&
+  node-id|node-cnt|to-tmr|burst-cnt|burst-tmr) ;&
+  tx-min-frag-size)
     _message -e numbers 'number'
   ;;
+  podl-pse-admin-control)
+    _wanted values expl 'value' compadd enable disable
+  ;;
   speed)
-        _wanted -x speed expl 'speed' compadd 10 100 1000
+    _wanted -x speed expl 'speed' compadd 10 100 1000
   ;;
   duplex)
     _wanted duplex expl 'duplex mode' compadd half full
@@ -166,8 +183,14 @@ if [[ -n $state ]]; then
   context)
     _message -e contexts 'RSS context'
   ;;
+  power-mode-policy)
+    _wanted policies expl 'policy' compadd high auto
+  ;;
   *)
     case ${${(Mk)opt_args:#cmd?*}[1]#cmd?-} in
+    -a|--show-pause)
+      _arguments '--src=-:source:(aggregate emac pmac)'
+    ;;
     -A|--pause)
       _values -S ' ' -w 'pause parameter' \
         'autoneg[specify if pause autonegotiation is enabled]' \
@@ -177,14 +200,16 @@ if [[ -n $state ]]; then
     -C|--coalesce)
       _wanted settings expl 'coalescing setting' compadd -F line -M 'r:|-=* r:|=*' - \
         adaptive-{r,t}x {r,t}x-{usecs,frames}{,-irq,-high,-low} \
-        stats-block-usecs pkt-rate-{low,high} sample-interval
+        stats-block-usecs pkt-rate-{low,high} sample-interval cqe-mode-{r,t}x \
+        tx-aggr-{max-bytes,max-frames,time-usecs}
     ;;
     -G|--set-ring)
       _values -S ' ' -w 'ring parameter' \
         'rx[change number of ring entries for the RX ring]' \
         'rx-mini[change number of ring entries for the RX Mini ring]' \
         'rx-jumbo[change number of ring entries for the RX Jumbo ring]' \
-        'tx[change number of ring entries for the TX ring]'
+        'tx[change number of ring entries for the TX ring]' \
+        rx-buf-len cqe-size tx-push rx-push tx-push-buf-len
     ;;
     -d|--register-dump)
       _values -S ' ' -w 'option' \
@@ -216,7 +241,9 @@ if [[ -n $state ]]; then
       (( CURRENT = 4 )) && _message -e length 'duration (seconds)'
     ;;
     -S|--statistics)
-      _arguments '(-)--all-groups' '(-)--groups:eth-phy: :eth-mac: :eth-ctrl: :rmon'
+      _arguments '(-)--all-groups' \
+        '(-)--groups:eth-phy: :eth-mac: :eth-ctrl: :rmon' \
+        '--src=-:source:(aggregate emac pmac)' \
     ;;
     -t|--test)
       _values -S ' ' -w 'test mode' \
@@ -318,7 +345,7 @@ if [[ -n $state ]]; then
     ;;
     --[gs]et-tunable)
       _wanted options expl tunable compadd rx-copybreak tx-copybreak \
-          pfc-prevention-tout
+          tx-buf-size pfc-prevention-tout
     ;;
     --reset)
       _wanted components expl component compadd flags dedicated all \
@@ -341,6 +368,13 @@ if [[ -n $state ]]; then
     --cable-test-tdr)
       _wanted options expl 'distance options' compadd first last step pair
     ;;
+    --set-module)
+      _wanted options expl tunable compadd power-mode-policy
+    ;;
+    --set-plca-cfg)
+      _wanted options expl tunable compadd enable node-id node-cnt \
+          to-tmr burst-cnt burst-tmr
+    ;;
     esac
   ;;
   esac
diff --git a/Completion/Linux/Command/_findmnt b/Completion/Linux/Command/_findmnt
index 0c832364d..b29372c39 100644
--- a/Completion/Linux/Command/_findmnt
+++ b/Completion/Linux/Command/_findmnt
@@ -26,6 +26,7 @@ _arguments -s -C \
   '(H -o --output)--output-all[output all available columns]' \
   '(H -p --poll)'{-p+,--poll=}'[monitor changes in /proc/self/mountinfo]::action:(mount umount remount move)' \
   '(H --real)--pseudo[print only pseudo-filesystems]' \
+  '(H)--shadowed[print only filesystems over-mounted by another filesystem]' \
   '(H -R --submounts)'{-R,--submounts}'[print recursively all submounts]' \
   '(H --pseudo)--real[print only real filesystems]' \
   '(H -S --source :)'{-S+,--source=}'[specify the mount source]: :->sources' \
@@ -35,9 +36,11 @@ _arguments -s -C \
   '(H -U --uniq)'{-U,--uniq}'[ignore filesystems with duplicated mount targets]' \
   '(H -u --notruncate)'{-u,--notruncate}'[do not truncate text in columns]' \
   '(H -v --nofsroot)'{-v,--nofsroot}'[do not print \[/dir\] in the SOURCE column]' \
+  '(H -y --shell -n --noheadings)'{-y,--shell}'[use column names usable as shell variable identifiers]' \
   '(H -w --timeout)'{-w+,--timeout}'[specify timeout for --poll]:milliseconds: ' \
   '(H -x --verify)'{-x,--verify}'[check mount table content]' \
   '(H)--verbose[print more information]' \
+  '(H)--vfs-all[print all VFS options]' \
   '(H)1: :->sources_targets' \
   '(H)2:: :->targets' \
   + '(format)' \
diff --git a/Completion/Linux/Command/_free b/Completion/Linux/Command/_free
index 6d74e4a0d..a0da97446 100644
--- a/Completion/Linux/Command/_free
+++ b/Completion/Linux/Command/_free
@@ -3,6 +3,7 @@
 _arguments -s \
   '(-l --lohi)'{-l,--lohi}'[show detailed low and high memory statistics]' \
   '(-t --total)'{-t,--total}'[show total for RAM + swap]' \
+  '(-v --committed)'{-v,--committed}'[show committed memory and commit limit]' \
   '(-w --wide)'{-w,--wide}'[wide mode]' \
   '(-s --seconds)'{-s,--seconds}'[specify the delay between display]:seconds: ' \
   '(-c --count)'{-c+,--count=}'[specify the display count]:count: ' \
diff --git a/Completion/Linux/Command/_fusermount b/Completion/Linux/Command/_fusermount
index d55eca29c..24f9a8018 100644
--- a/Completion/Linux/Command/_fusermount
+++ b/Completion/Linux/Command/_fusermount
@@ -1,4 +1,4 @@
-#compdef fusermount
+#compdef fusermount fusermount3
 
 local expl context state line
 typeset -A opt_args
diff --git a/Completion/Linux/Command/_gpasswd b/Completion/Linux/Command/_gpasswd
index 24fe361b0..d5d16ebba 100644
--- a/Completion/Linux/Command/_gpasswd
+++ b/Completion/Linux/Command/_gpasswd
@@ -5,7 +5,7 @@ _arguments -s \
   '(-d --delete -a --add)'{-d,--delete}'[remove user from group]: : _users' \
   '(-)'{-h,--help}'[display help]' \
   '(-Q --root)'{-Q,--root}'[specify directory to chroot into]: : _files -/' \
-  '(-r --remove-password)'{-r,--remove-password}'[remove the group password]' \
+  '(-r --delete-password)'{-r,--delete-password}'[remove the group password]' \
   '(-R --restrict)'{-R,--restrict}'[restrict access to GROUP to its members]' \
   '(-M --members -A --administrators)'{-M,--members}'[set the list of members of GROUP]: :_sequence _users' \
   '(-A --administrators -M --members)'{-A,--administrators}'[set the list of admins for GROUP]: :_sequence _users' \
diff --git a/Completion/Linux/Command/_ionice b/Completion/Linux/Command/_ionice
index ba403ca56..9989cd6a9 100644
--- a/Completion/Linux/Command/_ionice
+++ b/Completion/Linux/Command/_ionice
@@ -28,7 +28,7 @@ if [[ -n $state ]]; then
   elif (( $+opt_args[args--u] || $+opt_args[args---uid] )); then
     _message -e uids 'user id'
   else
-    _normal && ret=0
+    _normal -p $service && ret=0
   fi
 fi
 
diff --git a/Completion/Linux/Command/_iptables b/Completion/Linux/Command/_iptables
index 27c801da1..892c48710 100644
--- a/Completion/Linux/Command/_iptables
+++ b/Completion/Linux/Command/_iptables
@@ -1,7 +1,7 @@
-#compdef iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore
+#compdef iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore arptables ebtables
 
-local curcontext="$curcontext" state line expl i ret=1
-local -a cmds rcmds ropts rules states prev args
+local curcontext="$curcontext" i ret=1
+local -a state line expl cmds rcmds ropts rules states prev args
 
 case $service in
   iptables-save | ip6tables-save)
@@ -24,12 +24,12 @@ cmds=(
   -P --policy -E --rename-chain -h --help -V --version
 )
 ropts=(
-  -p --protocol -s --src --source -d --dst --destination -j --jump -i
+  -p --proto --protocol -s --src --source -d --dst --destination -j --jump -i
   --in-interface -o --out-interface -f --fragment -c --set-counters
 )
 
 prev=( ${words[1,CURRENT-1]} )
-case ${prev[${prev[(I)-p|--protocol]}+1]}; in
+case ${prev[${prev[(I)-p|--proto|--protocol]}+1]}; in
   tcp)
     args=(
       '--tcp-flags[match based on TCP flags in a packet]: :->tcp-flags: :->tcp-flags'
@@ -92,7 +92,42 @@ while
   (( i=words[(ib.i.)-m|--match]+1 ))
 (( i<CURRENT )); do
   case ${words[i]}; in
-    ah) args+=( '--ahspi[match SPIs in AH header]:*^!:spi' ) ;;
+    addrtype)
+      args+=(
+        '--src-type[match if the source address is of given type]:type:->address-types'
+        '--dst-type[match if the destination address is of given type]:type:->address-types'
+        '(--limit-iface-out)--limit-iface-in[limit to interface the packet is coming in]'
+        '(--limit-iface-in)--limit-iface-out[limit to interface the packet is going out]'
+      )
+    ;;
+    ah)
+      args+=( '--ahspi[match SPIs in AH header]:*^!:spi' )
+      [[ $service = ip6* ]] && args+=(
+        '--ahlen[total length of this header]:length (octets)'
+        '--ahres[match if the reserved field is filled with zero]'
+      )
+    ;;
+    bpf)
+      args+=(
+        '--object-pinned[pass a path to a pinned eBPF object]:path:_files'
+        '--bytecode[pass BPF byte code as generated by nfbpf_compile]:code'
+      )
+    ;;
+    cgroup)
+      args+=(
+        '--path[match cgroup2 membership]:path:_files -W /sys/fs/cgroup'
+        '--cgroup[match cgroup net_cls classid]:classid'
+      )
+    ;;
+    cluster)
+      args+=(
+        '--cluster-total-nodes[set number of total nodes in cluster]:number'
+        '--cluster-local-node[set the local node number ID]:number'
+        '--cluster-local-nodemask[set the local node number ID mask]:mask'
+        '--cluster-hash-seed[set seed value of the Jenkins hash]:value'
+      )
+    ;;
+    comment) args+=( '--comment[add comment to rule]:comment' ) ;;
     conntrack)
       args+=(
         '--ctstate[match packet state]:state:->cfstates'
@@ -160,30 +195,34 @@ _arguments -C -s \
   '(-)'{-V,--version}'[print version information]' \
   '(-h --help -V --version)'{-t,--table}'[specify table]:table:(filter nat mangle raw security)' \
   "($rcmds $cmds)"{-A,--append}'[append rules to end of specified chain]:chain:->chains' \
+  {-C,--check}'[check for the existence of a rule]' \
   "($rcmds $cmds -c --set-counters)"{-D,--delete}'[delete rules from specified chain]:chain:->chains::rule number:->rulenums' \
   "($rcmds $cmds)"{-I,--insert}'[insert rules before specified rule number]:chain:->chains::rule number:->rulenums' \
   "($rcmds $cmds)"{-R,--replace}'[replace a rule]:chain:->chains::rule number:->rulenums' \
-  "($rcmds "${(j. .)cmds:#(-Z|--zero)}" $ropts)"{-L,--list}'[list rules in selected chain]::chain:->chains' \
+  "($rcmds "${(j. .)cmds:#(-Z|--zero)}" $ropts)"{-L,--list}'[list rules in selected chain]::chain:->chains:rule number:->rulenums' \
+  '(-L --list -S --list-rules)'{-S,--list-rules}'[list rules in the form of options to iptables]::chain:->chains::rule number:->rulenums' \
   "($rcmds $cmds $ropts)"{-F,--flush}'[flush specified chain (delete all rules)]::chain:->chains' \
   "($rcmds "${(j. .)cmds:#(-L|--list)}" $ropts)"{-Z,--zero}'[zero the packet and byte counters]::chain:->chains' \
   "($rcmds $cmds)"{-N,--new,--new-chain}'[create a new user-defined chain]:chain name' \
   "($rcmds $cmds)"{-X,--delete-chain}'[delete a user-defined chain]:: :->user-chains' \
   "($rcmds $cmds)"{-P,--policy}'[set the policy for a chain to given target]:chain:->chains:target:->targets' \
   "($rcmds $cmds)"{-E,--rename-chain}'[rename a user-defined chain]:old chain:->user-chains:new chain name' \
-  "($cmds -p --protocol)"{-p,--protocol}'[specify protocol of rule]:*^!:protocol:(! tcp udp icmp all)' \
-  "($cmds -s --src --source)"{-s,--src,--source}'[specify source]:*^!:network:_hosts' \
-  "($cmds -d --dst --destination)"{-d,--dst,--destination}'[specify destination]:*^!:network:_hosts' \
+  "($cmds -p --proto --protocol)"{-p,--proto,--protocol}'[specify protocol of rule]:*^!:protocol:(! tcp udp icmp all)' \
+  "($cmds -s --src --source)"{-s,--src,--source}'[specify source]:*^!:network:_sequence _hosts' \
+  "($cmds -d --dst --destination)"{-d,--dst,--destination}'[specify destination]:*^!:network:_sequence _hosts' \
   "($cmds -j --jump)"{-j,--jump}'[specify rule target]:target:->targets' \
   "($cmds -i --in-interface)"{-i,--in-interface}'[specify interface via which packet is received]:*^!:interface:_net_interfaces' \
   "($cmds -o --out-interface)"{-o,--out-interface}'[specify interface via which packet is to be sent]:*^!:interface:_net_interfaces' \
   "($cmds -f --fragment)"{-f,--fragment}'[match second or further fragments only]' \
   "($cmds -D --delete -c --set-counters)"{-c,--set-counters}'[initialise packet and byte counters]:packets: :bytes' \
   '(-v --verbose)'{-v,--verbose}'[enable verbose output]' \
+  '(-w --wait)'{-w,--wait}'[specify maximum wait to acquire xtables lock before giving up]: :_numbers -u seconds -d 1 wait' \
+  '(-W --wait-interval)'{-W,--wait-interval}'[specify wait time to try to acquire xtables lock]: :_numbers -u usecs -d "1 second" wait' \
   '(-n --numeric)'{-n,--numeric}'[print IP addresses and port numbers in numeric format]' \
   '(-x --exact)'{-x,--exact}'[expand numbers (display exact values)]' \
   '--line-numbers[print line numbers when listing]' \
   '--modprobe=[specify command to load modules with]:command:_command_names -e' \
-  "($cmds)*"{-m,--match}'[extended match (may load extension)]:extension:(ah conntrack dscp esp helper icmp length limit mac mark multiport owner physdev pkttype state tcp tos ttl udp unclean)' \
+  "($cmds)*"{-m,--match}'[extended match (may load extension)]:extension:(addrtype ah bpf cgroup cluster comment connbytes connlabel connlimit connmark conntrack cpu dccp devgroup dscp dsr ecn esp eui64 frag hashlimit hbh helper hl icmp icmp6 iprange ipv6header ipvs length limit mac mark mh multiport nfacct osf owner physdev pkttype policy quota rateest realm recent rpfilter rt sctp set socket state statistic string tcp tcpmss time tos ttl u32 udp unclean)' \
   "$args[@]" && ret=0
 
 case "$state" in
@@ -230,6 +269,11 @@ case "$state" in
     [[ "$state" = cf* ]] && states+=( SNAT DNAT )
     _values -s , 'state' $states && return
   ;;
+  address-types)
+    _wanted address-types expl 'address type' compadd \
+        UNSPEC UNICAST LOCAL BROADCAST ANYCAST MULTICAST \
+        BLACKHOLE UNREACHABLE PROHIBIT THROW NAT XRESOLVE && ret=0
+  ;;
   port-list)
     compset -P '*,'
     if compset -S ',*'; then
diff --git a/Completion/Linux/Command/_lsblk b/Completion/Linux/Command/_lsblk
index 8a9bc18bf..63aac743c 100644
--- a/Completion/Linux/Command/_lsblk
+++ b/Completion/Linux/Command/_lsblk
@@ -6,16 +6,19 @@ local curcontext="$curcontext" state line expl
 typeset -A opt_args
 
 _arguments -C -s -S \
+  '(H -A --noempty)'{-A,--noempty}"[don't print empty devices]" \
   '(H -E --dedup)'{-E+,--dedup=}'[de-duplicate output by specified column]:column:->columns' \
   '(H -a --all)'{-a,--all}'[print all devices]' \
   '(H -b --bytes)'{-b,--bytes}'[print size in bytes rather than in human readable format]' \
   '(H -d --nodeps)'{-d,--nodeps}"[don't print slaves or holders]" \
   '(H -I --include)*'{-e,--exclude}'[exclude devices by major number]:major device number:->majorlist' \
   '(H -e --exclude)*'{-I+,--include=}'[show only devices with specified major numbers]:major device number:->majorlist' \
-  '(H -n --noheadings)'{-n,--noheadings}"[don't print headings]" \
+  '(H -n --noheadings -y --shell)'{-n,--noheadings}"[don't print headings]" \
   '(H -p --paths)'{-p,--paths}'[print complete device path]' \
   '(H -s --inverse)'{-s,--inverse}'[reverse dependency order]' \
+  '(H -w --width)'{-w+,--width=}'[specify output width]:width' \
   '(H -x --sort)'{-x+,--sort=}'[sort output by specified column]:column:->columns' \
+  '(H -y --shell -n --noheadings)'{-y,--shell}'[use column names usable as shell variable identifiers]' \
   '(H)--sysroot=[use specified directory as system root]:directory:_directories' \
   '*:device:_files -g "*(-%b)" -P / -W /' \
   + fields \
@@ -24,6 +27,8 @@ _arguments -C -s -S \
   '(H -f --fs -o --output -O --output-all)'{-f,--fs}'[output info about filesystems]' \
   '(H -m --perms -o --output -O --output-all)'{-m,--perms}'[output info about permissions]' \
   '(H -S --scsi -o --output -O --output-all)'{-S,--scsi}'[output info about SCSI devices]' \
+  '(H -N --nvme -o --output -O --output-all)'{-N,--nvme}'[output info about NVMe devices]' \
+  '(H -v --virtio -o --output -O --output-all)'{-v,--virtio}'[output info about virtio devices]' \
   '(H -t --topology -o --output -O --output-all)'{-t,--topology}'[output info about topology]' \
   '(H fields)'{-o+,--output=}'[specify output columns]:output column:->columnlist' \
   '(H fields)'{-O,--output-all}'[output all columns]' \
diff --git a/Completion/Linux/Command/_networkmanager b/Completion/Linux/Command/_networkmanager
index 1e05252b2..d44c313db 100644
--- a/Completion/Linux/Command/_networkmanager
+++ b/Completion/Linux/Command/_networkmanager
@@ -42,8 +42,24 @@ _nm_fields() {
 }
 
 _nm_general() {
-  _arguments "1:command:(status hostname permissions logging help)"
-  # TODO: provide completions for logging
+  local curcontext="$curcontext" state line
+  _arguments "1:command:(status hostname permissions logging reload help)" \
+    "*::arguments:->args"
+
+  case $line[1] in
+    l*)
+      _values -w -S ' ' values \
+        'level:level' \
+        'domains:domain'
+    ;;
+    r*)
+      _describe -t flags 'flag' '(
+        "conf:NetworkManager.conf configuration"
+        "dns-rc:update DNS configuration"
+        "dns-full:restart the DNS plugin"
+      )'
+    ;;
+  esac
 }
 
 _nm_networking() {
diff --git a/Completion/Linux/Command/_pidof b/Completion/Linux/Command/_pidof
index dd0649ce9..151a0e0f6 100644
--- a/Completion/Linux/Command/_pidof
+++ b/Completion/Linux/Command/_pidof
@@ -3,19 +3,51 @@
 local curcontext="$curcontext" state line expl ret=1
 typeset -A opt_args
 
-local exargs="-h --help -V --version"
-_arguments -C -s -w \
-  '(- *)'{-h,--help}'[display help information]' \
-  '(- *)'{-V,--version}'[print program version]' \
-  "(-s --single-shot $exargs)"{-s,--single-shot}'[return one PID only]' \
-  "(-c --check-root $exargs)"{-c,--check-root}'[omit processes with different root]' \
-  '-q[quiet mode, only set the exit code]' \
-  '(-w --with-workers)'{-w,--with-workers}'[show kernel workers too]' \
-  "(-x $exargs)"-x'[include shells running named scripts]' \
-  "($exargs)"\*{-o+,--omit-pid=}'[omit processes with PIDs]:pids:_sequence -s , _pids' \
-  '(-S --separator)'{-S+,--separator=}'[specify separator put between PIDs]:separator' \
-  '*:process:->procnames' \
-  && return 0
+_pick_variant -r variant procps='--separator' $OSTYPE -h
+
+case $variant in
+  (procps)
+    local exargs="-h --help -V --version"
+    _arguments -C -s -w \
+      '(- *)'{-h,--help}'[display help information]' \
+      '(- *)'{-V,--version}'[print program version]' \
+      "(-s --single-shot $exargs)"{-s,--single-shot}'[return one PID only]' \
+      "(-c --check-root $exargs)"{-c,--check-root}'[omit processes with different root]' \
+      '-q[quiet mode, only set the exit code]' \
+      '(-w --with-workers)'{-w,--with-workers}'[show kernel workers too]' \
+      "(-x $exargs)"-x'[include shells running named scripts]' \
+      "($exargs)"\*{-o+,--omit-pid=}'[omit processes with PIDs]:pids:_sequence -s , _pids' \
+      '(-S --separator)'{-S+,--separator=}'[specify separator put between PIDs]:separator' \
+      '*:process:->procnames' \
+      && return 0
+    ;;
+  (darwin*)
+    # Night Production pidof
+    _arguments -s -w \
+      '(- *)'{-h,-\?}'[display help information]' \
+      '(- *)-v[print out version info on pidof]' \
+      '-l[print output in long format]' \
+      '-k[kill processes by name]' \
+      '*:process:_process_names -a' \
+      && return 0
+    ;;
+  (*)
+    # sysvinit-utils
+    _arguments -C -s -w \
+      '(- *)-h[display help information]' \
+      '-c[return PIDs with the same root directory]' \
+      '-d[use the provided character as output separator]:separator' \
+      '-n[avoid using stat system function on network shares]' \
+      '-o[omit results with a given PID]:pid:_sequence -s , _pids' \
+      '-s[return one PID only]' \
+      '-q[quiet mode. Do not display output]' \
+      '-s[only return one PID]' \
+      '-x[return PIDs of shells running scripts with a matching name]' \
+      '-z[list zombie and I/O waiting processes. May cause pidof to hang]' \
+      '*:process:->procnames' \
+      && return 0
+    ;;
+esac
 
 case $state in
   procnames)
diff --git a/Completion/Linux/Command/_selinux b/Completion/Linux/Command/_selinux
new file mode 100644
index 000000000..a7ba68952
--- /dev/null
+++ b/Completion/Linux/Command/_selinux
@@ -0,0 +1,796 @@
+#compdef audit2allow audit2why avcstat chcon checkmodule checkpolicy fixfiles getpidprevcon getsebool matchpathcon newrole restorecon runcon sealert secon sedta seinfo selinuxconlist selinuxdefcon selinuxexeccon semanage semodule semodule_unpackage sepolgen sepolicy sesearch sestatus setenforce setsebool validatetrans
+
+# encompasses checkpolicy libselinux-utils policycoreutils
+# policycoreutils-devel policycoreutils-python-utils setools-console
+# setools-console-analyses setroubleshoot-server and a few utilities from
+# coreutils
+
+_selinux_attributes() {
+  local -a seattrs expl
+
+  seattrs=( ${(f)"$(_call_program selinux-attributes seinfo --flat -a)"} )
+  _description selinux-attrs expl "selinux attribute"
+  compadd "$@" "$expl[@]" -a seattrs
+}
+
+_selinux_bools() {
+  local -a sebools expl
+
+  sebools=( ${(f)"$(_call_program selinux-bools seinfo --flat -b)"} )
+  _description selinux-bools expl "selinux boolean"
+  compadd "$@" "$expl[@]" -a sebools
+}
+
+_selinux_categories() {
+  local -a secats expl
+
+  secats=( ${(f)"$(_call_program selinux-categories seinfo --flat --category)"} )
+  _description selinux-categories expl "selinux category"
+  compadd "$@" "$expl[@]" -a secats
+}
+
+_selinux_classes() {
+  local -a seclasses expl
+
+  seclasses=( ${(f)"$(_call_program selinux-classes seinfo --flat -c)"} )
+  _description selinux-classes expl "selinux object class"
+  compadd "$@" "$expl[@]" -a seclasses
+}
+
+_selinux_commons() {
+  local -a secommons expl
+
+  secommons=( ${(f)"$(_call_program selinux-commons seinfo --flat --common)"} )
+  _description selinux-commons expl "selinux common permission set"
+  compadd "$@" "$expl[@]" -a secommons
+}
+
+_selinux_interfaces() {
+  local -a seints expl
+
+  seints=( ${(f)"$(_call_program selinux-interfaces sepolicy interface -l)"} )
+  _description selinux-interfaces expl "selinux interface"
+  compadd "$@" "$expl[@]" -a seints
+}
+
+_selinux_permissions() {
+  local -a seperms expl
+
+  seperms=( ${${${${(f)"$(_call_program selinux-permissions seinfo -c --flat -x)"}:#[^[:blank:]]*}#[[:blank:]]}:1} )
+  _description selinux-permissions expl "selinux permission"
+  compadd "$@" "$expl[@]" -a seperms
+}
+
+_selinux_sids() {
+  local -a sesids expl
+
+  sesids=( ${(f)"$(_call_program selinux-sids seinfo --flat --initialsid)"} )
+  _description selinux-sids expl "selinux SID"
+  compadd "$@" "$expl[@]" -a sesids
+}
+
+_selinux_sens() {
+  local -a sens expl
+
+  sesids=( ${(f)"$(_call_program selinux-sens seinfo --flat --initialsid)"} )
+  _description selinux-sensitivities expl "selinux sensitivity"
+  compadd "$@" "$expl[@]" -a sesids
+}
+
+_selinux_modules() {
+  local -a modules expl
+
+  modules=( ${(f)"$(_call_program selinux-modules semodule -l)"} )
+  _description selinux-modules expl "selinux module"
+  compadd "$@" "$expl[@]" -a modules
+}
+
+local curcontext="$curcontext" ret=1
+local -A opt_args
+local -a args sepolgen state state_descr line
+local ign
+(( $#words > 2 )) && ign='!'
+
+sepolgen=(
+  "${ign}(-h --help)"{-h,--help}'[display help information]'
+  '(--application --cgi --dbus --inetd --init --admin_user --confined_admin --desktop_user --newtype --sandbox --x_user)'*{-d+,--domain=}'[specify domain to expand]:domain:_selinux_types -a domain'
+  \*{-r+,--role=}'[specify role(s) to which the administrator domain will transition]: :_selinux_roles'
+  \*{-u+,--user=}'[specify SELinux user(s) which will transition to this domain]: :_selinux_users'
+  \*{-a+,--admin=}'[specify domain(s) which this confined admin will administrate]:admin domain:_selinux_types'
+  '(-n --name)'{-n+,--name=}'[specify name of policy to generate]:name'
+  '(--admin_user --confined_admin --desktop_user --newtype --sandbox --x_user)*'{-t+,--type=}'[specify type(s) for which you will generate new definition and rule(s)]:type:_selinux_types'
+  '(-p --path)'{-p+,--path=}'[specify path in which the generated policy files will be stored]:path:_directories'
+  '(--newtype)*'{-w+,--writepath=}'[specify path to which the confined processes will need to write]:path:_directories'
+  '1:command:_files'
+  + '(application)'
+  "(-d)--application[generate 'User Application' policy]"
+  "(-d)--cgi[generate 'Web Application/Script (CGI)' policy]"
+  "(-d)--dbus[generate 'DBUS System Daemon' policy]"
+  "(-d)--inetd[generate 'Internet Services Daemon' policy]"
+  "(-d)--init[generate 'Standard Init Daemon' policy]"
+  "(-d -t 1)--admin_user[generate 'Administrator Login User Role' policy]"
+  "(-d -t 1)--confined_admin[generate 'Confined Root Administrator Role' policy]"
+  "(1)--customize[generate 'Existing Domain Type' policy]"
+  "(-d -t 1)--desktop_user[generate 'Desktop Login User Role' policy]"
+  "(-d -w 1)--newtype[generate 'Module information for a new type' policy]"
+  "(-d -t 1)--sandbox[generate 'Sandbox' policy]"
+  "(-d -t 1)--term_user[generate 'Minimal Terminal Login User Role' policy]"
+  "(-d -t 1)--x_user[generate 'Minimal X Windows Login User Role' policy]"
+)
+
+case $service in
+  check(module|policy))
+    args=(
+      '(-b --binary)'{-b,--binary}'[read an existing binary policy file rather than a source policy.conf file]'
+      '(-C --cil)'{-C,--cil}'[write CIL policy file rather than binary policy file]'
+      '(-E --werror)'{-E,--werror}'[treat warnings as errors]'
+      "${ign}(-h --help)"{-h,--help}'[display help information]'
+      '(-U --handle-unknown)'{-U+,--handle-unknown=}'[specify how the kernel should handle unknown classes or permissions]:action:(deny allow reject)'
+      '(-M --mls)'{-M,--mls}'[enable the MLS policy when checking and compiling the policy]'
+      '(-o --output)'{-o+,--output=}'[write a policy file]:file:_files'
+      '-c+[specify the policy version]:policy version [latest]'
+      ':input file:_files'
+    )
+  ;|
+
+  audit2(allow|why))
+    args=(
+      '(-b --boot -i --input)'{-b,--boot}'[audit messages since last boot]'
+      '(-a --all -i --input -d --dmesg)'{-a,--all}'[read input from audit log]'
+      '(-p --policy)'{-p+,--policy=}'[specify policy file to use for analysis]:file:_files'
+      '(-d --dmesg -a --all -i --input)'{-d,--dmesg}'[read input from dmesg]'
+      '(-i --input -a --all -b --boot)'{-i+,--input=}'[read input from file]:file:_files'
+      '(-l --lastreload)'{-l,--lastreload}'[read input only after the last reload]'
+      '(-r --requires)'{-r,--requires}'[generate require statements for rules]'
+      '(-m --module -M --module-package -r --requires)'{-m+,--module=}'[set the module name]:module name:_selinux_modules'
+      '(-M --module-package -o --output -m --module)'{-M+,--module-package=}'[generate a module package]:module package:_files'
+      '(-o --output -M --module-package)'{-o+,--output=}'[append output to file]:file:_files'
+      '(-D --dontaudit)'{-D,--dontaudit}'[generate policy with dontaudit rules]'
+      '(-R --reference)'{-R,--reference}'[use installed macros in generated policy]'
+      '!(-R --reference -N --noreference)'{-N,--noreference}
+      '(-v --verbose)'{-v,--verbose}'[explain generated output]'
+      '(-e --explain)'{-e,--explain}'[fully explain generated output]'
+      '(-t --type)'{-t+,--type=}'[only process messages with type matching regex]:type'
+      '--perm-map=[specify file name of perm map]:file:_files'
+      '--interface-info=[specify file name of interface information]:file:_files'
+      '(-x --xperms)'{-x,--xperms}'[generate extended permission rules]'
+      '--debug[leave generated modules for -M]'
+      '(-w --why)'{-w,--why}'[translate SELinux audit messages into a description of why the access was denied]'
+      "${ign}(-h --help)"{-h,--help}'[display help information]'
+      "${ign}--version[display version information]"
+    )
+  ;;
+
+  avcstat)
+    args=(
+      '-c[cumulative]'
+      '-f+[specify AVC statistics file]:file [/sys/fs/selinux/avc/cache_stats]:_files'
+      ': :_guard "^-*" "interval (seconds)"'
+    )
+  ;;
+
+  chcon)
+    args=( -S
+      '(-h --no-dereference)--dereference[dereference symlinks]' \
+      '(-h --no-dereference --dereference)'{-h,--no-dereference}'[operate on symlinks themselves]' \
+      '(1 -u --user -r --role  -l --range -t --type)--reference=[copy security context of specified file]:file:_files' \
+      '(1 --reference -u --user)'{-u+,--user=}'[set user in the target security context]: :_selinux_users' \
+      '(1 --reference -r --role)'{-r+,--role=}'[set role in the target security context]: :_selinux_roles' \
+      '(1 --reference -t --type)'{-t+,--type=}'[set type in the target security context]: :_selinux_types' \
+      '(1 --reference -l --range)'{-l+,--range=}'[set range in the target security context]:selinux range' \
+      '(--recursive -R)'{--recursive,-R}'[recurse subdirectories]' \
+      '(-v --verbose)'{-v,--verbose}'[output a diagnostic for every file processed]' \
+      '(-H -L -P)-H[follow symlinks on the command line]' \
+      '(-H -L -P)-L[follow all symlinks]' \
+      "(-H -L -P)-P[don't follow symlinks (default)]" \
+      '!(--preserve-root)--no-preserve-root' \
+      "--preserve-root[fail to operate recursively on '/']" \
+      '(--reference -u --user -r --role  -l --range -t --type)1:security context:_selinux_contexts' \
+      "${ign}--help[display help information]" \
+      "${ign}--version[display version information]" \
+      '*:file:_files'
+    )
+  ;;
+
+  checkmodule)
+    args=(
+      "${ign}(-)"{-V,--version}'[show policy versions created by this program]'
+      '-m[build a policy module instead of a base module]'
+      '-c+[build a policy module targeting a modular policy version]:version (4-21)'
+    )
+  ;;
+
+  checkpolicy)
+    args=(
+      '(-F --conf)'{-F,--conf}'[write policy.conf file rather than binary policy file]'
+      '(-d --debug)'{-d,--debug}'[enter debug mode after loading the policy]'
+      '(-S --sort)'{-S,--sort}'[sort ocontexts before writing out the binary policy]'
+      '(-t --target)'{-t+,--target=}'[specify the target platform]:platform:(selinux xen)'
+      '(-O --optimize)'{-O,--optimize}'[optimize the final kernel policy (remove redundant rules)]'
+      "${ign}(-)"{-V,--version}'[display version information]'
+    )
+  ;;
+
+  fixfiles)
+    args=(
+      '-B[record current date in /.autorelabel to speed later labeling]'
+      '-F[force reset of context to match file_context for customizable files]'
+      '-f[clear /tmp directory without prompt for removal]'
+      '-R+[discover files from specified rpm packages]:package'
+      '-C+[run a diff on the specified file]:file:_files'
+      '-N+[only act on files created after the specified date]:date (YYYY-MM-DD HH\:MM):_dates'
+      '-v[show changes in file labels]'
+      '-T+[specify number of threads to use]:threads'
+      '1::action:(check verify restore relabel onboot)'
+      '*:file:_files'
+    )
+  ;;
+
+  getpidprevcon)
+    _pids
+    return
+  ;;
+
+  getsebool)
+    args=(
+      '(:)-a[show all booleans]'
+      '(-a):boolean:_selinux_bools'
+    )
+  ;;
+
+  matchpathcon)
+    args=(
+      '-m+[force file type for the lookup]:type:(file dir pipe chr_file blk_file lnk_file sock_file)'
+      "-n[don't display path]"
+      "-N[don't use translations]"
+      '-f+[use alternate file_context file]:file:_files'
+      '-p+[use prefix to speed translations]:prefix'
+      '-P+[use alternate policy root path]:path:_directories'
+      '-V[verify file context on disk matches defaults]'
+      '*:file path:_files'
+    )
+  ;;
+
+  newrole)
+    local cmd cpp
+    cmd="$words[1]"
+    cpp='_comp_priv_prefix=( $cmd ${(kv)opt_args[(I)-([rtl]|-role|-type|-level)]} )'
+    args=(
+      '(-r --role)'{-r+,--role=}'[specify role]: :_selinux_roles'
+      '(-t --type)'{-t+,--type=}'[specify type]: :_selinux_types'
+      '(-l --level)'{-l+,--range=}'[specify level]:level'
+      '(-p --preserve-environment)'{-p,--preserve-environment}"[don't create new minimal environment]"
+      "${ign}(-)"{-V,--version}'[display version information]'
+      "(-)1: :{ $cpp; _command_names -e }" \
+      "*:: :{ $cpp; _normal }"
+    )
+  ;;
+
+  restorecon)
+    args=(
+      '*-e+[exclude a directory]:directory:_directories'
+      '-f+[provide list of files to be processed]:file:_files'
+      '-F[force reset of context to match file_context for customizable files]'
+      "-i[ignore files that don't exist]"
+      '-I[ignore digest to force checking of labels even if SHA256 digest matches]'
+      '-D[set or update any directory SHA256 digests]'
+      '-m[include non-seclabel mounts in relabeling checks]'
+      "-n[don't change any file labels (passive check)]"
+      '(-v)-p[show progress]'
+      '(-R -r)'{-R,-r}'[change file labels recursively]'
+      '(-p)-v[show changes in file labels]'
+      '-W[display warnings about entries that had no matching files]'
+      '-0[expect NUL characters as input filename separators]'
+      "-x[don't cross file system boundaries]"
+      '-T+[specify number of threads to use]:threads'
+      "${ign}(-)"{-h,-\?}'[display help information]'
+      '*:file path:_files'
+    )
+  ;;
+
+  runcon)
+    args=(
+      '(1 -c --compute)'{-c,--compute}'[compute process transition context before modifying]'
+      '(1 -t --type)'{-t+,--type=}'[specify type]: :_selinux_types'
+      '(1 -u --user)'{-u+,--user=}'[specify user identity]: :_selinux_users'
+      '(1 -r --role)'{-r+,--role=}'[specify role]: :_selinux_roles'
+      '(1 -l --range)'{-l+,--range=}'[specify level range]:range'
+      '(-)1:security context:_selinux_contexts'
+      '*:::args:_normal'
+    )
+  ;;
+
+  sealert)
+    args=(
+      '(-b --browser)'{-b,--browser}'[launch the browser]'
+      '(-s --service -S --noservice)'{-s,--service}'[start sealert as a dbus service]'
+      '(-S --noservice -s --service)'{-S,--noservice}'[start sealert without dbus service as standalone app]'
+      '(-l --lookupid)'{-l+,--lookupid=}'[lookup alert by id, id may be wildcard * to lookup all alerts]:id'
+      '(-a --analyze)'{-a+,--analyze=}'[scan a log file, analyze its AVCs]:log file:_files'
+      '(-u --user)'{-u+,--user=}'[logon user name]:username'
+      '(-p --password)'{-p+,--password=}'[logon user password]:password'
+      '(-P --plugin)'{-P+,--plugin=}'[specify plugin name, required for -f]:plugin name'
+      '(-f --fix)'{-f+,--fix=}'[fix avc with the given uuid, requires plugin]:uuid'
+      "${ign}(-)"{-h,--help}'[display help information]'
+    )
+  ;;
+
+  secon)
+    args=(
+      "${ign}(-)"{-h,--help}'[display help information]'
+      "${ign}(-)--version[display version information]"
+      '(-P --prompt)'{-P,--prompt}'[output in a format good for a prompt]'
+      '(-u --user)'{-u,--user}'[show user of the context]'
+      '(-r --role)'{-r,--role}'[show role of the context]'
+      '(-t --type)'{-t,--type}'[show type of the context]'
+      '(-s --sensitivity)'{-s,--sensitivity}'[show sensitivity level of the context]'
+      '(-c --clearance)'{-c,--clearance}'[show clearance level of the context]'
+      '(-m --mls-range)'{-m,--mls-range}'[show sensitivity to clearance range of]'
+      '(-R --raw)'{-R,--raw}'[output context in "raw" format]'
+      '(-C --color)'{-C,--color}'[output using ANSI color codes (requires -P)]'
+      + '(context)'
+      {--self,--current}'[get context for the current process]'
+      {--self-exec,--current-exec}'[get exec context for the current process]'
+      {--self-fs,--current-fs}'[get fs context for the current process]'
+      {--self-key,--current-key}'[get key context for the current process]'
+      '--parent[get context for the parent process]'
+      '--parent-exec[get exec context for the parent process]'
+      '--parent-fs[get fs context for the parent process]'
+      '--parent-key[get key context for the parent process]'
+      {-p+,--pid=}'[context from the specified pid]:pid:_pids'
+      '--pid-exec[use exec context from the specified pid]:pid:_pids'
+      '--pid-fs[use fs context from the specified pid]:pid:_pids'
+      '--pid-key[use key context from the specified pid]:pid:_pids'
+      {-f+,--file=}'[use context from the specified file]:file:_files'
+      {-L+,--link=}"[use context from the specified file, doesn't follow symlinks]:file:_files"
+      ':context:_selinux_contexts'
+    )
+  ;;
+
+  sedta)
+    args=(
+      '(-p --policy)'{-p+,--policy=}'[specify path to SELinux policy to analyze]:policy:_files'
+      '(-s --source)'{-s+,--source=}'[specify source type of the analysis]:source:_selinux_types -a domain'
+      '(-t --target)'{-t+,--target=}'[specify target type of the analysis]:target:_selinux_types -a domain'
+      '--full[print rule lists for transitions]'
+      '--stats[display statistics at the end of the analysis]'
+      '(-v --verbose)'{-v,--verbose}'[extra informational messages]'
+      '--debug[enable debugging]'
+      '(-S --shortest_path)'{-S,--shortest_path}'[calculate all shortest paths]'
+      '(-A --all_paths)'{-A+,--all_paths=}'[calculate all paths]:max steps'
+      '(-r --reverse)'{-r,--reverse}'[perform a reverse DTA]'
+      '(-l --limit_trans)'{-l+,--limit_trans=}'[limit to the specified number of transitions]:limit'
+      '*:excluded domain:_selinux_types -a domain'
+      "${ign}(- *)"{-h,--help}'[display help information]'
+      "${ign}(-)--version[display version information]"
+    )
+  ;;
+
+  seinfo)
+    args=(
+      '(-a --attribute)'{-a,--attribute}'[list attributes or print named attribute]:: :_selinux_attributes'
+      '(-b --bool)'{-b,--bool}'[list booleans or print named boolean]:: :_selinux_bools'
+      '(-c --class)'{-c,--class}'[list object classes or print named object class]:: :_selinux_classes'
+      '(-r --role)'{-r,--role}'[list roles or print named role]:: :_selinux_roles'
+      '(-t --type)'{-t,--type}'[list types or print named type]:: :_selinux_types'
+      '(-u --user)'{-u,--user}'[list users or print named user]:: :_selinux_users'
+      '--category[list categories or print named category]:: :_selinux_categories'
+      '--common[list common permission sets or print named common]:: :_selinux_commons'
+      '--constrain[list constraints or print constraints for named object class]:: :_selinux_classes'
+      '--default[list default_* statements or print statements for named object class]:: :_selinux_classes'
+      '--fs_use[list fs_use_* statements or print statements for named filesystem type]:: :_file_systems'
+      '--genfscon[list genfscon statements or print statements for named filesystem type]:: :_file_systems'
+      '--initialsid[list initial SIDs or print named SID]:: : _selinux_sids'
+      '--netifcon[list netif contexts or print for named interface]:: : _net_interfaces'
+      '--nodecon[list node contexts or print statement for node with specified address]::address'
+      '--permissive[list permissive types or print named statement]::type'
+      '--polcap[list policy capabilities or print named statement]::type'
+      '--portcon[list port contexts or print statements for port range]::port range'
+      '--sensitivity[list sensitivities or print named sensitivity]:: :_selinux_sens'
+      '--typebounds[list type bounds or print named bound type]:: :_selinux_typebounds'
+      '--validatetrans[list validatetrans rules or print constraints for named object class]:: :_selinux_classes'
+      '--all[list all components]'
+      '(-x --expand)'{-x,--expand}'[print additional details]'
+      '--flat[exclude headers and indentation in output]'
+      '(-v --verbose)'{-v,--verbose}'[print additional informational messages]'
+      '--debug[enable debugging output]'
+      "${ign}--help[display help information]"
+      "${ign}--version[display version information]"
+      ':policy:_files'
+    )
+  ;;
+
+  selinuxconlist)
+    args=(
+      '-l+[specify mcs/mls level]:level'
+      ':user:_selinux_users'
+      ':context:_selinux_contexts'
+    )
+  ;;
+
+  selinuxdefcon)
+    args=(
+      '-l+[specify mcs/mls level]:level'
+      ':user:_users'
+      ':context:_selinux_contexts'
+    )
+  ;;
+
+  selinuxexeccon)
+    args=(
+      '1:command:_files -g "*(-*)"'
+      '2:from context:_selinux_contexts'
+    )
+  ;;
+
+  semanage)
+    _arguments -C \
+      {-h,--help}'[display help information]' \
+      ': :->command' \
+      '*::: := ->option-or-argument' && ret=0
+
+    case $state in
+      command)
+        local -a subcmds
+
+        subcmds=(
+          import:'import local customizations'
+          export:'output local customizations'
+          login:'manage login mappings between linux users and SELinux confined users'
+          user:'manage SELinux confined users (Roles and levels for an SELinux user)'
+          port:'manage network port type definitions'
+          interface:'manage network interface type definitions'
+          module:'manage SELinux policy modules'
+          node:'manage network node type definitions'
+          fcontext:'manage file context mapping definitions'
+          boolean:'manage booleans to selectively enable functionality'
+          permissive:'manage process type enforcement mode'
+          dontaudit:'disable/enable dontaudit rules in policy'
+          ibpkey:'manage infiniband pkey type definitions'
+          ibendport:'manage infiniband end port type definitions'
+        )
+
+        _describe -t commands command subcmds
+        return
+      ;;
+      option-or-argument)
+        (( $#words > 2 )) && ign='!' || ign=''
+        curcontext=${curcontext%:*}-$line[1]:
+        args=(
+          "${ign}(-)"{-h,--help}'[display help information]'
+          '(-S --store)'{-S+,--store=}'[select an alternate SELinux Policy Store to manage]:store:_files'
+        )
+
+        case $line[1] in
+          ^export)
+            args+=( '(-N --noreload)'{-N,--noreload}"[don't reload policy after commit]" )
+          ;|
+          boolean|fcontext|ibendport|ibpkey|interface|login|module|node|port|user)
+            args+=( '(-C --locallist)'{-C,--locallist}'[list local customizations]' )
+          ;|
+          boolean|fcontext|ibendport|ibpkey|interface|login|module|node|permissive|port|user)
+            args+=(
+              '(-n --noheading)'{-n,--noheading}"[don't print list heading]"
+              '(-l --list)'{-l,--list}'[list records]'
+              '(-E --extract)'{-E,--extract}'[extract customizable commands, for use within a transaction]'
+            )
+          ;|
+          fcontext|ibendport|ibpkey|interface|login|module|node|permissive|port|user)
+            args+=( '(-a --add)'{-a,--add}'[add a record]' )
+          ;|
+          boolean|fcontext|ibendport|ibpkey|interface|login|node|permissive|port|user)
+            args+=(
+              '(-d --delete)'{-d,--delete}'[delete a record]'
+              '(-D --deleteall)'{-D,--deleteall}'[remove all local customizations]'
+            )
+          ;|
+          boolean|fcontext|ibendport|ibpkey|interface|login|node|port|user)
+            args+=( '(-m --modify)'{-m,--modify}'[modify a record]' )
+          ;|
+          fcontext|login)
+            args+=( '(-s --seuser)'{-s+,--seuser=}'[SELinux user name]:seuser:_selinux_users' )
+          ;|
+          fcontext|ibendport|ibpkey|interface|node|port)
+            args+=( '(-t --type)'{-t+,--type=}'[SELinux Type for the object]:type:_selinux_contexts -a file_type' )
+          ;|
+          fcontext|ibendport|ibpkey|interface|login|node|port|user)
+            args+=( '(-r --range)'{-r+,--range=}'[specify MLS/MCS Security Range]:range' )
+          ;|
+
+          import)
+            args+=( '(-f --input_file)'{-f+,--input_file=}'[specify input file]:input file:_files' )
+          ;;
+          export)
+            args+=( '(-f --output_file)'{-f+,--output_file=}'[specify output file]:output_file' )
+          ;;
+          login)
+            args+=( '(-l --list)1: :{ compset -P % && _groups || _users }' )
+          ;;
+          user)
+            args+=(
+              '(-L --level)'{-L,--level}'[default SELinux Level for SELinux user, s0 Default. (MLS/MCS Systems only)]:level'
+              \*{-R,--roles}'[specify SELinux Roles]:roles:_selinux_roles'
+              ': :_selinux_users'
+            )
+          ;;
+          port)
+            args+=(
+              '(-p --proto)'{-p+,--proto=}'[specify protocol for the specified port]:protocol:(tcp udp dccp sctp)'
+              ': :_ports'
+            )
+          ;|
+          interface)
+            args+=( ': :_selinux_interfaces' )
+          ;;
+          module)
+            args+=(
+              '(-P --priority)'{-P+,--priority=}'[select a priority for module operations]:priority [400]'
+              '(-E --extract)'{-E,--extract}'[extract customizable commands, for use within a transaction]'
+              '(-a --add)'{-a,--add}'[add a module]:module name:_selinux_modules'
+              '(-r --remove)'{-r,--remove}'[remove a module]:module name:_selinux_modules'
+              '(-d --disable)'{-d,--disable}'[disable a module]:module name:_selinux_modules'
+              '(-e --enable)'{-e,--enable}'[enable a module]:module name:_selinux_modules'
+            )
+          ;;
+          node)
+            args+=(
+              '(-p --proto)'{-p+,--proto=}'[specify protocol for the specified node]:protocol:(ipv4 ipv6)'
+              '(-M --netmask)'{-M+,--netmask=}'[specify network mask]:netmask'
+              ':node:'
+            )
+          ;;
+          fcontext)
+            args+=(
+              '(-e --equal)'{-e+,--equal=}'[substitute target path with sourcepath when generating default label]:equal'
+              '(-f --ftype)'{-f+,--ftype=}'[specify file type]:file type:((
+                f\:regular\ file
+                d\:directory
+                c\:character\ device
+                b\:block device
+                s\:socket
+                l\:symbolic\ link
+                p\:named\ pipe))'
+              ':file spec (regex):_files'
+            )
+          ;;
+          boolean)
+            args+=(
+              '(-)'{-1,--on}'[enable]'
+              '(-)'{-0,--off}'[disable]'
+              ':boolean:_selinux_bools'
+            )
+          ;;
+          permissive)
+            args+=( '1:type:_selinux_types' )
+          ;;
+          dontaudit)
+            args+=( '1:value:(on off)' )
+          ;;
+          ibpkey)
+            args+=(
+              '(-x --subnet_prefix)'{-x,--subnet_prefix}'[specify subnet prefix for the specified infiniband ibpkey]:subnet prefix'
+              ':pkey:'
+            )
+          ;;
+          ibendport)
+            args+=(
+              '(-z --ibdev_name)'{-z+,--ibdev_name=}'[specify name for the specified infiniband end port]:ibdev name'
+            )
+          ;;
+        esac
+      ;;
+    esac
+  ;;
+
+  semodule)
+    args=(
+      \*{-R,--reload}'[force a reload of policy]'
+      \*{-B,--build}'[build and reload policy]'
+      \*'--refresh[like --build but reuse existing linked policy if module files unchanged]'
+      \*{-D,--disable_dontaudit}'[remove dontaudits from policy]'
+      \*{-i+,--install=}'[install a new module]:module package:_files -g "*.(pp|cil)(-.)"'
+      \!{-b,--base,-u,--upgrade}':module package:_files -g "*.(pp|cil)(-.)"'
+      \*{-r+,--remove=}'[remove existing module at desired priority]:module name:_selinux_modules'
+      \*{-l+,--list-modules=-}'[display list of installed modules]::kind:((
+        standard\:highest\ priority,\ enabled\ modules
+        full\:list\ all\ modules
+      ))'
+      \*{-X+,--priority=}'[set priority for following operations]:priority (1-999)'
+      \*{-e,--enable=}'[enable module]:module name:_selinux_modules'
+      \*{-d,--disable=}'[disable module]:module name:_selinux_modules'
+      \*{-E,--extract=}'[extract module]:module name:_selinux_modules'
+      '(-s --store)'{-s+,--store=}'[name of the store to operate on]:store'
+      '(-N -n --noreload)'{-N,-n,--noreload}"[don't reload policy after commit]"
+      '(-v --verbose)'{-v,--verbose}'[be verbose]'
+      '(-P --preserve_tunables)'{-P,--preserve_tunables}'[preserve tunables in policy]'
+      '(-C --ignore-module-cache)'{-C,--ignore-module-cache}'[rebuild CIL modules compiled from HLL files]'
+      '(-p --path)'{-p,--path}'[use an alternate path for the policy root]'
+      '(-S --store-path)'{-S+,--store-path=}'[use an alternate path for the policy store root]:path:_directories'
+      '(-c --cil)'{-c,--cil}'[extract module as cil; only affects module extraction]'
+      '(-H --hll)'{-H,--hll}'[extract module as hll; only affects module extraction]'
+      '(-m --checksum)'{-m,--checksum}'[add SHA256 checksum of modules to the list output]'
+      '!(--refresh)--rebuild-if-modules-changed'
+      "${ign}(-)"{-h,--help}'[display help information]'
+    )
+  ;;
+
+  semodule_unpackage)
+    args=(
+      ':pp file:_files -g "*.pp(-.)"'
+      ':mod file:_files -g "*.mod(-.)"'
+      ':fc file:_files -g "*.fc(-.)"'
+    )
+  ;;
+
+  sepolgen)
+    args=( $sepolgen )
+  ;;
+  sepolicy)
+    _arguments -C \
+      '-P+[specify policy to examine]' \
+      "${ign}(- 1)-h[display help information]" \
+      '1:command:((
+          booleans\:"get description of booleans"
+          communicate\:"query if domains can communicate with each other"
+          generate\:"generate policy module template"
+          gui\:"graphical user interface for policies"
+          interface\:"list policy interfaces"
+          manpage\:"generate man pages for policies"
+          network\:"query policy network information"
+          transition\:"query policy to see how a source process domain can transition to the target process domain"))' \
+      '*::: := ->option-or-argument' && ret=0
+    case $state in
+      option-or-argument)
+        curcontext=${curcontext%:*}-$line[1]:
+        args=( '(-)'{-h,--help}'[display help information]' )
+        case $line[1] in
+          transition|communicate)
+            args+=(
+              '(-s --source)'{-s+,--source=}'[specify source domain]:source:_selinux_types -a domain'
+              '(-t --target)'{-t+,--target=}'[specify target domain]:target:_selinux_types -a domain'
+            )
+          ;|
+          manpage|network)
+            args+=(
+              {-d,--domain}'[specify domain]:*: :_selinux_types -a domain'
+              '!*'{-d-,--domain=-}': :_selinux_types -a domain'
+            )
+          ;|
+          booleans)
+            args+=(
+              '(-)'{-a,--all}'[get all booleans descriptions]'
+              \*{-b,--boolean}'[specify boolean to show description]:*:boolean:_selinux_bools'
+              '!(-a --all -h --help)*'{-b-,--boolean=}': :_selinux_bools'
+            )
+          ;;
+          communicate)
+            args+=(
+              '(-c --class)'{-c+,--class=}'[specify class to use for communications]:tclass [file]:_selinux_classes'
+              '(-S --sourceaccess)'{-S+,--sourceaccess=}'[specify permissions for the source type to use]:source access [open,write]'
+              '(-T --targetaccess)'{-T+,--targetaccess=}'[specify permissions for the target type to use]:target access [open,read]'
+            )
+          ;;
+          generate)
+            args=( $sepolgen )
+          ;;
+          interface)
+            args+=(
+              '(-c --compile)'{-c,--compile}'[run compile test for selected interface]'
+              '(-v --verbose)'{-v,--verbose}'[show verbose information]'
+              '(-f --file)'{-f+,--file=}'[specify interface file]:interface file:_files'
+              '(-a --list_admin)'{-a,--list_admin}'[list all domains with admin interface - DOMAIN_admin()]'
+              '(-u --list_user)'{-u,--list_user}'[list all domains with SELinux user role interface - DOMAIN_role()]'
+              '(-l --list)'{-l,--list}'[list all interfaces]'
+              {-i,--interfaces}'[specify interface names]:*:interface:_selinux_interfaces'
+              '!*'{-i-,--interfaces=-}':interface:_selinux_interfaces'
+            )
+          ;;
+          manpage)
+            args+=(
+              '(-p --path)'{-p+,--path=}'[specify path in which the generated selinux man pages will be stored]:path:_directories'
+              '(-o --os)'{-o+,--os=}'[specify name of the OS for man pages]:OS'
+              '(-w --web)'(-w,--web)'[generate HTML man pages structure]'
+              '(-r --root)'{-r+,--root=}'[specify alternate root directory]:root [/]:_directories'
+              '--source_files[alternative root path needs to include file context files and policy.xml file]'
+              '(-a --all -d --domain)'{-a,--all}'[all domains]'
+            )
+          ;;
+          network)
+            args+=(
+              '(-l --list)'{-l,--list}'[list all SELinux port types]'
+              {-p,--port}'[specify type related to the port]:*:port number'
+              '!*'{-p-,--port=-}':port number'
+              {-t,--type}'[show ports defined for this SELinux type]:*:port type:_selinux_types -a port_type'
+              '!*'{-t-,--type=-}':port type:_selinux_types -a port_type'
+              {-d,--domain}'[specify domain]:*:domain:_selinux_types -a domain'
+              '!*'{-d-,--domain=-}':domain:_selinux_types -a domain'
+              {-a,--application}'[show ports to which this application can bind and/or connect]:*:application:_selinux_types -a application_domain_type'
+              '!*'{-a-,--application=-}':domain:_selinux_types -a application_domain_type' # am not sure this is what is meant by applications
+            )
+          ;;
+        esac
+      ;;
+    esac
+  ;;
+
+  sesearch)
+    args=(
+      "${ign}(-h --help)"{-h,--help}'[display help information]'
+      "${ign}--version[display version information]"
+      '(-v --verbose)'{-v,--verbose}'[print extra informational messages]'
+      '--debug[enable debugging]'
+      '-A[search allow and allowxperm rules]'
+      '--allow[search allow rules]'
+      '--allowxperm[search allowxperm rules]'
+      '--auditallow[search auditallow rules]'
+      '--auditallowxperm[search auditallowxperm rules]'
+      '--dontaudit[search dontaudit rules]'
+      '--dontauditxperm[search dontauditxperm rules]'
+      '--neverallow[search neverallow rules]'
+      '--neverallowxperm[search neverallowxperm rules]'
+      '(-T --type_trans)'{-T,--type_trans}'[search type_transition rules]'
+      '--type_change[search type_change rules]'
+      '--type_member[search type_member rules]'
+      '--role_allow[find role allow rules]'
+      '--role_trans[find range_transition rules]'
+      '--range_trans[search range_transition rules]'
+      '(-s --source)'{-s+,--source=}'[source type/role of the TE/RBAC rule]: : _alternative
+        "types\:type\:_selinux_types"
+        "roles\:role\:_selinux_attributes"'
+      '(-t --target)'{-t+,--target=}'[target type/role of the TE/RBAC rule]: : _alternative
+        "types\:type\:_selinux_types"
+        "roles\:role\:_selinux_attributes"'
+      '(-c --class)'{-c+,--class=}'[comma separated list of object classes]:class:_sequence _selinux_classes'
+      '(-p --perms)'{-p+,--perms=}'[comma separated list of permissions]: :_sequence _selinux_permissions'
+      '(-x --xperms)'{-x+,--xperms=}'[comma separated list of extended permissions]:xperms'
+      '(-D --default)'{-D+,--default=}'[default of the rule. (type/role/range transition rules]:default'
+      '(-b --bool)'{-b+,--bool=}'[comma separated list of Booleans in the conditional expression]:bool '
+      '-eb[match Boolean list exactly instead of matching any listed boolean]'
+      '-ep[match permission set exactly instead of matching any listed permission]'
+      '-ex[match extended permission set exactly instead of matching any listed permission]'
+      '-Sp[match rules where the listed permissions are a subset of the rule permissions]'
+      '-ds[match source attributes directly instead of matching member types/roles]'
+      '-dt[match target attributes directly instead of matching member types/roles]'
+      '-rs[use regular expression matching for the source type/role]'
+      '-rt[use regular expression matching for the target type/role]'
+      '-rc[use regular expression matching for the object class]'
+      '-rd[use regular expression matching for the default type/role]'
+      '-rb[use regular expression matching for booleans]'
+      ':policy:_files'
+    )
+  ;;
+
+  sestatus)
+    args=( '-b[booleans]' '-v[contexts of files and processes listed in the /etc/sestatus.conf]' )
+  ;;
+
+  setenforce)
+    _alternative \
+      'enable-args:enable:(Enforcing 1)' \
+      'disable-args:disable:(Permissive 0)'
+    return
+  ;;
+
+  setsebool)
+    args=(
+      '-P[make changes persistent by writing pending values to disk]'
+      "-N[don't reload policy from disk]"
+      '-V[print verbose error messages]'
+      ':boolean:_selinux_bools'
+      ': : _values value
+              {1,on}"[enable]"
+              {0,off}"[disable]"'
+    )
+  ;;
+
+  validatetrans)
+    args=(
+      ':source context:_selinux_contexts'
+      ':target context:_selinux_contexts'
+      ':class:_selinux_classes'
+      ':new context:_selinux_contexts'
+    )
+  ;;
+esac
+
+_arguments -s $args
diff --git a/Completion/Linux/Command/_setpriv b/Completion/Linux/Command/_setpriv
index 196f2f627..8b8d99785 100644
--- a/Completion/Linux/Command/_setpriv
+++ b/Completion/Linux/Command/_setpriv
@@ -93,10 +93,10 @@ _arguments -C -S -s \
   '--reuid[set real and effective UNIX user id]:UNIX user:_users' \
   '--securebits[set "process securebits"]: : _sequence __setpriv_prctl_securebits_set_elements' \
   '--pdeathsig[keep, clear, or set parent death signal]: : __setpriv_death_signals' \
-  '--selinux-label[request a selinux label]:SELinux labels: ' \
+  '--selinux-label[request a selinux label]:SELinux label:_selinux_contexts' \
   '--apparmor-profile[request an apparmor profile]:AppArmor profiles: ' \
   '--reset-env[set environment as for a classic login shell]' \
-  '*:::command:_normal' \
+  '*:::command: _normal -p $service' \
   && return 0
 
 case $state in
diff --git a/Completion/Linux/Command/_strace b/Completion/Linux/Command/_strace
index b3b6f5096..37e14b6d6 100644
--- a/Completion/Linux/Command/_strace
+++ b/Completion/Linux/Command/_strace
@@ -11,11 +11,13 @@ _arguments -C -s \
   \*{-E+,--env=}'[set or remove exported environment variable]:variable:->envars' \
   '(:)*'{-p+,--attach=}'[attach to the process with specified process ID and begin tracing]:process ID:_pids' \
   "${root}(-u --user)"{-u+,--user=}'[run as specified user]:user:_users' \
+  '--argv0=[set argv0 for program]:name' \
   '(-b --detach-on)'{-b+,--detach-on=}'[detach from process on specified syscall]:syscall:(execve)' \
   '(--daemonize)-D[run tracer as detached grandchild, keeping traced process as direct child of calling process]' \
   '(-D)--daemonize=-[specify how to run tracer process]::method:(grandchild pgroup session)' \
   '(-f --follow-forks)'{-f,--follow-forks}'[trace child processes as they are created by currently traced processes]' \
   '(-I --interruptible)'{-I+,--interruptible=}'[specify when strace can be interrupted by signals]:interruptible:((1\:"no signals are blocked" 2\:"fatal signals are blocked while decoding syscall (default)" 3\:"fatal signals are always blocked (default with -o)" 4\:"fatal signals and SIGTSTP are always blocked"))' \
+  '--kill-on-exit[kill all tracees if strace is killed]' \
   \*{-e+,--trace=}'[select events to trace or how to trace]:system call:->expressions' \
   \*{-P+,--path=}'[trace only system calls accessing given path]:path:_files' \
   '(-z -Z --successful-only --failed-only)'{-z,--successful-only}'[trace only system calls that return success]' \
@@ -45,11 +47,14 @@ _arguments -C -s \
   '(-v --no-abbrev)'{-v,--no-abbrev}'[print unabbreviated versions of environment, stat, termios, etc. calls]' \
   '(-xx --strings-in-hex)-x[print all non-ASCII strings in hexadecimal string format]' \
   '(-x --strings-in-hex)-xx[print all strings in hexadecimal string format]' \
-  '(-x -xx)--strings-in-hex=[specify strings to print in hexadecimal format]:string type:(all non-ascii)' \
+  '(-x -xx)--strings-in-hex=[specify strings to print in hexadecimal format]:string type:(all non-ascii non-ascii-chars)' \
   '(-X --const-print-style)'{-X+,--const-print-style=}'[set the format for printing of named constants and flags]:format:(raw abbrev verbose)' \
   '(-c --summary-only -yy --decode-fds)-y[print paths associated with file descriptor arguments]' \
   '(-c --summary-only -y --decode-fds)-yy[print protocol specific information associated with socket file descriptors]' \
-  '(-c --summary-only -y -yy)--decode-fds=-[print information associated with file descriptors]::information [none]:_sequence compadd - none all path socket dev pidfd' \
+  '(-c --summary-only -y -yy)--decode-fds=-[print information associated with file descriptors]::information [none]:_sequence compadd - none all path socket dev pidfd signalfd' \
+  '(-c --summary-only -Y)--decode-pids=[print information associated with process IDs]:information [none]:_sequence compadd - none comm pidns' \
+  '!(-c --summary-only -Y --decode-pids)--pidns-translation' \
+  '(-c --summary-only --decode-pids)-Y[print command names for PIDs]' \
   '(-c --summary-only -C --summary -i --instruction-pointer -k --stack-traces -r --relative-timestamps -ff -t -tt -ttt --absolute-timestamps -T --syscall-times -y -yy --decode-fds)'{-c,--summary-only}'[count time, calls, and errors for each system call and report a summary]' \
   '(-c --summary-only -C --summary)'{-C,--summary}'[count time, calls, and errors for each system call and report a summary in addition to regular output]' \
   '(-O --summary-syscall-overhead)'{-O+,--summary-syscall-overhead=}'[specify overhead for tracing system calls]:overhead (microseconds)' \
@@ -57,9 +62,11 @@ _arguments -C -s \
   '(-U --summary-columns)'{-U+,--summary-columns=}'[show specific columns in the summary report]:column:_sequence compadd - time-percent total-time min-time max-time avg-time calls errors name' \
   '(-w --summary-wall-clock)'{-w,--summary-wall-clock}'[summarise syscall latency]' \
   '(-c --summary-only -C)-ff[write each process trace to <filename>.<pid> (when using -o <filename>]' \
+  '--syscall-limit=[detach all tracees after tracing given number of syscalls]:limit' \
   '(-d --debug)'{-d,--debug}'[show debug output of strace itself on standard error]' \
   '(- 1 *)'{-h,--help}'[display help information]' \
   '--seccomp-bpf[enable seccomp-bpf filtering]' \
+  '--tips=-[show strace tips, tricks, and tweaks before exit]:tip [id\:random,format\:compact]' \
   '(- 1 *)'{-V,--version}'[display version information]' \
   '(-):command name: _command_names -e' \
   '*::arguments:_normal' && ret=0
@@ -72,6 +79,7 @@ case $state in
       'verbose[dereference structures for the specified set of system calls]:system call:_sequence _sys_calls -a -n' \
       'raw[print raw, undecoded arguments for the specified set of system calls]:system call:_sequence _sys_calls -a -n' \
       'signal[trace only the specified subset of signals]:signal:_sequence _signals -s -M "B\:!="' \
+      'trace-fds[trace operations on listed file descriptors]:file descriptor:_sequence _file_descriptors' \
       'read[perform a full hex and ASCII dump of all the data read from listed file descriptors]:file descriptor:_sequence _file_descriptors' \
       'write[perform a full hex and ASCII dump of all the data written to listed file descriptors]:file descriptor:_sequence _file_descriptors' \
       'fault[perform syscall fault injection]:system call:_sys_calls -a -n' \
@@ -79,7 +87,8 @@ case $state in
       'status[trace system calls with given return status]:status:->status' \
       'quiet[suppress various information messages]:message [none]:_sequence compadd - none attach exit path-resolution personality thread-execve superseded' \
       'kvm[print the exit reason of kvm vcpu]: :(vcpu)' \
-      'decode-fds[print information associated with file descriptors]:information [none]:_sequence compadd - none all path socket dev pidfd' && ret=0
+      'decode-fds[print information associated with file descriptors]:information [none]:_sequence compadd - none all path socket dev pidfd signalfd' \
+      'decode-pids[print information associated with process IDs]:information [none]:_sequence compadd - none comm pidns' && ret=0
     if [[ $state = status ]]; then
       _values -s , 'return status [all]' \
         all successful failed \
diff --git a/Completion/Linux/Command/_sysstat b/Completion/Linux/Command/_sysstat
index 5620da73d..59a2f5da9 100644
--- a/Completion/Linux/Command/_sysstat
+++ b/Completion/Linux/Command/_sysstat
@@ -56,6 +56,7 @@ _sadf() {
       '--dev=-[specify block devices for which statistics are to be displayed]:block device:_files -g "*(-%)"' \
       '--fs=-[specify filesystems for which statistics are to be displayed]:file system:_dir_list -s ,' \
       '--iface=-[specify network interfaces for which statistics are to be displayed]:network interface:_sequence _net_interfaces' \
+      '--int=-[specify interrupts for which statistics are to be displayed]: : _values -s "," interrupt 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15' \
       '-s[set starting time of report]:starting time (HH\:MM\:SS)"' \
       '(-t -U)-T[display timestamp in local time]' \
       '(-T -U)-t[display timestamp in file\''s original localtime]' \
@@ -99,9 +100,10 @@ _sar() {
     '(--human -p)-h[make output easier to read: implies --human and -p]' \
     '(- 1 2)--help[display usage information]' \
     '--human[print sizes in human readable format]' \
-    '*-I[report statistics for interrupts]: : _values -s "," interrupt 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 SUM ALL XALL' \
+    '-I[report statistics for interrupts]:interrupt:(SUM ALL)' \
     '-i[select records as close as possible to interval]:interval' \
     '--iface=-[specify network interfaces for which statistics are to be displayed]:network interface:_sequence _net_interfaces' \
+    '--int=-[specify interrupts for which statistics are to be displayed]: : _values -s "," interrupt 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15' \
     '-j[display persistent device names]:type:(ID LABEL PATH UUID)' \
     '-m[report power management statistics]:keyword:_sequence compadd - CPU FAN FREQ IN TEMP USB ALL' \
     '-n[report network statistics]:keyword:_sequence compadd - DEV EDEV NFS NFSD SOCK IP EIP ICMP EICMP TCP ETCP UDP SOCK6 IP6 EIP6 ICMP6 EICMP6 UDP6 FC SOFT ALL' \
@@ -130,7 +132,7 @@ _pidstat() {
   _arguments -s : \
     '-C[filter tasks by string]:task filter' \
     '-d[report I/O statistics]' \
-    '-e[execute specified program and monitor it with pidstat]:*::command: _normal' \
+    '-e[execute specified program and monitor it with pidstat]:*::command: _normal -p $service' \
     '-H[display timestamp in seconds since the epoch]' \
     '-h[display horizontally]' \
     '-I[divide CPU usage by number of processors]' \
diff --git a/Completion/Linux/Command/_valgrind b/Completion/Linux/Command/_valgrind
index b4bb3248e..5eaaea338 100644
--- a/Completion/Linux/Command/_valgrind
+++ b/Completion/Linux/Command/_valgrind
@@ -165,7 +165,7 @@ args_massif=(
   "--time-unit=-[specify time unit]:unit [i]:((
     i\:instructions\ executed
     ms\:milliseconds
-    b\:heap\ bytes\ alloc\'d/dealloc\'d
+    B\:heap\ bytes\ alloc\'d/dealloc\'d
   ))"
   '--detailed-freq=-[every Nth snapshot should be detailed]:snapshot interval [10]'
   '--max-snapshots=-[specofy maximum number of snapshots recorded]:maximum [100]'
@@ -216,7 +216,7 @@ _arguments -C ${(P)args} $cmd \
   '--vgdb=-[activate gdbserver]:enable [yes]:(yes no full)' \
   '--vgdb-error=-[invoke gdbserver after specified number of errors]:errors [999999999]:errors' \
   '--vgdb-stop-at=-[invoke gdbserver for given events]:event:_sequence compadd - startup exit valgrindabexit all none' \
-  '--track-fds=-[track open file descriptors]:enable:(yes no)' \
+  '--track-fds=-[track open file descriptors]:enable [no]:(yes no all)' \
   '--time-stamp=-[add timestamps to log messages]:enable:(yes no)' \
   '--log-fd=-[log messages to specified file descriptor]:file descriptor:_file_descriptors' \
   '--log-file=-[log messages to specified file with pid appended]:file:_files' \
diff --git a/Completion/Linux/Type/_selinux_contexts b/Completion/Linux/Type/_selinux_contexts
index 4c2cf4288..bdad8e72b 100644
--- a/Completion/Linux/Type/_selinux_contexts
+++ b/Completion/Linux/Type/_selinux_contexts
@@ -1,14 +1,21 @@
 #autoload
 
-local -a parts suf
+local -a parts users roles types
+
+zparseopts -E -D a:=types P:=users
+
+if ! compset -S ':*'; then
+  users+=( -qS : )
+  roles+=( -qS : )
+  [[ $(</sys/fs/selinux/mls) = 0 ]] 2>/dev/null || types+=( -qS : )
+fi
 
 parts=( users roles types )
 while compset -P 1 '*:' && (( $+parts[1] )) ; do
   shift parts
 done
 if (( $+parts[1] )); then
-  compset -S ':*' || suf=( -S : )
-  _selinux_$parts[1] $suf
+  _selinux_$parts[1] ${(P)parts[1]}
 else
   _message -e selinux-ranges 'selinux range'
 fi
diff --git a/Completion/Linux/Type/_selinux_types b/Completion/Linux/Type/_selinux_types
index ef31f45d2..69047c690 100644
--- a/Completion/Linux/Type/_selinux_types
+++ b/Completion/Linux/Type/_selinux_types
@@ -1,7 +1,19 @@
 #autoload
 
-local -a setypes expl
+# Pass -a attribute to filter types, e.g.:
+#   -a domain    - for process types
+#   -a file_type - for file types
+#   -a port_type - for network ports
+
+local -a setypes expl extra
+
+zparseopts -E -D -a extra a:
+
+if (( $#extra )); then
+  setypes=( ${${${(f)"$(_call_program selinux-types seinfo $extra --flat -x)"}#[[:blank:]]}:1} )
+else
+  setypes=( ${(f)"$(_call_program selinux-types seinfo --flat -t)"} )
+fi
 
-setypes=( ${(f)"$(_call_program selinux-types seinfo --flat -t)"} )
 _description selinux-types expl "selinux type"
 compadd "$@" "$expl[@]" -a setypes
diff --git a/Completion/Redhat/Command/_dnf b/Completion/Redhat/Command/_dnf
index ce111f38f..a5edf8564 100644
--- a/Completion/Redhat/Command/_dnf
+++ b/Completion/Redhat/Command/_dnf
@@ -245,7 +245,7 @@ _dnf() {
     '--security[include security relevant packages]'
     '*--setopt=[override config option]:repoid.option=value: '
     '--skip-broken[resolve depsolve problems by skipping packages]'
-    '--show-duplicates[show duplicate packages in repos]'
+    '--showduplicates[show duplicate packages in repos]'
     '(-v --verbose)'{-v,--verbose}'[set verbose, show debug messages]'
     '(- *)--version[show dnf version]'
     '(-y --assumeyes --assumeno)'{-y,--assumeyes}'[answer yes for all questions]'
diff --git a/Completion/Redhat/Command/_rpm b/Completion/Redhat/Command/_rpm
index d00f88429..97f65cd6c 100644
--- a/Completion/Redhat/Command/_rpm
+++ b/Completion/Redhat/Command/_rpm
@@ -74,6 +74,7 @@ _rpm () {
   selectopts=(
     {-a,--all}'[query all packages]'
     {-f,--file}'[query packages that own specified files]'
+    '--path[query packages that own specified files, installed or not]'
     {-p,--package}'[query uninstalled packages]'
     {-g,--group}'[query packages in one of specified groups]'
     --pkgid --hdrid --tid --querybynumber
@@ -165,9 +166,7 @@ _rpm () {
         {-F+,--freshen}'[freshen mode]:*:upgrade:->upgrade'
         {-e+,--erase}'[uninstall mode]:*:uninstall:->uninstall'
         '--reinstall[reinstall mode]:*:install:->install'
-        '--setperms[set file permissions]:*:package:->setattrs'
-        '--setugids[set file owner/group]:*:package:->setattrs'
-        '--setcaps[set capabilities of files in the given package]:*:package:->setattrs'
+        '!--set'{perms,ugids,caps}':*:package:->setattrs'
         '--restore[restore owner, group, permissions and capabilities of files in the given package]:*:package:->setattrs'
       )
     ;;
@@ -261,13 +260,15 @@ _rpm () {
     install)
       _arguments -s -C \!{-i,--install,-U,--upgrade,-F,--freshen} $tmp \
         $commonopts $pathopts \
+        '(--nodb)--justdb[update the database but not the filesystem]' \
+        '(--justdb)--nodb[update the filesystem but not the database]' \
         '--excludepath=:file to exclude:_files -/' \
 	'--relocate:relocate:->relocate' \
         '--prefix=[relocate the package]:package prefix directory:_files -/' \
         '(-h --hash)'{-h,--hash}'[print hash marks as package installs]' \
 	'(--replacepkgs --replacefiles --oldpackage)--force' \
 	'(--force)--'{replacefiles,replacepkgs} \
-        --{aid,allfiles,badreloc,excludedocs,ignorearch,ignoreos,ignoresize,includedocs,justdb,percent,test} \
+        --{aid,allfiles,badreloc,excludedocs,ignorearch,ignoreos,ignoresize,includedocs,percent,test} \
         --no{deps,filedigest,contexts,caps,order,suggest,pre,post,preun,postun,trigger{s,in,un,postun}} \
 	'(--nopre --nopost --nopreun --nopostun)--noscripts' \
         '*:pkg file:->package_file'
@@ -275,7 +276,9 @@ _rpm () {
     uninstall)
       _arguments -s -C \!{-e,--erase} \
 	"${commonopts[@]}" "${pathopts[@]}" \
-	--{allmatches,justdb,repackage,test} \
+        '(--nodb)--justdb[update the database but not the filesystem]' \
+        '(--justdb)--nodb[update the filesystem but not the database]' \
+	--{allmatches,repackage,test} \
 	--no{deps,scripts,preun,postun,trigger{s,un,postun}} \
         '*:package:->package'
       ;;
diff --git a/Completion/Solaris/Command/_dumpadm b/Completion/Solaris/Command/_dumpadm
index 44d681ae0..aa1c058bb 100644
--- a/Completion/Solaris/Command/_dumpadm
+++ b/Completion/Solaris/Command/_dumpadm
@@ -16,7 +16,7 @@ _arguments -s \
   '-y[run savecore on reboot]' \
   '-c[set dump content]:dump content:(($content))' \
   '-d[set dump device]: : _alternative "tokens\:token\:(swap none)" "files\:block device\:_files -g \*\(-%b\)"' \
-  '-m[set minfree size]:size' \
+  '-m[set minfree size]: :_numbers size k m %' \
   '-s[set the savecore directory]:directory:_files -/' \
   '-r[alternate root directory]:directory:_files -/' \
   '-z[enable saving core files in a compressed format]:compression:(on off)'
diff --git a/Completion/Solaris/Command/_ipadm b/Completion/Solaris/Command/_ipadm
index 34d1eacba..c59fc8108 100644
--- a/Completion/Solaris/Command/_ipadm
+++ b/Completion/Solaris/Command/_ipadm
@@ -136,7 +136,7 @@ _ipadm() {
 	proto_icmp_properties=( "max_buf" "recv_buf" "send_buf" )
 	proto_all_properties=( $proto_ipv4_properties $proto_ipv6_properties $proto_tcp_properties
 		$proto_udp_properties $proto_sctp_properties $proto_icmp_properties )
-	proto_all_properties=( $^proto_all_properties:value:_ipadm_get_possible_values )
+	proto_all_properties=( ${^proto_all_properties}:value:_ipadm_get_possible_values )
 
 	proto_propproperties=( "proto" "property" "perm" "current" "persistent" "default" "possible" )
 
diff --git a/Completion/Solaris/Command/_pkg5 b/Completion/Solaris/Command/_pkg5
index bcd4e3daf..5524e4eda 100644
--- a/Completion/Solaris/Command/_pkg5
+++ b/Completion/Solaris/Command/_pkg5
@@ -378,6 +378,7 @@ _pkg5() {
 			'--non-sticky[Make this publisher non-sticky]' \
 			'--search-after[Set publisher search-order]:publisher:_pkg5_pubs' \
 			'--search-before[Set publisher search-order]:publisher:_pkg5_pubs' \
+			'--search-first[set the specified publisher first in the search order]' \
 			'--approve-ca-cert[Add trusted CA certificate]:CA cert path:_path_files' \
 			'--revoke-ca-cert[Revoke CA certificate]:CA cert hash:(${${certs#/etc/openssl/certs/}%.0})' \
 			'--unset-ca-cert[Remove trusted CA certificate]:CA cert hash:' \
diff --git a/Completion/Unix/Command/_ansible b/Completion/Unix/Command/_ansible
index 2d976b0a0..e0d9fb9b6 100644
--- a/Completion/Unix/Command/_ansible
+++ b/Completion/Unix/Command/_ansible
@@ -20,10 +20,11 @@ case $service in
   ;|
   ansible|ansible-console|ansible-playbook|ansible-pull)
     args+=(
-      '(-K --ask-become-pass)'{-K,--ask-become-pass}'[ask for privilege escalation password]'
-      '(-k --ask-pass)'{-k,--ask-pass}'[ask for connection password]'
+      '(-K --ask-become-pass --become-password-file)'{-K,--ask-become-pass}'[ask for privilege escalation password]'
+      '(-K --ask-become-pass)--become-password-file=[specify file containing become password]:file:_files'
+      '(-k --ask-pass --connection-password-file)'{-k,--ask-pass}'[ask for connection password]'
+      '(-k --ask-pass)--connection-password-file=[specify file containing connection password]:file:_files'
       '--list-hosts[output list of matching hosts]'
-      '(-l --limit)'{-l+,--limit=}'[further limit hosts to an additional pattern]:host subset:->hosts'
       '(-T --timeout)'{-T+,--timeout=}'[override the connection timeout]:timeout (seconds) [10]'
       '(-c --connection)'{-c+,--connection=}'[specify connection type]:connection type [smart]:->connect-types'
       '(-u --user)'{-u+,--user=}'[specify remote user for connection]:remote user:_users'
@@ -42,19 +43,19 @@ case $service in
       '(-f --forks)'{-f+,--forks=}'[specify number of parallel processes to use]:processes [5]'
       '--become-method=[specify privilege escalation method to use]:method [sudo]:(sesu sudo su pbrun pfexec doas dzdo ksu runas pmrun enable machinectl)'
       '--become-user=[specify remote user for running operations]:user:_users'
-      "--syntax-check[perform a syntax check on the playbook, but don't execute it]"
       '!(-R --su-user -U --sudo-user)'{-R,-U,--su-user,--sudo-user}':user [root]:_users'
     )
   ;|
   ansible|ansible-console|ansible-inventory|ansible-playbook|ansible-pull)
     args+=(
       --ask-vault-pass{,word}'[ask for vault password]'
-      '(-e --extra-vars)'{-e+,--extra-vars=}'[set additional variables]:key=value or YAML/JSON'
-      '--vault-id=[specify vault identity to use]:vault identity'
+      \*{-e+,--extra-vars=}'[set additional variables]:key=value, YAML/JSON or @file:->extra-vars'
+      '*--vault-id=[specify vault identity to use]:vault identity'
       --vault-pass{,word}-file='[specify vault password file]:vault password file:_files'
       \*{-i+,--inventory=}'[specify inventory host file or host list]: : _alternative "files\:inventory file\:_files"
 	"hosts\:host\: _sequence _hosts"'
       '!(-i --inventory)--inventory-file=:inventory file:_files'
+      '(-l --limit)'{-l+,--limit=}'[further limit hosts to an additional pattern]:host subset:->hosts'
     )
   ;|
   ansible|ansible-console|ansible-inventory)
@@ -68,6 +69,11 @@ case $service in
       "--skip-tags[only run plays and tasks whose tags don't match]"
     )
   ;|
+  ansible-playbook|ansible-console)
+    args+=(
+      '--step[one-step-at-a-time: confirm each task before running]'
+    )
+  ;|
   ansible|ansible-console)
     args+=(
       '--task-timeout[set the task timeout limit]:timeout (seconds)'
@@ -86,31 +92,26 @@ case $service in
     )
   ;;
   ansible-config)
-    args+=(
-      '(-c --config)'{-c+,--config=}'[specify configuration file]:config file:_files'
+    args=( -A "-*" $args
       '1:action:((
         list\:list\ all\ configuration
 	dump\:show\ the\ current\ settings,\ merge\ specified\ configuration
 	view\:display\ the\ current\ config\ file
+        init\:create\ initial\ configuration
       ))'
-    )
-    [[ -n $words[(r)dump] ]] && args+=( '--only-changed[only show configuration that is changed from the default]' )
-  ;;
-  ansible-console)
-    args+=(
-      '--step[one-step-at-a-time: confirm each task before running]'
+      '*::args:->config'
     )
   ;;
   ansible-doc)
     args+=(
-      '!--metadata-dump' # "internal testing only"
+      '!--metadata-dump' '!--no-fail-on-errors' # "internal use only"
       '(-l --list -F --list_files -s --snippet --metadata-dump -e --entry-point)'{-j,--json}'[change output to json format]'
       '(-l --list -F --list_files -s --snippet --metadata-dump -e --entry-point)'{-l,--list}'[list available plugins]'
       '(-l --list -F --list_files -s --snippet --metadata-dump -e --entry-point)'{-F,--list_files}'[show plugin names and their source files without summaries]'
-      '(-l --list -F --list_files -s --snippet --metadata-dump -e --entry-point)'{-s,--snippet}'[show playbook snippet for specified plugins]'
+      '(-l --list -F --list_files -s --snippet --metadata-dump -e --entry-point)'{-s,--snippet}'[show playbook snippet for inventory, lookup and module plugins]'
       '(-l --list -F --list_files -s --snippet -e --entry-point)--metadata-dump[dump json metadata for all plugins]'
       '(-l --list -F --list_files -s --snippet --metadata-dump -e --entry-point)'{-e+,--entry-point=}'[select the entry point for roles]:entry point'
-      '(-t --type)'{-t+,--type=}'[choose plugin type]:plugin type [module]:(become cache callback cliconf connection httpapi inventory lookup netconf shell vars module strategy role keyword)'
+      '(-t --type)'{-t+,--type=}'[choose plugin type]:plugin type [module]:(become cache callback cliconf connection httpapi inventory lookup netconf shell vars module strategy test filter role keyword)'
       '(-r --roles-path)'{-r+,--roles-path=}'[specify directory containing roles]:directory:_directories'
       '*:plugin:->plugins'
     )
@@ -145,6 +146,7 @@ case $service in
       '--list-tags[list all available tags]'
       '--list-tasks[list all tasks that would be executed]'
       '--start-at-task=[start the playbook at specified task]:task'
+      "--syntax-check[perform a syntax check on the playbook, but don't execute it]"
       '--key-file=[specify file to use to authenticate the connection]:private key file:_files'
       '*:playbook:_files -g "(#i)*.y(|a)ml"'
     )
@@ -218,18 +220,13 @@ case $state in
   ;;
   connect-types)
     plug=connection
-  ;&
-  plugins)
-    plugvar=_ansible_${plug}_plugins
-    typeset -ga ${plug}
-    if zstyle -T ":completion:${curcontext}:plugins" verbose; then
-      (( ${(P)#plugvar} )) || set -A ${plugvar} \
-	  ${${(f)"$(_call_program plugins ansible-doc -t $plug -l)"}/ ##/:}
-      _describe -t plugins "${plug} plugin" $plugvar -M 'r:|.=* r:|=*' && ret=0
+    state=plugins
+  ;;
+  extra-vars)
+    if compset -P '@'; then
+      _files -g "*.(json|yml|yaml|ini)(-.)" && ret=0
     else
-      (( ${(P)#plugvar} )) || set -A ${plugvar} \
-	  ${${(f)"$(_call_program plugins ansible-doc -t $plug -F)"}%% *}
-      _wanted plugins expl "${plug} plugin" compadd -M 'r:|.=* r:|=*' -a $plugvar && ret=0
+      _message 'key=value, YAML/JSON or @file'
     fi
   ;;
   tags)
@@ -237,9 +234,45 @@ case $state in
     _sequence _wanted tags expl tag compadd - \
         ${(s.,.)${(j.,.)${(M)${(f)"$(cat **/*.yml)"}:# #tags:*}#*: }} && ret=0
   ;;
+  config)
+    ign=''
+    curcontext="${curcontext%:*}-${words[1]}:"
+    (( $#words > 3 )) && ign='!'
+    args=(
+      "${ign}(-)"{-h,--help}'[display usage information]'
+      \*{-v,--verbose}'[verbose mode]'
+      '(-c --config)'{-c+,--config=}'[specify configuration file]:config file:_files'
+      '(-t --type)'{-t+,--type=}'[filter down to a specific plugin type]:plugin type [base]:(all base become cache callback cliconf connection httpapi inventory lookup netconf shell vars)'
+      '*:plugin:->plugins'
+    )
+    case $words[1] in
+      dump)
+        args+=(
+          '(--only-changed --changed-only)'{--only-changed,--changed-only}'[only show configuration that is changed from the default]'
+          '(-f --format)'{-f+,--format=}'[specify output format]:format:(json yaml display)'
+        )
+      ;;
+      init)
+        args+=(
+          '--format=[specify output format for init]:format:(init env vars)'
+          '--disabled[prefix all entries with a comment character]'
+        )
+      ;;
+      list)
+        args+=(
+          '(-f --format)'{-f+,--format=}'[specify output format]:format:(json yaml)'
+        )
+      ;;
+    esac
+    _arguments -s -S : $args && ret=0
+    plug=${(v)opt_args[(i)-(t|-type)]}
+    [[ $plug = base ]] && state=
+  ;;
   galaxy)
     ign=''
     gactions=( delete import info init install list remove search setup )
+    args=( "${ign}(-)"{-h,--help}'[display usage information]' )
+    (( $#words > 3 )) && ign='!'
     case ${(j.:.)line[1,3]} in
       (role|collection):*:*)
         subcmd="${line[1]}-${line[2]}"
@@ -253,18 +286,16 @@ case $state in
       [^:]#)
         words=( role "$words[@]" )
         (( CURRENT++ ))
+        args=()
       ;;
     esac
     curcontext="${curcontext%:*}-${subcmd}:"
-    (( $#words > 3 )) && ign='!'
-    args=(
-      "${ign}(-)"{-h,--help}'[display usage information]'
-      '1: :{ _wanted actions expl action compadd -a gactions }'
-    )
+    args+=( '1: :{ _wanted actions expl action compadd -a gactions }' )
     case $subcmd in
       *-*)
         args+=(
           '(-c --ignore-certs)'{-c,--ignore-certs}'[ignore SSL certificate validation errors]'
+          '--timeout=[specify time to wait for operations against the galaxy]:timeout (seconds) [60]'
           '(-s --server)'{-s+,--server=}'[specify API server destination]:server:_hosts'
           --{token,api-key}='[specify ansible galaxy API key]:api key'
           \*{-v,--verbose}'[verbose mode]'
@@ -403,4 +434,19 @@ case $state in
   ;;
 esac
 
+if [[ $state = plugins ]]; then
+  [[ -z $plug ]] && return ret
+  plugvar=_ansible_${plug}_plugins
+  typeset -ga ${plug}
+  if zstyle -T ":completion:${curcontext}:plugins" verbose; then
+    (( ${(P)#plugvar} )) || set -A ${plugvar} \
+        ${${${(f)"$(_call_program plugins ansible-doc -t $plug -l)"}:# *}/(:|) ##/:}
+    _describe -t plugins "${plug} plugin" $plugvar -M 'r:|.=* r:|=*' && ret=0
+  else
+    (( ${(P)#plugvar} )) || set -A ${plugvar} \
+        ${${(f)"$(_call_program plugins ansible-doc -t $plug -F)"}%%(|:) *}
+    _wanted plugins expl "${plug} plugin" compadd -M 'r:|.=* r:|=*' -a $plugvar && ret=0
+  fi
+fi
+
 return ret
diff --git a/Completion/Unix/Command/_ant b/Completion/Unix/Command/_ant
index 7401c7449..fd6112add 100644
--- a/Completion/Unix/Command/_ant
+++ b/Completion/Unix/Command/_ant
@@ -6,7 +6,8 @@ local curcontext="$curcontext" state line expl ret=1
 typeset -A opt_args
 local buildfile classpath cp userjars importedfiles target='*:target:->target' targets tmp
 
-find_targets() {
+(( $+functions[_ant_targets] )) ||
+_ant_targets() {
     importedfiles=( $(sed -n "s/ *<import[^>]* file=[\"']\([^\"']*\)[\"'].*/\1/p" < $1) )
     # Tweaked to omit targets beginning with "-" that can't
     # be invoked from the command line; see zsh-workers/24129.
@@ -14,12 +15,12 @@ find_targets() {
     if (( $#importedfiles )) ; then
         ( cd $1:h
             for file in $importedfiles ; do
-                expanded=( $(echo $file | sed -n "s|\${ant.home}|$ANT_HOME|p") )
-                if [[ ! "bla$expanded" = "bla" ]]; then
+                expanded=${file//\${ant.home}/$ANT_HOME}
+                if [[ "$expanded" != "$file" ]]; then
                     file=$expanded
                 fi
                 if [[ -f $file ]]; then
-                    find_targets $file
+                    _ant_targets $file
                 fi
         done )
     fi
@@ -79,8 +80,8 @@ case $state in
     compset -P '*:'
     compset -S ':*'
     _alternative \
-      "classpath:$state:_path_files -qS: -g '*.(jar|zip)(-.)'" \
-      "classpath:$state:_path_files -r': ' -/" && ret=0
+      "classpath:${state}:_path_files -qS: -g '*.(jar|zip)(-.)'" \
+      "classpath:${state}:_path_files -r': ' -/" && ret=0
   ;;
   property)
     if compset -P 1 '*='; then
@@ -122,20 +123,20 @@ case $state in
                         read default_target junk
                     fi
                     # Output target again indicating its the default one.
-                    print -n "'${default_target}:(Default target) ' "
+                    print -rn -- "${(qq):-${default_target}:(Default target)} "
                 ;;
                 (Searching:*|Main:targets:|Subtargets:|BUILD:SUCCESSFUL|Total:time:*)
                 ;;
                 (*)
                     # Return target and description
-                    print -n "'$ln' "
+                    print -rn -- "${(qq)ln} "
                 ;;
             esac
           done
         )//$'\015'}"
         _describe 'target' tmp && ret=0
       else
-        targets=( $(find_targets $buildfile) )
+        targets=( $(_ant_targets $buildfile) )
         _wanted targets expl target compadd -a targets && ret=0
       fi
     else
diff --git a/Completion/Unix/Command/_awk b/Completion/Unix/Command/_awk
index e8f4a2530..b69cc5cf8 100644
--- a/Completion/Unix/Command/_awk
+++ b/Completion/Unix/Command/_awk
@@ -50,6 +50,7 @@ case $variant in
       {-D-,--debug=-}'[enable debugging]::debugger command file:_files'
       {-g,--gen-pot}'[scan awk program and generate .po file on stdout]'
       '*'{-i+,--include}'[load source library]:library file:->script'
+      {-I,--trace}'[print internal byte code names as they are executed]'
       '*'{-l+,--load}'[load dynamic extension]:extension:->extension'
       {-M,--bignum}'[select arbitrary-precision arithmetic on numbers]'
       {-o-,--pretty-print=-}'[pretty-print awk program]::output file:_files'
diff --git a/Completion/Unix/Command/_cal b/Completion/Unix/Command/_cal
index 82bb98b5f..b92e8153f 100644
--- a/Completion/Unix/Command/_cal
+++ b/Completion/Unix/Command/_cal
@@ -1,28 +1,131 @@
 #compdef cal ncal
 
-local args
+local -a args
+args=()
 
 case $service in
   cal)
-    args=(
-      '-3[three in a row]'
-      '-m[Monday as first day of the week]'
-    )
+    # check util-linux's cal or bsdmainutils's cal
+    if $service --version 1>/dev/null 2>/dev/null ; then
+      args+=(
+        '(-1 --one)'{-1,--one}'[show only a single month]'
+        '(-3 --three)'{-3,--three}'[show three months spanning the date]'
+        '(-n --months)'{-n,--months=}"[show num months starting with date's month]:month"
+        '(-S --span)'{-S,--span}'[span the date when displaying multiple month]'
+        '(-s --sunday)'{-s,--sunday}'[Sunday as first day of week]'
+        '(-m --monday)'{-m,--monday}'[Monday as first day of week]'
+        '(-j --julian)'{-j,--julian}'[use day-of-year for all calendars]'
+        '--reform=[Gregorian reform date]:val:(1752 gregorian iso julian)'
+        '--iso[alias for --reform=iso]'
+        '(-y --year)'{-y,--year}'[show the whole year]'
+        '(-Y --twelve)'{-Y,--twelve}'[show the next twelve months]'
+        '(-w --week)'{-w,--week=-}'[show US or ISO-8601 week numbers]::num'
+        '(-v --vertical)'{-v,--vertical}'[show day vertically instead of line]'
+        '(-c --columns)'{-c,--columns=}'[amount of columns to use]:width'
+        '--color=-[colorize messages]:when:(auto always never)'
+        '(- *)'{-h,--help}'[display help]'
+        '(- *)'{-V,--version}'[display version]'
+      )
+    else
+      case $OSTYPE in
+        (linux*|openbsd*|freebsd*|netbsd*|darwin*|dragonfly*)
+          args+=(
+            '-j[display Julian days]'
+          )
+        ;|
+        (linux*|freebsd*|netbsd*|darwin*|dragonfly*)
+          args+=(
+            '-3[display the previous, current and next month surrounding today]'
+            '-A[months to add after]:months'
+            '-B[months to add before]:months'
+          )
+        ;|
+        (freebsd*|netbsd*|darwin*|dragonfly*)
+          args+=(
+            '-h[turns off highlighting of today]'
+          )
+        ;|
+        (netbsd*|openbsd*)
+          args+=(
+            '-y[display a calendar for the current year]'
+          )
+        ;|
+        (linux*|freebsd*|darwin*|dragonfly*)
+          args+=(
+            '-m[display the specified month]:month'
+            '-y[display a calendar for the specified year]:year'
+            '-C[switch to cal mode]'
+            '-d[use yyyy-mm as the current date]:yyyy-mm'
+          )
+        ;|
+        (freebsd*|darwin*|dragonfly*)
+          args+=(
+            '-N[switch to ncal mode]'
+          )
+        ;|
+        (linux*)
+          args+=(
+            '-1[display only the current month]'
+          )
+        ;|
+        (openbsd*)
+          args+=(
+            '-m[display weeks starting on Monday instead of Sunday]'
+            '-w[display week numbers in the month display]'
+          )
+        ;|
+        (netbsd*)
+          args+=(
+            '-C[display context months before and after the specified month]:months'
+            '-d[specifies the day of the week on which the calendar should start]:day_of_week'
+            '-h[highlight the current day]'
+            '-R[selects an alternate Gregorian reform point from the default of September 3rd, 1752]:reform-sp'
+            '-r[display the month in which the Gregorian Reform adjustment was applied]'
+          )
+        ;;
+      esac
+    fi
   ;;
   ncal)
     args=(
-      '-J[display Julian calendar]'
-      '-e[display date of western Easter]'
-      '-o[display date of orthodox Easter]'
-      '-p[assume as by ncal]'
-      '-s[country code]'
-      '-w[print number of the week below each column]'
+      '-h[turns off highlighting of today]'
+      '-J[display Julian Calendar]'
+      '-e[display date of Easter]'
+      '-j[display Julian days]'
+      '-o[display date of Orthodox Easter]'
+      '-m[display the specified month]:month'
+      '-p[print the country codes and switching days from Julian to Gregorian Calendar]'
+      '-s[assume the switch from Julian to Gregorian Calendar at the date associated with the country_code]:country_code'
+      '-w[print the number of the week below each week column]'
+      '-y[display a calendar for the specified year]:year'
+      '-3[display the previous, current and next month surrounding today]'
+      '-A[months to add after]:months'
+      '-B[months to add before]:months'
+      '-C[switch to cal mode]'
+      '-d[use yyyy-mm as the current date]:yyyy-mm'
+      '-H[use yyyy-mm-dd as the current date]:yyyy-mm-dd'
+      '-M[weeks start on Monday]'
+      '-S[weeks start on Sunday]'
+      '-W[first week of the year has at least number days]:number'
+      '-b[use oldstyle format for ncal output]'
     )
+
+    case $OSTYPE in
+      (linux*)
+        args+=(
+          '-b[use oldstyle format for ncal output]'
+          '-1[display only the current month]'
+        )
+        ;;
+      (*)
+        args+=(
+          '-N[switch to ncal mode]'
+        )
+        ;;
+    esac
   ;;
 esac
 
 _arguments "${args[@]}" \
-  '-j[display Julian days]' \
-  '-y[display a calendar for the current year]' \
   '::month' \
   ':year'
diff --git a/Completion/Unix/Command/_cat b/Completion/Unix/Command/_cat
index 74d7278b8..526c49e31 100644
--- a/Completion/Unix/Command/_cat
+++ b/Completion/Unix/Command/_cat
@@ -38,6 +38,9 @@ elif [[ "$OSTYPE" == (*bsd|dragonfly|darwin)* ]]; then
     '-B+[read with buffer of specified size]:size (bytes)'
     '-f[only attempt to display regular files]'
   )
+  [[ $OSTYPE = darwin* ]] && args+=(
+    '-l[set an exclusive advisory lock on standard output]'
+  )
 elif [[ $OSTYPE = solaris* ]]; then
   args=(
     -A "-*"
diff --git a/Completion/Unix/Command/_chown b/Completion/Unix/Command/_chown
index 9ebbf7bab..4362d6e75 100644
--- a/Completion/Unix/Command/_chown
+++ b/Completion/Unix/Command/_chown
@@ -43,7 +43,7 @@ case "$variant" in
       '(-H -L -P)-P[do not follow symlinks (default)]'
     )
     ;|
-  dragonfly*|freebsd*)
+  dragonfly*|freebsd*|darwin*)
     args+=(
       "-x[don't traverse file systems]"
     )
@@ -63,6 +63,11 @@ case "$variant" in
       '-s[owner and/or group are Windows SID strings]'
     )
     ;;
+  darwin*)
+    args+=(
+      '-n[interpret user and group as numeric, avoiding name lookups]'
+    )
+    ;;
 esac
 
 (( $+words[(r)--reference*] )) || args+=( '(--reference)1: :->owner' )
diff --git a/Completion/Unix/Command/_chroot b/Completion/Unix/Command/_chroot
index 516992694..a9c577bd7 100644
--- a/Completion/Unix/Command/_chroot
+++ b/Completion/Unix/Command/_chroot
@@ -33,7 +33,7 @@ case $variant in
     ;;
 esac
 
-args+=( '1:new root directory:_directories' '*:::command:_normal' )
+args+=( '1:new root directory:_directories' '*::: : _normal -p $service' )
 
 _arguments -s -S : $args && ret=0
 
diff --git a/Completion/Unix/Command/_cmp b/Completion/Unix/Command/_cmp
index 6d7bfb1b7..20d309e32 100644
--- a/Completion/Unix/Command/_cmp
+++ b/Completion/Unix/Command/_cmp
@@ -1,23 +1,29 @@
 #compdef cmp gcmp
 
-local args variant
+local args variant units
 _pick_variant -r variant gnu=GNU $OSTYPE --version
 
 case $variant in
-  gnu)
+  freebsd*|gnu)
     args=(
       '(-b --print-bytes)'{-b,--print-bytes}'[print differing bytes]'
       '(-i --ignore-initial)'{-i+,--ignore-initial}'[skip specified number of bytes]:bytes'
       '(-l --verbose -s --silent --quiet)'{-l,--verbose}'[output all differences]'
       '(-n --bytes)'{-n+,--bytes=}'[specify maximum bytes to compare]:bytes'
       '(-s --quiet --silent -l --verbose)'{-s,--quiet,--silent}'[return status alone signifies differences]'
+    )
+    units=":_numbers -u bytes offset K M G T P E Z Y"
+  ;|
+  gnu)
+    args=(
       '(- *)'{-v,--version}'[display version information]'
       '(- *)--help[display help information]'
     )
+    units+=" kB MB GB TB PB EB ZB YB"
   ;;
   netbsd*) args+=( "-c[don't use mmap]" ) ;|
   freebsd*|openbsd*)
-    args=(
+    args+=(
       "-h[don't follow symbolic links]"
       '-x[hexadecimal output and zero based offset index]'
       '-z[compare file sizes first]'
@@ -31,4 +37,4 @@ case $variant in
   ;;
 esac
 
-_arguments -s $args '1:file 1:_files' '2:file 2:_files' '::byte offset' '::byte offset'
+_arguments -s $args '1:file 1:_files' '2:file 2:_files' "::byte offset$units" "::byte offset$units"
diff --git a/Completion/Unix/Command/_column b/Completion/Unix/Command/_column
index 94bdccf0a..687d7620f 100644
--- a/Completion/Unix/Command/_column
+++ b/Completion/Unix/Command/_column
@@ -22,7 +22,7 @@ case $variant in
     aopts=()
     args=(
       '(info json -c --output-width)'{-c+,--output-width=}'[format output to fit display of specified width]:width'
-      '(info)'{-L,--table-empty-lines}"[don't ignore empty lines]"
+      '(info)'{-L,--keep-empty-lines}"[don't ignore empty lines]"
       + fill
       '(info table text json -x --fillrows)'{-x,--fillrows}'[print across before down]'
       + table
@@ -30,8 +30,20 @@ case $variant in
       '(info fill -o --output-separator)'{-o+,--output-separator=}'[specify column separator for table output]:separator [two spaces]'
       '(info fill -s --separator)'{-s+,--separator=}'[specify column delimiters in input data]:delimiters'
       '(info fill -O --table-order)'{-O+,--table-order=}'[specify order of output columns]: :->columns'
-      '(info fill -N --table-columns)'{-N+,--table-columns=}'[specify column names]:names'
+      '(info fill -N --table-columns)*'{-C+,--table-column=}'[specify column properties]: :_values -s, -S= property
+        "name[column name]\:name"
+        "trunc[truncate text in the columns when necessary]"
+        "right[right align text]"
+        "width[specify column width]\:width"
+        "strictwidth[strictly follow column width setting]"
+        "noextreme[allow length to be ignored]"
+        "wrap[wrap text when necessary]"
+        "hide[don'\''t print column]"
+        "json[define type for JSON output]\:type\:(string number boolean)"'
+      '(info fill -N --table-columns -C --table-column)'{-N+,--table-columns=}'[specify column names]:names'
+      '(info fill -l --table-columns-limit)'{-l+,--table-columns-limit=}'[specify maximum number of input columns]:columns'
       '(info fill -H --table-hide)'{-H+,--table-hide=}"[don't print specified columns]: :->columns"
+      '(info fill -m --table-maxout)'{-m,--table-maxout}'[fill all available space]'
       + text
       '(info fill json -d --table-noheadings)'{-d,--table-noheadings}"[don't print header]"
       '(info fill json -E --table-noextreme)'{-E+,--table-noextreme}"[specify columns where length can be ignored]: :->columns"
diff --git a/Completion/Unix/Command/_cp b/Completion/Unix/Command/_cp
index f7411055b..cb899cc28 100644
--- a/Completion/Unix/Command/_cp
+++ b/Completion/Unix/Command/_cp
@@ -32,7 +32,7 @@ if _pick_variant gnu=GNU unix --version; then
     '(-v --verbose)'{-v,--verbose}'[explain what is being done]' \
     '(-x --one-file-system)'{-x,--one-file-system}'[stay on this file system]' \
     '(--context)-Z[set destination SELinux security context]' \
-    '(-Z)--context=-[set destination SELinux security context]:: :_selinux_contexts' \
+    '(-Z)--context=-[set destination SELinux security context]:: :_selinux_contexts -a file_type' \
     '(- *)--help' '(- *)--version' \
     '*:file or directory:_files'
 else
@@ -51,14 +51,16 @@ else
     '(aix|hpux|irix|solaris)*' '-r[copy directories recursively]' \
     'solaris2.<9->*' '-@[preserve extended attributes]' \
     'solaris2.<11->*' '-/[preserve extended attributes and extended system attributes]' \
+    'solaris2.<11->*' '-z[fast relink(3C) based copy]' \
     '(darwin|dragonfly|freebsd)*' "(-f -i)-n[don't overwrite existing file]" \
     'netbsd*' "-N[don't copy file flags]" \
     '(darwin|dragonfly|freebsd|netbsd|openbsd)*' '-a[archive mode, same as -RpP]' \
-    '(dragonfly|freebsd)*' '-l[link files instead of copying]' \
+    '(dragonfly|freebsd|darwin)*' '-l[link files instead of copying]' \
     '(darwin|dragonfly|*bsd)*' '-v[show file names as they are copied]' \
     'darwin*' "-X[don't copy extended attributes or resource forks]" \
-    '(dragonfly|freebsd)*' "-x[don't traverse file systems]" \
-    'freebsd<10->.*' '-s[make symbolic links instead of copies of non-directories]'
+    '(dragonfly|freebsd|darwin)*' "-x[don't traverse file systems]" \
+    '(freebsd<10->.|darwin)*' '-s[make symbolic links instead of copies of non-directories]' \
+    'darwin*' '-c[copy files using clonefile(2)]'
   do
     [[ $OSTYPE = $~pattern ]] && args+=( $arg )
   done
diff --git a/Completion/Unix/Command/_cut b/Completion/Unix/Command/_cut
index d3b1e2b10..778439cf1 100644
--- a/Completion/Unix/Command/_cut
+++ b/Completion/Unix/Command/_cut
@@ -1,6 +1,7 @@
 #compdef cut gcut
 
 typeset -A _cut_args
+local -a args
 
 case $LANG in
   (de_DE.UTF-8)
@@ -45,7 +46,7 @@ if _pick_variant gnu="Free Soft" unix --version; then
     '*:file:_files'
 else
   case $OSTYPE in
-    freebsd*|dragonfly*) args+=( '(-d)-w[use whitespace as the delimiter]' ) ;;
+    freebsd*|dragonfly*|darwin*) args=( '(-d)-w[use whitespace as the delimiter]' ) ;;
   esac
   _arguments $args \
     "-b[${_cut_args[bytes]}]:list" \
diff --git a/Completion/Unix/Command/_date b/Completion/Unix/Command/_date
index 97c272830..f0053ec02 100644
--- a/Completion/Unix/Command/_date
+++ b/Completion/Unix/Command/_date
@@ -7,8 +7,8 @@ local -a opts args
 opts=( -s -w -C )
 
 if _pick_variant gnu="Free Software Foundation" unix --version; then
-  local d='(-d --date -f --file -r --reference -s --set)'
-  local f='(-I --iso-8601 -R --rfc-email --rfc-3339)'
+  local d='(-d --date -f --file -r --reference -s --set --resolution)'
+  local f='(-I --iso-8601 -R --rfc-email --rfc-3339 --resolution)'
   args=(
     $d{-d+,--date=}'[output date specified by string]:time string'
     '--debug[annotate parsed date and warn about questionable usage]'
@@ -16,9 +16,10 @@ if _pick_variant gnu="Free Software Foundation" unix --version; then
     $d{-r+,--reference=}'[output last modification time of specified file]:file:_files'
     $d{-s+,--set=}'[set time]:time string'
     $f{-I-,--iso-8601=-}'[display in ISO 8601 format]::precision:(date hours minutes seconds ns)'
+    '(-)--resolution[output the available resolution of timestamps]'
     $f{-R,--rfc-email}'[display in RFC5322 format]'
     $f'--rfc-3339=-[display in RFC 3339 format]:precision:(date seconds ns)'
-    '(-u --utc --universal)'{-u,--utc,--universal}'[display or set time in UTC]'
+    '(-u --utc --universal --resolution)'{-u,--utc,--universal}'[display or set time in UTC]'
     '(- :)--help[output help and exit]'
     '(- :)--version[output version info and exit]'
   )
@@ -43,12 +44,12 @@ else
 	'-f+[use specified format for input]:parsing format:_date_formats:new date'
       )
     ;|
-    dragonfly*|darwin*|netbsd*|openbsd*)
+    dragonfly*|netbsd*|openbsd*)
       args+=(
 	'-r+[output date specified by reference time]:seconds since epoch'
       )
     ;|
-    freebsd*)
+    freebsd*|darwin*)
       local -a alts
       alts=(
 	'seconds:sec:_guard "(0x[0-9a-fA-F]#|[0-9]#)" "seconds since epoch"'
@@ -56,27 +57,25 @@ else
       )
       args+=(
 	'-r+[reference time: file modification or literal time]:reference: _alternative $alts'
-	'(-R)-I-[display in ISO 8601 format]::precision:(date hours minutes seconds)'
       )
     ;|
     freebsd*|dragonfly*|darwin*)
       args+=(
+        '-R[display in RFC2822 format]'
+	'(-R)-I-[display in ISO 8601 format]::precision [date]:(date hours minutes seconds)'
 	"*-v+[adjust and print (but don't set) date]:[+-]value[ymwdHMS]"
       )
     ;|
-    freebsd<-12>.*|darwin*)
+    freebsd<-12>.*)
       args+=(
 	'-d+:daylight saving time value'
 	'-t+:minutes west of GMT'
       )
     ;|
-    freebsd*|dragonfly*)
-      args+=( '-R[display in RFC2822 format]' )
-    ;|
     openbsd*|netbsd*) args+=( '-a[gradually skew]' )
     ;|
-    openbsd*)
-      args+=( '-z[specify timezone for output]:time zone:_time_zone')
+    freebsd<14->.*|openbsd*)
+      args+=( '-z+[specify timezone for output]:time zone:_time_zone')
     ;|
     netbsd*)
       args+=( '-d[output date specified by string]:time string:' )
diff --git a/Completion/Unix/Command/_dbus b/Completion/Unix/Command/_dbus
index 37b5458d7..d2a93152c 100644
--- a/Completion/Unix/Command/_dbus
+++ b/Completion/Unix/Command/_dbus
@@ -8,11 +8,13 @@ case $service in
   dbus-send)
     _arguments -A "--*" -C \
       '(--session)--system' '(--system)--session' \
-      '--address=-:bus address:->addresses' \
+      '--bus=-:bus address:->addresses' \
+      '--peer=-:bus address:->addresses' \
       '--dest=-:connection:->connections' \
       '--print-reply=-::format:(literal)' \
       '--reply-timeout=-:timeout (ms)' \
-      '--type=-:type:(method_call signal)' \
+      '--sender=-:name' \
+      '--type=-:type [signal]:(method_call signal)' \
       '(* -)--help' \
       ':object path:->objectpaths' \
       ':message name:->methods' \
diff --git a/Completion/Unix/Command/_dd b/Completion/Unix/Command/_dd
index 10682bc8e..c55efb68c 100644
--- a/Completion/Unix/Command/_dd
+++ b/Completion/Unix/Command/_dd
@@ -74,7 +74,7 @@ case $variant in
     vals+=(
       'status[specify level of information to print to stderr]:level:(none noxfer progress)'
     )
-    flags+=( fullblock noatime nocache count_bytes skip_bytes seek_bytes )
+    flags+=( fullblock noatime nocache )
     conv+=( excl nocreat fdatasync fsync )
     units=( c:1 w:2 b:512 kB:1000 K:1024 MB:1000^2 M:1024\^2 GB G TB T PB P EB E ZB Z YB Y )
   ;;
diff --git a/Completion/Unix/Command/_dig b/Completion/Unix/Command/_dig
index 3081e2cfd..c09bebbe5 100644
--- a/Completion/Unix/Command/_dig
+++ b/Completion/Unix/Command/_dig
@@ -6,8 +6,9 @@ local -a alts args
   '*+'{no,}'tcp[use TCP instead of UDP for queries]'
   '*+'{no,}'ignore[ignore truncation in UDP responses]'
   '*+domain=[set search list to single domain]:domain:_hosts'
-  '*+dscp=[set DSCP code point for query]:code point (0..63)'
+  '!*+dscp=:code point (0..63)'
   '*+'{no,}'search[use search list defined in resolv.conf]'
+  '!*+'{no,}defname
   '*+'{no,}'showsearch[show intermediate results in domain search]'
   '*+split[split hex/base64 fields into chunks]:width (characters) [56]'
   '*+'{no,}'aaonly[set aa flag in the query]'
@@ -18,6 +19,7 @@ local -a alts args
   '*+'{no,}'class[display the CLASS whening printing the record]'
   '*+'{no,}'cookie[add a COOKIE option to the request]'
   '*+'{no,}'crypto[display cryptographic fields in DNSSEC records]'
+  '*+'{no,}'dns64prefix[get the DNS64 prefixes from ipv4only.arpa]'
   '*+edns=[specify EDNS version for query]:version (0-255)'
   '*+noedns[clear EDNS version to be sent]'
   '*+ednsflags=[set EDNS flags bits]:flags'
@@ -27,11 +29,15 @@ local -a alts args
   '*+'{no,}'expandaaaa[expand AAAA records]'
   '*+'{no,}'expire[send an EDNS Expire option]'
   '*+'{no,}'header-only[send query without a question section]'
+  '*+'{no,}'https=[DNS-over-HTTPS POST mode]::endpoint [/dns-query]'
+  '!*+'{no,}'https-post=::endpoint [/dns-query]'
+  '*+'{no,}'https-get=[DNS-over-HTTPS GET mode]::endpoint [/dns-query]'
+  '*+'{no,}'http-plain=[DNS-over-HTTP POST mode]::endpoint [/dns-query]'
+  '*+'{no,}'http-plain-get=[DNS-over-HTTP GET mode]::endpoint [/dns-query]'
   '*+'{no,}'idnin[set processing of IDN domain names on input]'
   '*+'{no,}'idnout[set conversion of IDN puny code on output]'
   '*+'{no,}'keepalive[request EDNS TCP keepalive]'
   '*+'{no,}'keepopen[keep TCP socket open between queries]'
-  '*+'{no,}'mapped[allow mapped IPv4 over IPv6 to be used]'
   '*+'{no,}'recurse[set the RD (recursion desired) bit in the query]'
   '*+'{no,}'nssearch[search all authoritative nameservers]'
   '*+opcode[set DNS message opcode of the request]:opcode [QUERY]:(QUERY IQUERY STATUS NOTIFY UPDATE)'
@@ -39,10 +45,12 @@ local -a alts args
   '*+'{no,}'trace[trace delegation down from root]'
   '*+'{no,}'cmd[print initial comment in output]'
   '*+'{no,}'short[print terse output]'
+  '*+'{no,}'showbadcookie[show BADCOOKIE message]'
   '*+'{no,}'identify[print IP and port of responder]'
   '*+'{no,}'comments[print comment lines in output]'
   '*+'{no,}'stats[print statistics]'
   '*+padding[set padding block size]:size [0]'
+  '*+qid=[specify query ID]:query ID'
   '*+'{no,}'qr[print query as it was sent]'
   '*+'{no,}'question[print question section of a query]'
   '*+'{no,}'raflag[set RA flag in the query]'
@@ -52,6 +60,11 @@ local -a alts args
   '*+'{no,}'subnet[send EDNS client subnet option]:addr/prefix-length'
   '*+'{no,}'tcflag[set TC flag in the query]'
   '*+timeout=[set query timeout]:timeout (seconds) [5]'
+  '*+'{no,}'tls[DNS-over-TLS mode]'
+  '*+'{no,}"tls-ca=[enable remote server's TLS certificate validation]:file:_files"
+  '*+'{no,}"tls-hostname=[explicitly set the expected TLS hostname]:hostname"
+  '*+'{no,}'tls-certfile=[load client TLS certificate chain from file]:file:_files'
+  '*+'{no,}'tls-keyfile=[load client TLS private key from file]:file:_files'
   '*+tries=[specify number of UDP query attempts]:tries'
   '*+retry=[specify number of UDP query retries]:retries'
   '*+'{no,}'rrcomments[set display of per-record comments]'
@@ -65,7 +78,6 @@ local -a alts args
   '*+'{no,}'nsid[include EDNS name server ID request in query]'
   '*+'{no,}'ttlid[display the TTL whening printing the record]'
   '*+'{no,}'ttlunits[display the TTL in human-readable units]'
-  '*+'{no,}'unexpected[print replies from unexpected sources]'
   '*+'{no,}'unknownformat[print RDATA in RFC 3597 "unknown" format]'
   '*+'{no,}'yaml[present the results as YAML]'
   '*+'{no,}'zflag[set Z flag in query]'
diff --git a/Completion/Unix/Command/_dmidecode b/Completion/Unix/Command/_dmidecode
index 047b74f6d..e2c511313 100644
--- a/Completion/Unix/Command/_dmidecode
+++ b/Completion/Unix/Command/_dmidecode
@@ -4,6 +4,7 @@ _arguments -s \
   '(-d --dev-mem --from-dump)'{-d+,--dev-mem=}'[read memory from specified file]:memory device [/dev/mem]:_files' \
   '(-)'{-h,--help}'[display usage information]' \
   '(-q --quiet -u --dump)'{-q,--quiet}'[be less verbose]' \
+  '--no-quirks[decode everything without quirks]' \
   '(-t --type -H --handle -u --dump --dump-bin -s --string)'{-s+,--string=}'[only display value of specified DMI string]:DMI string:(bios-vendor bios-version bios-release-date system-manufacturer system-product-name system-version system-serial-number system-uuid baseboard-manufacturer baseboard-product-name baseboard-version baseboard-serial-number baseboard-asset-tag chassis-manufacturer chassis-type chassis-version chassis-serial-number chassis-asset-tag processor-family processor-manufacturer processor-version processor-frequency)' \
   '(-s --string -H --handle --dump-bin)*'{-t+,--type=}'[only display entries of specified type]:entry type:(bios system baseboard chassis processor memory cache connector slot)' \
   '(-s --string -t --type -H --handle --dump-bin)'{-H,--handle=}'[only display the entry of specified handle]:handle' \
diff --git a/Completion/Unix/Command/_du b/Completion/Unix/Command/_du
index 711f43471..ccb5bdd94 100644
--- a/Completion/Unix/Command/_du
+++ b/Completion/Unix/Command/_du
@@ -55,7 +55,7 @@ else
   )
   local xdev='[skip directories on different filesystems]'
   for pattern arg in \
-    'freebsd*' '-A[apparent size instead of usage]' \
+    '(freebsd|darwin)*' '-A[apparent size instead of usage]' \
     '(darwin*|*bsd*|dragonfly*|solaris2.<10->)' '(-H -L -P)-H[follow symlinks on the command line]' \
     '(darwin|*bsd|dragonfly)*' '(-H -L -P)-P[do not follow symlinks (default)]' \
     '(darwin|dragonfly|freebsd)*' '*-I+[ignore files/directories matching specified mask]:mask' \
@@ -64,12 +64,12 @@ else
     'netbsd*' '-i[output inode usage instead of blocks]' \
     '(darwin*|freebsd*|netbsd*|solaris2.<11->)' '(-h -k -g -B)-m[use block size of 1M-byte]' \
     '(darwin|freebsd<8->.|netbsd)*' '(-h -k -m -B)-g[use block size of 1G-byte]' \
-    'freebsd*' '(-h -k -m -g)-B+[block size]:block size (bytes)' \
+    '(freebsd|darwin)*' '(-h -k -m -g)-B+[block size]:block size (bytes)' \
     '(darwin|*bsd|dragonfly)*' '-c[display grand total]' \
-    'freebsd*' '-l[count sizes many times if hard linked]' \
+    '(freebsd|darwin)*' '-l[count sizes many times if hard linked]' \
     '(freebsd|netbsd)*' '-n[ignore files and directories with nodump flag set]' \
     'solaris*' "(-a)-o[don't add child directories' usage to parent's total]" \
-    'freebsd<8->.*' '-t+[report only entries for which size exceeds threshold]:threshold' \
+    '(freebsd|darwin)*' '-t+[report only entries for which size exceeds threshold]:threshold' \
     'solaris*' "-d$xdev" \
     '(darwin|*bsd|dragonfly|solaris)*' "-x$xdev"
   do
diff --git a/Completion/Unix/Command/_elfdump b/Completion/Unix/Command/_elfdump
index 065f4b97f..b3cc77695 100644
--- a/Completion/Unix/Command/_elfdump
+++ b/Completion/Unix/Command/_elfdump
@@ -34,10 +34,15 @@ case $OSTYPE in
       '-l[show long section names without truncation]'
       '-O[specify osabi to apply]:osabi'
       '-P[use alternative section header]'
-      "*:elf file:_object_files"
     )
   ;;
-  freebsd*) args+=( '-a[dump all information]' ) ;;
+  freebsd*)
+    args+=(
+      '-a[dump all information]'
+      '(-)-E[return success if file is an ELF file and failure if not]'
+    )
+  ;;
 esac
 
-_arguments -s $args
+_arguments -s $args \
+  "*:elf file:_object_files"
diff --git a/Completion/Unix/Command/_enscript b/Completion/Unix/Command/_enscript
index 3e09da5a4..4658ae4bc 100644
--- a/Completion/Unix/Command/_enscript
+++ b/Completion/Unix/Command/_enscript
@@ -128,7 +128,7 @@ case "$state" in
     local suf='{'
     compquote suf
     if [[ ${PREFIX} = *[%$]D${suf}[^}]# ]]; then
-      _strftime
+      _date_formats
     elif [[ ${(Q)PREFIX} = *\$\([^\)]# ]]; then
       compset -P '*\('
       _parameters -g '*export*' -S '\)'
diff --git a/Completion/Unix/Command/_env b/Completion/Unix/Command/_env
index a5dd49d37..8cf0ad467 100644
--- a/Completion/Unix/Command/_env
+++ b/Completion/Unix/Command/_env
@@ -9,6 +9,7 @@ case $variant in
     (( $#words > 2 )) && ign='!'
     args=(
       '(-)'{-i,--ignore-environment}'[start with empty environment]'
+      '(* -0 --null)'{-0,--null}'[end each output line with NUL, not newline]'
       '(--ignore-environment -i --help --version)*'{-u+,--unset=}'[remove variable from the environment]:env var to remove:_parameters -g "*export*"'
       '(-C --chdir)'{-C+,--chdir=}'[change working directory]:directory:_directories'
       '(-S --split-string)'{-S+,--split-string=}'[perform word splitting]:string to split'
@@ -23,11 +24,13 @@ case $variant in
   ;;
   freebsd*)
     args=(
-      '-0[use NUL, not newline after each variable in output]'
       '-L[add variables from system login.conf(5)]: :->user-class'
       '-U[add variables from user and system login.conf(5)]: :->user-class'
     )
   ;|
+  freebsd*|darwin*)
+    args=( '-0[use NUL, not newline after each variable in output]' )
+  ;|
   freebsd*|darwin*|dragonfly*)
     args+=(
       '(-i)*-u+[remove variable from the environment]:env var to remove:_parameters -g "*export*"'
@@ -58,7 +61,7 @@ if [[ -n $state ]]; then
         shift words
         (( CURRENT-- ))
       done
-      _normal && ret=0
+      _normal -p env && ret=0
     ;;
     user-class)
       if compset -P 1 '*/'; then
diff --git a/Completion/Unix/Command/_ffmpeg b/Completion/Unix/Command/_ffmpeg
index 1329939cd..e5afdac4f 100644
--- a/Completion/Unix/Command/_ffmpeg
+++ b/Completion/Unix/Command/_ffmpeg
@@ -125,7 +125,7 @@ local -a _ffmpeg_argspecs
                 lastopt_description=${lastopt_description//:/\\:}
                 if [[ $example == filename ]]; then
                     lastopt_takesargs=0
-                    lastopt+=":$lastopt_description:_files"
+                    lastopt+=":${lastopt_description}:_files"
                 elif [[ $lastopt == -[asv]pre ]]; then
                     lastopt_takesargs=0
                     lastopt="*$lastopt"
diff --git a/Completion/Unix/Command/_find b/Completion/Unix/Command/_find
index 560b77f7e..4f1c338ee 100644
--- a/Completion/Unix/Command/_find
+++ b/Completion/Unix/Command/_find
@@ -115,14 +115,14 @@ case $variant in
       '*-readable'
       '*-writable'
       '*-xtype:file type:((b\:block\ special\ file c\:character\ special\ file d\:directory p\:named\ pipe f\:normal\ file l\:symbolic\ link s\:socket))'
-      '-files0-from[start recursing from targets in given file]:NUL-separated targets file:_files'
+      '(*)-files0-from[start recursing from targets in given file]:NUL-separated targets file:_files'
       '*-fls:output file:_files'
       '*-fprint:output file:_files'
       '*-fprint0:output file:_files'
       '*-fprintf:output file:_files:output format'
       '*-printf:output format'
     )
-    [[ $OSTYPE = linux-gnu ]] && args+=( '*-context:SELinux context (glob pattern):_selinux_contexts' )
+    [[ $OSTYPE = linux-gnu ]] && args+=( '*-context:SELinux context (glob pattern):_selinux_contexts -a file_type' )
   ;;
 esac
 
diff --git a/Completion/Unix/Command/_flac b/Completion/Unix/Command/_flac
index 82b6f0160..1773061ee 100644
--- a/Completion/Unix/Command/_flac
+++ b/Completion/Unix/Command/_flac
@@ -85,6 +85,7 @@ case $service in
       '(-p --qlp-coeff-precision-search -q --qlp-coeff-precision)'{-p,--qlp-coeff-precision-search}'[exhaustively search LP coeff quantization]' \
       '(-p --qlp-coeff-precision-search -q --qlp-coeff-precision)'{-q,--qlp-coeff-precision=}'[specify precision]:precision (bits)' \
       '(-r --rice-partition-order)'{-r,--rice-partition-order=}'[set min/max residual partition order]:order' \
+      "--limit-min-bitrate[don't allow frames consisting of only constant subframes]" \
       '--endian=:byte order:(big little)' \
       '--channels=:channels' \
       '--bps=:bits per sample' \
diff --git a/Completion/Unix/Command/_gcc b/Completion/Unix/Command/_gcc
index ac0e8fda3..8690c5599 100644
--- a/Completion/Unix/Command/_gcc
+++ b/Completion/Unix/Command/_gcc
@@ -1318,11 +1318,13 @@ fi
 
 local -a sanitizers
 sanitizers=(
-  address alignment bool bounds enum float-cast-overflow float-divide-by-zero
-  integer-divide-by-zero memory nonnull-attribute null nullability-arg
-  nullability-assign nullability-return object-size pointer-overflow return
-  unsigned-integer-overflow returns-nonnull-attribute shift signed-integer-overflow
-  unreachable vla-bound vptr
+  address alignment bool bounds bounds-strict enum builtin float-cast-overflow
+  float-divide-by-zero hwaddress integer-divide-by-zero kernel-address
+  kernel-hwaddress leak memory nonnull-attribute null nullability-arg nullability-assign
+  nullability-return object-size pointer-compare pointer-overflow pointer-subtract return
+  returns-nonnull-attribute shadow-call-stack shift shift-base shift-exponent
+  signed-integer-overflow thread undefined unsigned-integer-overflow unreachable
+  vla-bound vptr
 )
 
 local -a languages
@@ -1892,7 +1894,7 @@ args+=(
   '-freschedule-modulo-scheduled-loops[enable/disable the traditional scheduling in loops that already passed modulo scheduling]'
   '-frounding-math[disable optimizations that assume default FP rounding behavior]'
   '-frtti[generate run time type descriptor information]'
-  "-fsanitize=-[enable AddressSanitizer, a memory error detector]:style:($sanitizers)"
+  "*-fsanitize=-[enable AddressSanitizer, a memory error detector]:style:->sanitize"
   '-fsched2-use-superblocks[if scheduling post reload, do superblock scheduling]'
   '-fsched-critical-path-heuristic[enable the critical path heuristic in the scheduler]'
   '-fsched-dep-count-heuristic[enable the dependent count heuristic in the scheduler]'
@@ -2282,6 +2284,9 @@ archgeneric)
   arch+=(generic)
   _wanted cputypes expl "CPU type" compadd -a arch && ret=0
   ;;
+sanitize)
+  _values -s , 'sanitizer' $sanitizers
+  ;;
 esac
 
 return ret
diff --git a/Completion/Unix/Command/_gcore b/Completion/Unix/Command/_gcore
index a31a81267..ef3afd919 100644
--- a/Completion/Unix/Command/_gcore
+++ b/Completion/Unix/Command/_gcore
@@ -46,6 +46,7 @@ case $OSTYPE in
     _arguments -s \
       '-c+[write core file to specified file]:file:_files' \
       '-f[dump all available segments]' \
+      '-k[use the ptrace(2) PT_COREDUMP kernel facility to write the core dump]' \
       '::executable:' \
       ':pid:_pids'
   ;;
diff --git a/Completion/Unix/Command/_gem b/Completion/Unix/Command/_gem
index 7d81619bb..c5a64cdf1 100644
--- a/Completion/Unix/Command/_gem
+++ b/Completion/Unix/Command/_gem
@@ -20,6 +20,7 @@ lropts=( $proxy
 _arguments -C -s \
   '(* -)'{-h,--help}'[display usage information]' \
   '(* -)'{-v,--version}'[display version information]' \
+  '-C[change directory first]:directory:_directories' \
   '*::command:->command' && ret=0
 
 if [[ $state = command ]]; then
@@ -27,7 +28,7 @@ if [[ $state = command ]]; then
     cmd=subcommands
   else
     cmds=(
-      build cert check cleanup contents dependency environment fetch
+      build cert check cleanup contents dependency environment exec fetch
       generate_index help install info list lock mirror open outdated owner
       pristine push query rdoc search server signin signout sources
       specification stale uninstall unpack update which yank
@@ -87,13 +88,13 @@ if [[ $state = command ]]; then
         '!(-d --details)--no-details'
       )
     ;|
-    check|contents|dependency|fetch|install|list|open|pristine|query|rdoc|search|specification|uninstall|unpack|yank)
+    check|contents|dependency|exec|fetch|install|list|open|pristine|query|rdoc|search|specification|uninstall|unpack|yank)
       args+=( '(-v --version)'{-v,--version=}'[specify version of gem]:version' )
     ;|
-    dependency|fetch|install|outdated|specification|uninstall|update|yank)
+    build|dependency|fetch|install|outdated|specification|uninstall|update|yank)
       args+=( '--platform=[specify the platform of gem]:platform' )
     ;|
-    dependency|fetch|install|list|query|search|specification|update)
+    dependency|exec|fetch|install|list|query|search|specification|update)
       args+=( '--prerelease[include prerelease versions of a gem]' '!(--prerelease)--no-prerelease' )
     ;|
     install|unpack|update)
@@ -125,13 +126,13 @@ if [[ $state = command ]]; then
     ;|
     (un|)install|pristine|update)
       args+=(
+        '(-i --install-dir)'{-i,--install-dir=}'[specify gem repository directory to get installed gems]:directory:_directories'
         '(-n --bindir)'{-n,--bindir=}'[specify directory where binary files are located]:directory:_directories'
       )
     ;|
     (un|)install|update)
       args+=(
         '--ignore-dependencies[ignore dependency requirements]'
-        '(-i --install-dir)'{-i,--install-dir=}'[specify gem repository directory to get installed gems]:directory:_directories'
       )
     ;|
     owner|push)
@@ -166,6 +167,7 @@ if [[ $state = command ]]; then
         '(-b --build)'{-b,--build=}'[build private key and self-signed certificate for specified email address]:email address:_email_addresses -c'
         '(-C --certificate)'{-C,--certificate=}'[specify signing certificate for --sign]:certificate'
         '(-K --private-key)'{-K,--private-key=}'[specify key for --sign or --build]:key'
+        '(-A --key-algorithm)'{-A,--key-algorithm=}'[select which key algorithm to use for --build]:algorithm'
         '(-s --sign)'{-s,--sign=}'[sign specified certificate with the key from -K and the certificate from -C]:certificate'
         '(-d --days)'{-d,--days=}'[specify days before certificate expires]:days'
         '(-R --re-sign)'{-R,--re-sign}'[re-sign the certificate]'
@@ -181,7 +183,7 @@ if [[ $state = command ]]; then
     ;;
     cleanup)
       args+=(
-        '(-n -d --dryrun)'{-n,-d,--dryrun}"[don't uninstall gems]"
+        '(-n -d --dry-run)'{-n,-d,--dry-run}"[don't uninstall gems]"
         "--user-install[cleanup in user's home directory instead of GEM_HOME]"
       )
     ;;
@@ -201,11 +203,20 @@ if [[ $state = command ]]; then
       )
     ;;
     environment)
-      args+=( '1:information:(gemdir gempath version remotesources platform)' )
+      args+=( '1:information:(gemdir gempath home path user_gemhome version remotesources platform)' )
+    ;;
+    exec)
+      args+=(
+        '--conservative[prefer most recent installed version to the overall latest]'
+        '1:gem:->gems-remote'
+        '*: :_default'
+      )
     ;;
     fetch)
       def=( both \! local \! remote \! )
-      args+=( ${(e)lropts} )
+      args+=( ${(e)lropts}
+        "--no-suggestions[don't suggest alternates when gems are not found]"
+      )
     ;;
     generate_index)
       args+=(
@@ -232,13 +243,15 @@ if [[ $state = command ]]; then
       args+=(
         '(*)*--skip=[with --all, skip specified gem]:installed gem:->gems-local'
         "--no-extensions[don't restore gems with extensions in addition to regular gems]"
+        '--only-missing-extensions[only restore gems with missing extensions]'
         '--only-executables[only restore executables]'
+        '--only-plugins[only restore plugins]'
       )
     ;;
     push)
       args+=( '1:gem file:_files -g "*.gem(-.)"' )
     ;;
-    query)
+    query) # deprecated
       args+=(
         '(-n --name-matches)'{-n,--name-matches=}'[specify regex to match against gem names]:gem name (regex):->gems-local'
       )
@@ -266,6 +279,7 @@ if [[ $state = command ]]; then
         '(-r --remove)'{-r,--remove=}'[remove source]:source URI:_urls'
         '(-c --clear-all)'{-c,--clear-all}'[remove all sources (clear the cache)]'
         '(-u --update)'{-u,--update}'[update source cache]'
+        '(-f --force)'{-f,--force}"[don't show any confirmation prompts]"
       )
     ;;
     specification)
@@ -319,7 +333,7 @@ if [[ $state = command ]]; then
     '--norc[avoid loading any .gemrc file]' && ret=0
 
   if [[ $state == gems* ]]; then
-    filter=( ${${opt_args[(I)-([lbr]|-local|-remote|-both)]}:-${${(M)state:#*-*}/gems-/--}} )
+    filter=( ${${opt_args[(I)-([lbr]|-conservative|-local|-remote|-both)]/conservative/local}:-${${(M)state:#*-*}/gems-/--}} )
     _description gems expl gem
     compadd "$expl[@]" ${${(f)"$(_call_program gems gem list $filter -q --no-versions)"}%% *} && ret=0
   fi
diff --git a/Completion/Unix/Command/_getent b/Completion/Unix/Command/_getent
index b96852db3..5604e526e 100644
--- a/Completion/Unix/Command/_getent
+++ b/Completion/Unix/Command/_getent
@@ -8,6 +8,7 @@ typeset -A opt_args
 if _pick_variant -r is_gnu gnu='(Free Soft|GNU|GLIBC|Gentoo)' unix --version; then
   args+=(
     '(- 1 *)'{-\?,--help}'[display help information]'
+    '(-A --no-addrconfig)'{-A,--no-addrconfig}"[don't filter out unsupported IPv4/IPv6 addresses (with ahosts*)]"
     '(- 1 *)--usage[display a short usage message]'
     '(- 1 *)'{-V,--version}'[display version information]'
     '*'{-s+,--service=}'[specify service configuration to use]: :->services'
@@ -23,7 +24,7 @@ case $state in
   services)
     # @todo GNU getent supports both `-s svc` and `-s db:svc`; we only complete
     # the former here
-    services=( {,/usr}/lib/{,*-linux-gnu/}libnss_*(N-.:fr:t:s/libnss_//) )
+    services=( {,/usr}/lib{,64}/{,*-linux-gnu/}libnss_*(N-.:fr:t:s/libnss_//) )
     _wanted services expl 'service or database:service' \
       compadd ${(u)services%-*} \
     && ret=0
diff --git a/Completion/Unix/Command/_git b/Completion/Unix/Command/_git
index cecb80ac3..7370aaead 100644
--- a/Completion/Unix/Command/_git
+++ b/Completion/Unix/Command/_git
@@ -76,17 +76,21 @@ _git-add () {
 
   case $state in
     (file)
-      declare -a ignored_files_alternatives
+      declare -a file_alternatives
+      if [[ -z ${opt_args[(I)-u|--update]} ]]; then
+        file_alternatives=(
+          'other-files::__git_ignore_line_inside_arguments __git_other_files'
+        )
+      fi
       if [[ -n ${opt_args[(I)-f|--force]} ]]; then
-        ignored_files_alternatives=(
+        file_alternatives+=(
           'ignored-modified-files:ignored modified file:__git_ignore_line_inside_arguments __git_modified_files --ignored'
           'ignored-other-files:ignored other file:__git_ignore_line_inside_arguments __git_other_files --ignored')
       fi
 
       _alternative \
         'modified-files::__git_ignore_line_inside_arguments __git_modified_files' \
-        'other-files::__git_ignore_line_inside_arguments __git_other_files' \
-        $ignored_files_alternatives && ret=0
+        $file_alternatives && ret=0
       ;;
   esac
 
@@ -119,7 +123,10 @@ _git-am () {
     $apply_options \
     '--quit[abort the patching operation but keep HEAD where it is]' \
     '--show-current-patch=-[show the message being applied]::show [raw]:(diff raw)' \
+    '(--empty)--allow-empty[record the empty patch as an empty commit]' \
+    '(--allow-empty)--empty=[select hanndling of empty patches]:handling:(stop drop keep)' \
     '(-i --interactive)'{-i,--interactive}'[apply patches interactively]' \
+    '(-n --no-verify)'{-n,--no-verify}'[bypass pre-applypatch and applypatch-msg hooks]' \
     '--committer-date-is-author-date[use author date as committer date]' \
     '--ignore-date[use committer date as author date]' \
     '--skip[skip the current patch]' \
@@ -160,8 +167,10 @@ _git-archive () {
     '--format=-[format of the resulting archive]:archive format:__git_archive_formats' \
     '(- :)'{-l,--list}'[list available archive formats]' \
     '(-v --verbose)'{-v,--verbose}'[report progress to stderr]' \
+    '--mtime=[set modification time of archive entries]:mtime' \
     '--prefix=-[prepend the given path prefix to each filename]:path prefix:_directories -r ""' \
     '--add-file=[add untracked file to archive]:file:_files' \
+    '--add-virtual-file=[add untracked file to archive]:path:_files' \
     '(-o --output)'{-o+,--output=}'[write archive to specified file]:archive:_files' \
     '--worktree-attributes[look for attributes in .gitattributes in working directory too]' \
     $backend_args \
@@ -329,7 +338,8 @@ _git-branch () {
     "(- :)--show-current[show current branch name]" \
     "($l $m $d)--create-reflog[create the branch's reflog]" \
     "($l $m $d -f --force)"{-f,--force}'[force the creation of a new branch]' \
-    "($l $m $d -t --track)"{-t,--track}'[setup configuration so that pull merges from the start point]' \
+    "($l $m $d --track)-t[setup configuration so that pull merges from the start point]" \
+    "($l $m $d -t)--track=-[setup configuration so that pull merges from the start point]::upstream tracking:(direct inherit)" \
     "($l $m $d)--no-track[override the branch.autosetupmerge configuration variable]" \
     "($l $m $d -u --set-upstream --set-upstream-to --unset-upstream)"{-u+,--set-upstream-to=}'[set up configuration so that pull merges]:remote branch:__git_remote_branch_names' \
     "($l $m $d -u --set-upstream --set-upstream-to --unset-upstream)--unset-upstream[remove upstream configuration]" \
@@ -341,6 +351,7 @@ _git-branch () {
     $dependent_creation_args \
     "($l $c $d $m)"{-m,--move}"[rename a branch and the corresponding reflog]" \
     "($l $c $d $m)-M[rename a branch even if the new branch-name already exists]" \
+    "--omit-empty[don't output a newline after empty formatted refs]" \
     "($l $c $d $m)"{-c,--copy}"[copy a branch and the corresponding reflog]" \
     "($l $c $d $m)-C[copy a branch even if the new branch-name already exists]" \
     $dependent_modification_args \
@@ -350,6 +361,7 @@ _git-branch () {
     '*--sort=[specify field to sort on]: :__git_ref_sort_keys' \
     '--points-at=[only list tags of the given object]: :__git_commits' \
     "($c $m $d -i --ignore-case)"{-i,--ignore-case}'[sorting and filtering are case-insensitive]' \
+    "($l $m $d)--recurse-submodules[recurse through submodules]" \
     $dependent_deletion_args
 }
 
@@ -383,13 +395,12 @@ _git-bundle () {
             _arguments \
               '(-q --quiet)'{-q,--quiet}"[don't show progress]" \
               '--progress[show progress meter]' \
-              '--all-progress[show progress meter during object writing phase]' \
-              '--all-progress-implied[similar to --all-progress when progress meter is shown]' \
+              \!--all-progress{,-implied} \
               '--version=[specify bundle format version]:version:(2 3)' \
               ':bundle:_files' && ret=0
           else
             local revision_options
-            __git_setup_revision_options
+            __git_setup_revision_options -d
 
             _arguments -S -s \
               $revision_options \
@@ -464,13 +475,14 @@ _git-checkout () {
     '(-q --quiet -2 --ours -3 --theirs --patch)'{-3,--theirs}'[check out stage #3 for unmerged paths]' \
     '(   -B --orphan -2 --ours -3 --theirs --conflict --patch -d --detach)-b+[create a new branch based at given commit]: :__git_branch_names' \
     '(-b    --orphan -2 --ours -3 --theirs --conflict --patch -d --detach)-B+[create or update branch based at given commit]: :__git_branch_names' \
-    '(-t --track --orphan --patch -d --detach)'{-t,--track}'[set up configuration so pull merges from the base commit]' \
+    '(--track --no-track --orphan --patch -d --detach)-t[set upstream info for new branch]' \
+    '(-t --no-track --orphan --patch -d --detach)--track=-[set upstream info for new branch]::configuration:(direct inherit)' \
     '(--patch)--no-track[override the branch.autosetupmerge configuration variable]' \
     $new_branch_reflog_opt \
     '(-b -B -t --track --patch --orphan -d --detach)'{-d,--detach}'[detach the HEAD at named commit]' \
     '(-b -B -t --track --patch -d --detach)--orphan=[create a new orphan branch based at given commit]: :__git_branch_names' \
     '(-q --quiet -f --force -m --merge --conflict --patch)'{-m,--merge}'[3way merge current branch, working tree and new branch]' \
-    '(-q --quiet -f --force -m --merge --patch)--conflict=[same as --merge, using given merge style]:style:(merge diff3)' \
+    '(-q --quiet -f --force -m --merge --patch)--conflict=[same as --merge, using given merge style]:style:(merge diff3 zdiff3)' \
     '(-)'{-p,--patch}'[interactively select hunks in diff between given tree-ish and working tree]' \
     "--ignore-skip-worktree-bits[don't limit pathspecs to sparse entries only]" \
     "--no-guess[don't second guess 'git checkout <no-such-branch>']" '!(--no-guess)--guess' \
@@ -529,10 +541,7 @@ _git-cherry-pick () {
   local -a git_commit_opts
   git_commit_opts=(--all --not HEAD --not)
   _arguments \
-    '(- :)--quit[end revert or cherry-pick sequence]' \
-    '(- :)--continue[resume revert or cherry-pick sequence]' \
-    '(- :)--skip[skip current commit and continue]' \
-    '(- :)--abort[cancel revert or cherry-pick sequence]' \
+    - init \
     '--cleanup=[specify how to strip spaces and #comments from message]:mode:_git_cleanup_modes' \
     '--allow-empty[preserve initially empty commits]' \
     '--allow-empty-message[allow replaying a commit with an empty message]' \
@@ -540,15 +549,21 @@ _git-cherry-pick () {
     '(-e --edit --ff)'{-e,--edit}'[edit commit before committing the cherry-pick]' \
     '(--ff)-x[append information about what commit was cherry-picked]' \
     '(-m --mainline)'{-m+,--mainline=}'[specify mainline when cherry-picking a merge commit]:parent number' \
-    '--rerere-autoupdate[update index with reused conflict resolution if possible]' \
+    '(--no-rerere-autoupdate)--rerere-autoupdate[update index with reused conflict resolution if possible]' \
+    '(--rerere-autoupdate)--no-rerere-autoupdate' \
     '(-n --no-commit --ff)'{-n,--no-commit}'[do not make the actual commit]' \
     '(-s --signoff --ff)'{-s,--signoff}'[add Signed-off-by trailer at the end of the commit message]' \
     '(-S --gpg-sign --no-gpg-sign)'{-S-,--gpg-sign=-}'[GPG-sign the commit]::key id' \
     "(-S --gpg-sign --no-gpg-sign)--no-gpg-sign[don't GPG-sign the commit]" \
-    '*'{-s+,--strategy=}'[use given merge strategy]:merge strategy:__git_merge_strategies' \
+    '*--strategy=[use given merge strategy]:merge strategy:__git_merge_strategies' \
     '*'{-X+,--strategy-option=}'[pass merge-strategy-specific option to merge strategy]: :_git_strategy_options' \
     '(-e --edit -x -n --no-commit -s --signoff)--ff[fast forward, if possible]' \
-    '*: : __git_commit_ranges -O expl:git_commit_opts'
+    '*: : __git_commit_ranges -O expl:git_commit_opts' \
+    - '(sequencer)' \
+    '--quit[end revert or cherry-pick sequence]' \
+    '--continue[resume revert or cherry-pick sequence]' \
+    '--skip[skip current commit and continue]' \
+    '--abort[cancel revert or cherry-pick sequence]' \
 }
 
 (( $+functions[_git-citool] )) ||
@@ -642,9 +657,9 @@ _git-clone () {
     '(-u --upload-pack)'{-u+,--upload-pack=}'[specify path to git-upload-pack on remote side]:remote path' \
     '--template=[directory to use as a template for the object database]: :_directories' \
     '*'{-c,--config}'[<key>=<value> set a configuration variable in the newly created repository]' \
-    '--depth[create a shallow clone, given number of revisions deep]: :__git_guard_number depth' \
-    '--shallow-since=[shallow clone since a specific time]:time' \
-    '*--shallow-exclude=[shallow clone excluding commits reachable from specified remote revision]:revision' \
+    '(--bundle-uri)--depth[create a shallow clone, given number of revisions deep]: :__git_guard_number depth' \
+    '(--bundle-uri)--shallow-since=[shallow clone since a specific time]:time' \
+    '(--bundle-uri)*--shallow-exclude=[shallow clone excluding commits reachable from specified remote revision]:revision' \
     '(--no-single-branch)--single-branch[clone only history leading up to the main branch or the one specified by -b]' \
     '(--single-branch)--no-single-branch[clone history leading up to each branch]' \
     "--no-tags[don't clone any tags and make later fetches not follow them]" \
@@ -656,8 +671,10 @@ _git-clone () {
     '(-4 --ipv4 -6 --ipv6)'{-4,--ipv4}'[use IPv4 addresses only]' \
     '(-4 --ipv4 -6 --ipv6)'{-6,--ipv6}'[use IPv6 addresses only]' \
     '--filter=[object filtering]:filter:_git_rev-list_filters' \
+    '--also-filter-submodules[apply partial clone filters to submodules]' \
     '--remote-submodules[any cloned submodules will use their remote-tracking branch]' \
     '--sparse[initialize the sparse-checkout file to start with only the top-level files]' \
+    '(--depth --shallow-since --shallow-exclude)--bundle-uri=[before fetching, get a bundle from specified location]:uri:_urls' \
     ': :->repository' \
     ': :_directories' && ret=0
 
@@ -710,10 +727,10 @@ _git-commit () {
     "--no-ahead-behind[don't display detailed ahead/behind counts relative to upstream branch]" \
     '(--short             --dry-run)--porcelain[dry run with machine-readable output format]' \
     '(--short --porcelain --dry-run -z --null)'{-z,--null}'[dry run with NULL-separated output format]' \
-    {-p,--patch}'[use the interactive patch selection interface to chose which changes to commit]' \
+    {-p,--patch}'[use the interactive patch selection interface to choose which changes to commit]' \
     '(--reset-author)--author[override the author name used in the commit]:author name' \
     '--date=[override the author date used in the commit]:date' \
-    '*--trailer=[add custom trailer(s)]:trailer' \
+    '*--trailer=[add custom trailer(s)]:trailer:__git_trailers_tokens' \
     '(-s --signoff)'{-s,--signoff}'[add Signed-off-by trailer at the end of the commit message]' \
     '(-n --no-verify)'{-n,--no-verify}'[bypass pre-commit and commit-msg hooks]' \
     '--allow-empty[allow recording an empty commit]' \
@@ -722,8 +739,8 @@ _git-commit () {
     '(-e --edit --no-edit)'{-e,--edit}'[edit the commit message before committing]' \
     '(-e --edit --no-edit)--no-edit[do not edit the commit message before committing]' \
     '--no-post-rewrite[bypass the post-rewrite hook]' \
-    '(-a --all --interactive -o --only -i --include)'{-i,--include}'[update the given files and commit the whole index]' \
-    '(-a --all --interactive -o --only -i --include)'{-o,--only}'[commit only the given files]' \
+    '(-a --all --interactive -o --only)*'{-i,--include}'[update the given files and commit the whole index]' \
+    '(-a --all --interactive -i --include)*'{-o,--only}'[commit only the given files]' \
     '(-u --untracked-files)'{-u-,--untracked-files=-}'[show files in untracked directories]::mode:((no\:"show no untracked files"
                                                                                                   normal\:"show untracked files and directories"
                                                                                                   all\:"show individual files in untracked directories"))' \
@@ -779,6 +796,7 @@ _git-diff () {
   _arguments -C -s $endopt \
     $* \
     $diff_options \
+    '--exit-code[report exit code 1 if differences, 0 otherwise]' \
     '(--exit-code)--quiet[disable all output]' \
     $diff_stage_options \
     '(--cached --staged)--no-index[show diff between two paths on the filesystem]' \
@@ -808,18 +826,6 @@ _git-diff () {
 
       # Otherwise, more complex conditions need to be checked.
       case $CURRENT in
-        (1)
-          local files_alt='files::__git_changed-in-working-tree_files'
-          if [[ -n ${opt_args[(I)--cached|--staged]} ]]; then
-            files_alt='files::__git_changed-in-index_files'
-          fi
-
-          _alternative \
-            'commit-ranges::__git_commit_ranges' \
-            'blobs-and-trees-in-treeish::__git_blobs_and_trees_in_treeish' \
-            $files_alt \
-            'blobs::__git_blobs ' && ret=0
-          ;;
         (2)
           # Check if first argument is something special. In case of committish ranges and committishs offer a full list compatible completions.
           if __git_is_committish_range $line[1]; then
@@ -841,10 +847,19 @@ _git-diff () {
           elif [[ -n ${opt_args[(I)--cached|--staged]} ]]; then
             # Example: git diff --cached file1 <tab>
             __git_changed-in-index_files && ret=0
-          else
-            # Example: git diff file1 <tab>
-            __git_changed-in-working-tree_files && ret=0
           fi
+          ;&
+        (1)
+          local files_alt='files::__git_changed-in-working-tree_files'
+          if [[ -n ${opt_args[(I)--cached|--staged]} ]]; then
+            files_alt='files::__git_changed-in-index_files'
+          fi
+
+          _alternative \
+            'commit-ranges::__git_commit_ranges' \
+            'blobs-and-trees-in-treeish::__git_blobs_and_trees_in_treeish' \
+            $files_alt \
+            'blobs::__git_blobs ' && ret=0
           ;;
         (*)
           if __git_is_committish_range $line[1]; then
@@ -893,6 +908,7 @@ _git-fetch () {
     '(--all -m --multiple)'{-m,--multiple}'[fetch from multiple remotes]' \
     '(-n --no-tags -t --tags)'{-n,--no-tags}'[disable automatic tag following]' \
     '--prefetch[modify the refspec to place all refs within refs/prefetch/]' \
+    '--refetch[fetch all objects as a fresh clone would]' \
     '(-P --prune-tags)'{-P,--prune-tags}'[prune local tags no longer on remote and clobber changed tags]' \
     '--write-fetch-head[write fetched references to the FETCH_HEAD file]' \
     "--negotiate-only[don't fetch a packfile; instead, print ancestors of negotiation tips]" \
@@ -972,6 +988,7 @@ _git-format-patch () {
     '--interdiff=[insert interdiff against previous patch series in cover letter or single patch]:reference to tip of previous series:__git_revisions' \
     '--range-diff=[insert range-diff against previous patch series in cover letter or single patch]:reference to tip ot previous series:__git_revisions' \
     '--creation-factor=[for range-diff, specify weighting for creation]:weighting (percent)' \
+    '--force-in-body-from[show in-body From: even if identical to the e-mail header]' \
     ': :->commit-or-commit-range' && ret=0
 
   case $state in
@@ -992,8 +1009,9 @@ _git-gc () {
   _arguments -S -s $endopt \
     '--aggressive[more aggressively optimize]' \
     '--auto[check whether housekeeping is required]' \
-    '(        --no-prune)--prune=-[prune loose objects older than given date]::date [2 weeks ago]:__git_datetimes' \
+    '(        --no-prune)--prune=-[prune loose objects older than given date]::date [2 weeks ago]:_git_approxidates' \
     '(--prune           )--no-prune[do not prune any loose objects]' \
+    '--cruft[pack unreferenced objects separately]' \
     '(-q --quiet)'{-q,--quiet}'[suppress progress reporting]' \
     '--keep-largest-pack[repack all other packs except the largest pack]' \
 }
@@ -1056,6 +1074,7 @@ _git-grep () {
     '--threads=[use specified number of threads]:number of threads' \
     '(-c --count -p --show-function)'{-p,--show-function}'[show preceding line containing function name of match]' \
     '(-c --count -W --function-context)'{-W,--function-context}'[show whole function where a match was found]' \
+    '(-m --max-count)'{-m+,--max-count=}'[specify maximum number of results per file]:results' \
     '(1)*-f+[read patterns from given file]:pattern file:_files' \
     '(1)*-e+[use the given pattern for matching]:pattern' \
     $pattern_operators \
@@ -1293,6 +1312,7 @@ _git-merge () {
     $merge_options \
     \*{-m+,--message=}'[set the commit message to be used for the merge commit]:merge message' \
     \*{-F+,--file=}'[read commit message from a file]:file' \
+    '--into-name=[use specified name instead of the real target]:branch name:__git_branch_names' \
     '(--edit --no-edit)-e[open an editor to change the commit message]' \
     '(                    --no-rerere-autoupdate)--rerere-autoupdate[allow the rerere mechanism to update the index]' \
     '(--rerere-autoupdate                       )--no-rerere-autoupdate[do not allow the rerere mechanism to update the index]' \
@@ -1332,6 +1352,7 @@ _git-mv () {
 (( $+functions[_git-notes] )) ||
 _git-notes () {
   local curcontext=$curcontext state line ret=1
+  local -a args
   declare -A opt_args
 
   _arguments -C $endopt \
@@ -1369,12 +1390,18 @@ _git-notes () {
         (add)
           # TODO: Only complete commits that don't have notes already, unless
           # -f or --force has been given.
-          _arguments -S -s $endopt \
+          args=( '(-f --force)'{-f,--force}'[overwrite existing note]' )
+        ;&
+        (append)
+          _arguments -S -s $endopt $args \
             '*'{-m+,--message=}'[use given note message]:message' \
             '*'{-F+,--file=}'[take note message from given file]:note message file:_files' \
             '(-C --reuse-message)'{-C+,--reuse-message=}'[take note message from given blob object]: :__git_blobs' \
             '(-c --reedit-message)'{-c+,--reedit-message=}'[take note message from given blob object and edit it]: :__git_blobs' \
-            '(-f --force)'{-f,--force}'[overwrite existing note]' \
+            '--allow-empty[allow storing empty note]' \
+            '(--no-separator)--separator=-[insert text between paragraphs]::paragraph break' \
+            '(--separator)--no-separator' \
+            '--stripspace[remove unnecessary whitespace]' \
             ': :__git_commits' && ret=0
           ;;
         (copy)
@@ -1405,14 +1432,6 @@ _git-notes () {
 	(remove)
 	  _arguments -S $endopt --ignore-missing --stdin ':object:__git_commits' && ret=0
 	  ;;
-        (append)
-          _arguments -S -s $endopt \
-            '*'{-m+,--message=}'[use given note message]:message' \
-            '*'{-F+,--file=}'[take note message from given file]:note message file:_files' \
-            '(-C --reuse-message)'{-C+,--reuse-message=}'[take note message from given blob object]: :__git_blobs' \
-            '(-c --reedit-message)'{-c+,--reedit-message=}'[take note message from given blob object and edit it]: :__git_blobs' \
-            ': :__git_commits' && ret=0
-          ;;
         (get-ref)
           _nothing
           ;;
@@ -1461,14 +1480,22 @@ _git-push () {
   # only complete files on the local end, not the remote end.  Still, it may be
   # helpful to get some sort of completion going, perhaps modifying the path
   # later on to match the remote end.
+
+  local ref_arg
+  if (( words[(I)-d|--delete] )); then
+      ref_arg='*: :__git_remote_branch_names_noprefix'
+  else
+      ref_arg='*: :__git_ref_specs_pushy'
+  fi
+
   _arguments -S -s $endopt \
-    '--all[push all refs under refs/heads/]' \
+    '(* --all --branches --mirror --tags)'{--all,--branches}'[push all branches]' \
     '--prune[remove remote branches that do not have a local counterpart]' \
-    '--mirror[push all refs under refs/heads/ and refs/tags/ and delete non-existing refs]' \
+    '(* --all --branches --tags)--mirror[push all refs under refs/heads/ and refs/tags/ and delete non-existing refs]' \
     '(-n --dry-run)'{-n,--dry-run}'[do everything except actually send the updates]' \
     '--porcelain[produce machine-readable output]' \
     '(-d --delete)'{-d,--delete}'[delete all listed refs from the remote repository]' \
-    '--tags[all tags under refs/tags are pushed]' \
+    '(* --all --branches --mirror)--tags[all tags under refs/tags are pushed]' \
     '--follow-tags[also push missing annotated tags reachable from the pushed refs]' \
     '(--receive-pack --exec)'{--receive-pack=-,--exec=-}'[path to git-receive-pack on remote]:remote git-receive-pack:_files' \
     '(--force-with-lease --no-force-with-lease)*--force-with-lease=-[allow refs that are not ancestors to be updated if current ref matches expected value]::ref and expectation:->lease' \
@@ -1496,7 +1523,7 @@ _git-push () {
     '(-4 --ipv4 -6 --ipv6)'{-4,--ipv4}'[use IPv4 addresses only]' \
     '(-4 --ipv4 -6 --ipv6)'{-6,--ipv6}'[use IPv6 addresses only]' \
     ': :__git_any_repositories' \
-    '*: :__git_ref_specs_pushy' && ret=0
+    $ref_arg && ret=0
 
   case $state in
     (lease)
@@ -1580,6 +1607,8 @@ _git-rebase () {
     '(--keep-base)--onto=[start new branch with HEAD equal to given revision]:newbase:__git_revisions' \
     "(--apply --whitespace -C)--reschedule-failed-exec[automatically re-schedule any 'exec' that fails]" \
     '(--apply --whitespace -C)--reapply-cherry-picks[apply all changes, even those already present upstream]' \
+    '--update-refs[update branches that point to commits that are being rebased]' \
+    '!(--update-refs)--no-update-refs' \
     ':upstream branch:__git_revisions' \
     '::working branch:__git_revisions'
 }
@@ -1599,6 +1628,7 @@ _git-reset () {
       '--recurse-submodules=-[control recursive updating of submodules]::reset:__git_commits' \
       '(-p --patch)'{-p,--patch}'[select diff hunks to remove from the index]' \
       '(-q --quiet)'{-q,--quiet}'[suppress all output]' \
+      '--no-refresh[skip refreshing the index after reset]' \
       '(*)--pathspec-from-file=[read pathspec from file]:file:_files' \
       '(*)--pathspec-file-nul[pathspec elements are separated with NUL character]' \
       '(--soft --mixed --hard --merge --keep):: :__git_commits' \
@@ -1638,7 +1668,7 @@ _git-restore() {
     '(-q --quiet --progress)--no-progress[suppress progress reporting]' \
     '(--no-progress)--progress[force progress reporting]' \
     '(-m --merge)'{-m,--merge}'[perform a 3-way merge with the new branch]' \
-    '--conflict=[change how conflicting hunks are presented]:conflict style [merge]:(merge diff3)' \
+    '--conflict=[change how conflicting hunks are presented]:conflict style [merge]:(merge diff3 zdiff3)' \
     '(-2 --ours -3 --theirs -m --merge)'{-2,--ours}'[checkout our version for unmerged files]' \
     '(-2 --ours -3 --theirs -m --merge)'{-3,--theirs}'[checkout their version for unmerged files]' \
     '(-p --patch)'{-p,--patch}'[select hunks interactively]' \
@@ -1690,6 +1720,7 @@ _git-revert () {
     '*'{-X+,--strategy-option=}'[pass merge-strategy-specific option to merge strategy]: :_git_strategy_options' \
     '(-S --gpg-sign --no-gpg-sign)'{-S-,--gpg-sign=-}'[GPG-sign the commit]::key id' \
     "(-S --gpg-sign --no-gpg-sign)--no-gpg-sign[don't GPG-sign the commit]" \
+    "--reference[use the 'reference' format to refer to commits in log message]" \
     ': :__git_recent_commits'
 }
 
@@ -1832,6 +1863,7 @@ _git-sparse-checkout() {
         add:'update the sparse-checkout file to include additional patterns'
         reapply:'reapply the sparsity pattern rules to paths in the working tree'
         disable:'disable the config setting, and restore all files in the working directory'
+        check-rules:'check whether sparsity rules match one or more paths'
       )
 
       _describe -t commands command commands && ret=0
@@ -1842,13 +1874,22 @@ _git-sparse-checkout() {
         init)
           _arguments \
             '--cone[allow for better performance with a limited set of patterns]' \
-            '--no-sparse-index[rewrite index to not be sparse]'
+            '--no-sparse-index[rewrite index to not be sparse]' && ret=0
         ;;
         set|add)
           _arguments -S \
-            '--stdin[read patterns from input]' \
+            '--cone[initialize the sparse-checkout in cone mode]' \
+            '--sparse-index[toggle the use of a sparse index]' \
+            '--skip-checks[skip some sanity checks on the given paths that might give false positives]' \
+            '(*)--stdin[read patterns from input]' \
             '*:pattern:_files' && ret=0
         ;;
+        check-rules)
+          _arguments \
+           '-z[terminate input and output files by a NUL character]' \
+           '--cone[interpret rules file patterns as cone mode patterns]' \
+           '--rules-file=[use patterns in specified file]:file:_files' && ret=0
+        ;;
       esac
     ;;
   esac
@@ -1867,10 +1908,11 @@ _git-stash () {
     '(-k --keep-index --no-keep-index)'{-k,--keep-index}'[all changes already added to the index are left intact]'
     '(-k --keep-index)--no-keep-index[all changes already added to the index are undone]'
     '(-q --quiet)'{-q,--quiet}'[suppress all output]'
-    '(-p --patch -a --all -u --include-untracked)'{-u,--include-untracked}'[include untracked files]'
-    '(-p --patch -a --all -u --include-untracked)'{-a,--all}'[include ignored files]'
+    '(-p --patch -a --all -u --include-untracked -S --staged)'{-u,--include-untracked}'[include untracked files]'
+    '(-p --patch -a --all -u --include-untracked -S --staged)'{-a,--all}'[include ignored files]'
     '(* -p --patch)--pathspec-from-file=[read pathspec from file]:file:_files'
     '(* -p --patch)--pathspec-file-nul[pathspec elements are separated with NUL character]'
+    '(-S --staged -a --all -u --include-untracked)'{-S,--staged}'[only stash changes that are currently staged]'
   )
 
   _arguments -C \
@@ -1892,6 +1934,7 @@ _git-stash () {
         clear:'remove all the stashed states'
         drop:'remove a single stashed state from the stash list'
         create:'create a stash without storing it in the ref namespace'
+        store:'store a stash created with git stash create in the stash ref'
       )
 
       _describe -t commands command commands && ret=0
@@ -1928,7 +1971,9 @@ _git-stash () {
           __git_setup_diff_options
 
           _arguments -S -s $endopt \
-            $diff_options \
+            ${diff_options:#*\)-u*} \
+            '(-u --include-untracked --only-untracked)'{-u,--include-untracked}'[show the untracked files in the stash entry as part of the diff]' \
+            '(-u --include-untracked)--only-untracked[show only the untracked files in the stash entry as part of the diff]' \
             ':: :__git_stashes' && ret=0
           ;;
         (pop|apply)
@@ -1950,9 +1995,14 @@ _git-stash () {
             '(-q --quiet)'{-q,--quiet}'[suppress all output]' \
             ':: :__git_stashes' && ret=0
           ;;
+        (store)
+          _arguments -S -s $endopt \
+            '(-m --message)'{-m+,--message=}'[specify stash description]:description' \
+            '(-q --quiet)'{-q,--quiet}'[suppress all output]' && ret=0
+        ;;
         (create)
-          _nothing
-          ;;
+          _message -e messages message
+        ;;
         (*)
           _nothing
           ;;
@@ -2056,7 +2106,6 @@ _git-submodule () {
             '*: :__git_ignore_line_inside_arguments __git_submodules' && ret=0
           ;;
         (update)
-          # TODO: --init not properly documented.
           _arguments -S \
             '(-q --quiet)'{-q,--quiet}'[suppress all output]' \
             '(-N --no-fetch)'{-N,--no-fetch}'[do not fetch new objects from repository]' \
@@ -2070,6 +2119,7 @@ _git-submodule () {
             '--force[discard local changes by checking out the current up-to-date version]' \
             '--init[initialize uninitialized submodules]' \
             '--single-branch[clone only one branch]' \
+            '--filter=[apply partial clone filter to the submodule]:filter' \
             '*: :__git_ignore_line_inside_arguments __git_submodules' && ret=0
 	;;
 	(set-branch)
@@ -2141,7 +2191,7 @@ _git-subtree () {
   _arguments -C \
     '(-q --quiet)'{-q,--quiet}'[suppress progress output]' \
     '(-P --prefix)'{-P+,--prefix=}'[the path to the subtree in the repository to manipulate]: :_directories' \
-    '-d[show debug messages]' \
+    '(-d --debug)'{-d,--debug}'[show debug messages]' \
     ': :->command' \
     '*::: := ->option-or-argument' && ret=0
 
@@ -2238,9 +2288,10 @@ _git-switch() {
     '(-q --quiet --progress)--no-progress[suppress progress reporting]' \
     '--progress[force progress reporting]' \
     '(-m --merge --discard-changes --orphan)'{-m,--merge}'[perform a 3-way merge with the new branch]' \
-    '(--discard-changes --orphan)--conflict=[change how conflicting hunks are presented]:conflict style [merge]:(merge diff3)' \
+    '(--discard-changes --orphan)--conflict=[change how conflicting hunks are presented]:conflict style [merge]:(merge diff3 zdiff3)' \
     '(-d --detach -c --create -C --force-create --ignore-other-worktrees --orphan --guess --no-guess 1)'{-d,--detach}'[detach HEAD at named commit]' \
-    '(-t --track --no-track --guess --orphan 1)'{-t,--track}'[set upstream info for new branch]' \
+    '(--track --no-track --guess --orphan 1)-t[set upstream info for new branch]' \
+    '(-t --no-track --guess --orphan 1)--track=-[set upstream info for new branch]::configuration:(direct inherit)' \
     "(-t --track --guess --orphan 1)--no-track[don't set upstream info for a new branch]" \
     '(-c --create -C --force-create -d --detach --ignore-other-worktrees -m --merge --conflict -t --track --guess --no-track -t --track)--orphan[create new unparented branch]: :__git_branch_names' \
     '!--overwrite-ignore' \
@@ -2301,6 +2352,7 @@ _git-tag () {
       "*--no-contains=[only list tags that don't contain the specified commit]: :__git_commits" \
       '--merged=-[print only tags that are merged]:: :__git_commits' \
       '--no-merged=-[print only tags that are not merged]:: :__git_commits' \
+      "--omit-empty[don't output a newline after empty formatted refs]" \
       '--sort=[specify how the tags should be sorted]:field:__git_ref_sort_keys' \
       '--points-at=[only list tags of the given object]: :__git_commits' \
       '--format=[specify format to use for the output]:format:__git_format_ref' \
@@ -2332,6 +2384,7 @@ _git-worktree() {
 	lock:'prevent a working tree from being pruned'
 	move:'move a working tree to a new location'
 	remove:'remove a working tree'
+        repair:'repair worktree administrative files'
 	unlock:'allow working tree to be pruned, moved or deleted'
       )
 
@@ -2346,23 +2399,34 @@ _git-worktree() {
 	  else
 	    args=( ':commit:__git_commits' )
 	  fi
-          _arguments -S $endopt \
+          _arguments -s -S $endopt \
 	    '(-f --force)'{-f,--force}'[checkout branch even if already checked out in another worktree]' \
-	    '(-B --detach)-b+[create a new branch]: :__git_branch_names' \
-	    '(-b --detach)-B+[create or reset a branch]: :__git_branch_names' \
-	    '(-b -B)--detach[detach HEAD at named commit]' \
+            '(-B -d --detach --guess-remote)-b+[create a new branch]: :__git_branch_names' \
+            '(-b -d --detach --guess-remote)-B+[create or reset a branch]: :__git_branch_names' \
+            '(-b -d --detach)--orphan[create unborn/orphaned branch]' \
+            '(-d --detach -b -B --orphan --guess-remote --track --no-track)'{-d,--detach}'[detach HEAD at named commit]' \
 	    '--no-checkout[suppress file checkout in new worktree]' \
 	    '--lock[keep working tree locked after creation]' \
+            '--reason=[specify reason for locking]:reason' \
+            '(2 --no-guess-remote -b -B -d --detach)--guess-remote[guess remote tracking branch from path basename]' \
+            "(--guess-remote)--no-guess-remote[don't guess remote tracking branch from path basename]" \
+            '(--no-track -d --detach)--track[set upstream info for new branch]' \
+            "(--track -d --detach)--no-track[don't set upstream info for new branch]" \
+            '(-q --quiet)'{-q,--quiet}'[suppress feedback messages]' \
 	    ':path:_directories' $args && ret=0
 	;;
         (prune)
-          _arguments -S $endopt \
+          _arguments -s -S $endopt \
 	    '(-n --dry-run)'{-n,--dry-run}"[don't remove, show only]" \
 	    '(-v --verbose)'{-v,--verbose}'[report pruned objects]' \
-	    '--expire[expire objects older than specified time]:time' && ret=0
+            '--expire=[expire objects older than specified time]: :_git_approxidates' && ret=0
 	;;
         (list)
-	  _arguments -S $endopt '--porcelain[machine-readable output]' && ret=0
+          _arguments -S $endopt \
+            '(-v --verbose --porcelain -z)'{-v,--verbose}'[output additional information about worktrees]' \
+            "--expire=[add 'prunable' annotation to worktrees older than specified time]: :_git_approxidates" \
+            '(-v)--porcelain[machine-readable output]' \
+            '(-v)-z[terminate each line with a NUL rather than a newline]' && ret=0
 	;;
 	(lock)
 	  _arguments -C -S $endopt '--reason=[specify reason for locking]:reason' ': :->worktrees' && ret=0
@@ -2373,9 +2437,13 @@ _git-worktree() {
             ':location:_directories' && ret=0
 	;;
 	(remove)
-	  _arguments -C -S $endopt '--force[remove working trees that are not clean or that have submodules]' \
+          _arguments -C -S $endopt \
+            '(-f --force)'{-f,--force}'[remove working trees that are not clean or that have submodules]' \
             ': :->worktrees' && ret=0
 	;;
+        (repair)
+          _directories && ret=0
+        ;;
 	(unlock)
 	  state=worktrees
 	;;
@@ -3829,7 +3897,11 @@ _git-pack-refs () {
     '(      --no-all)--all[pack all refs]' \
     '(--all         )--no-all[do not pack all refs]' \
     '(        --no-prune)--prune[remove loose refs after packing them]' \
-    '(--prune           )--no-prune[do not remove loose refs after packing them]'
+    '(--prune           )--no-prune[do not remove loose refs after packing them]' \
+    '*--include=[references to include]:reference pattern:_git_full_references' \
+    '*--exclude=[references to exclude]:reference pattern:_git_full_references' \
+    '--no-include[clear and reset the list of include patterns]' \
+    '--no-exclude[clear and reset the list of exclude patterns]'
 }
 
 (( $+functions[_git-prune] )) ||
@@ -3838,7 +3910,7 @@ _git-prune () {
     '(-n --dry-run)'{-n,--dry-run}'[do not remove anything; just report what would be removed]' \
     '(-v --verbose)'{-v,--verbose}'[report all removed objects]' \
     '--progress[show progress]' \
-    '--expire=[only expire loose objects older than specified date]: :__git_datetimes' \
+    '--expire=[only expire loose objects older than specified date]: :_git_approxidates' \
     '--exclude-promisor-objects[limit traversal to objects outside promisor packfiles]' \
     '*:: :__git_heads'
 }
@@ -3886,8 +3958,8 @@ _git-reflog () {
             _arguments -S \
               '(-n --dry-run)'{-n,--dry-run}"[don't actually prune any entries; show what would be pruned]" \
               '--stale-fix[prune any reflog entries that point to "broken commits"]' \
-              '--expire=-[prune entries older than given time]: :__git_datetimes' \
-              '--expire-unreachable=-[prune entries older than given time and unreachable]: :__git_datetimes' \
+              '--expire=-[prune entries older than given time]:age [90 days]:_git_approxidates' \
+              '--expire-unreachable=-[prune entries older than given time and unreachable]:age [30 days]:_git_approxidates' \
               '--all[prune all refs]' \
               '--updateref[update ref with SHA-1 of top reflog entry after expiring or deleting]' \
               '--rewrite[adjust reflog entries to ensure old SHA-1 points to new SHA-1 of previous entry after expiring or deleting]' \
@@ -3895,7 +3967,7 @@ _git-reflog () {
             ;;
           (delete)
             _arguments -C -S \
-              '(-n --dry-run)'{-n,--dry-run}"[dpn't update entries; show what would be done]" \
+              '(-n --dry-run)'{-n,--dry-run}"[don't update entries; show what would be done]" \
               '--updateref[update ref with SHA-1 of top reflog entry after expiring or deleting]' \
               '--rewrite[adjust reflog entries to ensure old SHA-1 points to new SHA-1 of previous entry after expiring or deleting]' \
               '--verbose[output additional information]' \
@@ -3975,7 +4047,9 @@ _git-remote () {
             ': :__git_remotes' && ret=0
           ;;
         (rename)
-          _arguments \
+          _arguments -S $endopt \
+            '(--no-progress)--progress' \
+            '(--progress)--no-progress' \
             ':old name:__git_remotes' \
             ':new name:__git_remotes' && ret=0
           ;;
@@ -4033,8 +4107,10 @@ _git-repack () {
   _arguments -s \
     '(-A --unpack-unreachable)-a[pack all objects into a single pack]' \
     '(-a -k --keep-unreachable)-A[pack all objects into a single pack, but unreachable objects become loose]' \
+    '--cruft[pack unreachable cruft objects separately]' \
+    '--cruft-expiration=[expire cruft objects older than specified time]: :_git_approxidates' \
     '-d[remove redundant packs after packing]' \
-    "--unpack-unreachable=[with -A, don't loosen objects older than specified date]:date" \
+    "--unpack-unreachable=[with -A, don't loosen objects older than specified date]: :_git_approxidates" \
     '-f[pass --no-reuse-delta option to git pack-objects]' \
     '-F[pass --no-reuse-object option to git pack-objects]' \
     "-n[don't update server information]" \
@@ -4042,7 +4118,7 @@ _git-repack () {
     '(-l --local)'{-l,--local}'[pass --local option to git pack-objects]' \
     '(-b --write-bitmap-index)'{-b,--write-bitmap-index}'[write a bitmap index]' \
     '(-i --delta-islands)'{-i,--delta-islands}'[pass --delta-islands to git-pack-objects]' \
-    "--unpack-unreachable=[with -A, don't loosen objects older than specified time]:time" \
+    "--unpack-unreachable=[with -A, don't loosen objects older than specified time]: :_git_approxidates" \
     '(-k --keep-unreachable)'{-k,--keep-unreachable}'[with -a, repack unreachable objects]' \
     '--window=[number of objects to consider when doing delta compression]:number of objects' \
     '--window-memory=[scale window size dynamically to not use more than specified amount of memory]: : __git_guard_bytes' \
@@ -4052,7 +4128,8 @@ _git-repack () {
     '--pack-kept-objects[repack objects in packs marked with .keep]' \
     '--keep-pack=[ignore named pack]:pack' \
     '(-g --geometric)'{-g+,--geometric=}'[find a geometric progression with specified factor]:factor' \
-    '(-m --write-midx)'{-m,--write-midx}'[write a multi-pack index of the resulting packs]'
+    '(-m --write-midx)'{-m,--write-midx}'[write a multi-pack index of the resulting packs]' \
+    '--expire-to=[pack prefix to store a pack containing pruned objects]:directory:_directories'
 }
 
 (( $+functions[_git-replace] )) ||
@@ -4085,7 +4162,7 @@ _git-blame () {
   declare -A opt_args
 
   declare -a revision_options
-  __git_setup_revision_options
+  __git_setup_revision_options -d
 
   # TODO: Not sure about __git_cached_files.
   _arguments -C -S -s $endopt \
@@ -4128,7 +4205,8 @@ _git-blame () {
       else
         _alternative \
           'line-numbers: :__git_guard_number "line number"' \
-          'regexes::_guard "(/[^/]#(\\?[^/]#)#(/|)|)" regex' && ret=0
+          'regexes::_guard "(/[^/]#(\\?[^/]#)#(/|)|)" regex' \
+          'functions::_guard "(|:*)" "function name"' && ret=0
       fi
       ;;
   esac
@@ -4139,8 +4217,9 @@ _git-blame () {
 (( $+functions[_git-bugreport] )) ||
 _git-bugreport() {
   _arguments \
-    '(-o --output-directory)'{-o+,--output-directory=}'[specify a destination for the bugreport file]:directory:_directories' \
-    '(-s --suffix)'{-s+,--suffix=}'[specify a strftime format suffix for the filename]:format:_date_formats'
+    '--diagnose=-[create an additional zip archive of detailed diagnostics]::mode [stats]:(stats all)' \
+    '(-o --output-directory)'{-o+,--output-directory=}'[specify a destination for the bugreport]:directory:_directories' \
+    '(-s --suffix)'{-s+,--suffix=}'[specify a strftime format filename suffix]:format:_date_formats'
 }
 
 (( $+functions[_git-cherry] )) ||
@@ -4160,6 +4239,14 @@ _git-count-objects () {
     {-H,--human-readable}'[print sizes in human readable format]'
 }
 
+(( $+functions[_git-diagnose] )) ||
+_git-diagnose() {
+  _arguments -S $endopt \
+    '(-o --output-directory)'{-o+,--output-directory=}'[specify a destination for the diagnostics archive]:destination:_directories' \
+    '(-s --suffix)'{-s+,--suffix=}'[specify a strftime format suffix for the filename]:format:_date_formats' \
+    '--mode=[specify the content of the diagnostic archive]:content [stats]:(stats all)'
+}
+
 (( $+functions[_git-difftool] )) ||
 _git-difftool () {
   # TODO: Is this fine, or do we need to modify the context or similar?
@@ -4189,9 +4276,10 @@ _git-fsck () {
     '--full[check all object directories]' \
     '--connectivity-only[check only connectivity]' \
     '--strict[do strict checking]' \
-    '(-v --verbose)'{-v,--verbose}'[output additional information]' \
+    '(-v --verbose --no-progress)'{-v,--verbose}'[output additional information]' \
     '--lost-found[write dangling objects into .git/lost-found]' \
-    '--progress[show progress]' \
+    "(-v --verbose)--no-progress[don't show progress]" \
+    '!(-v --verbose --no-progress)--progress' \
     '--name-objects[show verbose names for reachable objects]' \
     '*: :__git_objects'
 }
@@ -4204,14 +4292,19 @@ _git-get-tar-commit-id () {
 (( $+functions[_git-help] )) ||
 _git-help () {
   _arguments -S -s \
-    '(-c --config -i --info -m --man -w --web)'{-a,--all}'[show all available commands]' \
+    '(-a --all -g --guides --user-interfaces --developer-interfaces -c --config -i --info -m --man -w --web)'{-a,--all}'[show all available commands]' \
+    '(-g --guides --user-interfaces --developer-interfaces -c --config -i --info -m --man -w --web)--no-external-commands[exclude external commands, with --all]' \
+    '(-g --guides --user-interfaces --developer-interfaces -c --config -i --info -m --man -w --web)--no-aliases[exclude aliases, with --all]' \
+    '(-a --all -g --guides --user-interfaces --developer-interfaces -c --config -i --info -w --web)'{-m,--man}'[display manual for the command in man format]' \
+    '(-a --all -g --guides --user-interfaces --developer-interfaces -c --config -i --info -m --man)'{-w,--web}'[display manual for the command in HTML format]' \
+    '(-a --all -g --guides --user-interfaces --developer-interfaces -c --config -m --man -w --web)'{-i,--info}'[display manual for the command in info format]' \
+    '!(--no-verbose)'{-v,--verbose} \
+    "--no-verbose[don't print command descriptions]" \
+    '(-)'{-g,--guides}'[print list of useful guides]' \
+    '(-)--user-interfaces[print list of user-facing repository, command and file interfaces]' \
+    '(-)--developer-interfaces[print list of file formats, protocols and other developer interfaces]' \
     '(-)'{-c,--config}'[print all configuration variable names]' \
-    '(-a --all -g --guides -c --config -m --man -w --web)'{-i,--info}'[display manual for the command in info format]' \
-    '(-a --all -g --guides -c --config -i --info -w --web)'{-m,--man}'[display manual for the command in man format]' \
-    '(-a --all -g --guides -c --config -i --info -m --man)'{-w,--web}'[display manual for the command in HTML format]' \
-    '(-g --guides -c --config -i --info -m --man -w --web)'{-g,--guides}'[prints a list of useful guides on the standard output]' \
-    '(-v --verbose)'{-v,--verbose}'[print command descriptions]' \
-    ': : _alternative commands:command:_git_commands "guides:git guide:(attributes cli core-tutorial cvs-migration diffcore everyday glossary hooks ignore modules namespaces repository-layout revisions tutorial tutorial-2 workflows)"'
+    ': : _alternative commands:command:_git_commands "guides:git guide:_git_help_guides"'
 }
 
 (( $+functions[_git-instaweb] )) ||
@@ -4248,7 +4341,16 @@ _git-instaweb () {
 
 (( $+functions[_git-merge-tree] )) ||
 _git-merge-tree () {
-  _arguments \
+  _arguments -S $endopt \
+    '(1)--write-tree[do a real merge instead of a trivial merge]' \
+    '(-)--trivial-merge[do a trivial merge only]' \
+    '(--no-messages)--messages[also show informational/conflict messages]' \
+    "(--messages)--no-messages[don't show informational/conflict messages]" \
+    '-z[separate paths with the NUL character]' \
+    '--name-only[list filenames without modes/oids/stages]' \
+    '--allow-unrelated-histories[allow merging unrelated histories]' \
+    '--stdin[perform multiple merges, one per line of input]' \
+    '--merge-base=[specify a merge-base for the merge]:commit:__git_commits' \
     ':base-tree:__git_tree_ishs' \
     ':branch 1:__git_tree_ishs' \
     ':branch 2:__git_tree_ishs'
@@ -4261,14 +4363,14 @@ _git-rerere () {
 
   _arguments -C -S -s $endopt \
     '--rerere-autoupdate[register clean resolutions in index]' \
-    ': :->command' && ret=0
+    ': :->command' \
+    '*: :{ [[ $words[CURRENT-1] = forget ]] && __git_cached_files }' && ret=0
 
   case $state in
     (command)
-      # TODO: This isn't optimal, as forget get confused.
       _values command \
         'clear[reset metadata used by rerere]' \
-        'forget[resets metadata used by rerere for specific conflict]: :__git_cached_files' \
+        'forget[resets metadata used by rerere for specific conflict]' \
         'diff[output diffs for the current state of the resolution]' \
         'status[print paths with conflicts whose merge resolution rerere will record]' \
         'remaining[print paths with conflicts that have not been autoresolved by rerere]' \
@@ -4344,8 +4446,8 @@ _git-rev-parse () {
       '--is-inside-work-tree[show whether or not current working directory is inside work tree]' \
       '--is-bare-repository[show whether or not repository is bare]' \
       '(--revs-only --no-revs --flags --no-flags --verify)--short=-[show only shorter unique name]:: :__git_guard_number length' \
-      '(--since --after)'{--since=-,--after=-}'[show --max-age= parameter corresponding given date string]:datestring' \
-      '(--until --before)'{--until=-,--before=-}'[show --min-age= parameter corresponding given date string]:datestring' \
+      '(--since --after)'{--since=-,--after=-}'[show --max-age= parameter corresponding given date string]: :_git_approxidates' \
+      '(--until --before)'{--until=-,--before=-}'[show --min-age= parameter corresponding given date string]: :_git_approxidates' \
       '--resolve-git-dir[check if <path> is a valid repository or gitfile and print location]:git dir:_files -/' \
       '*: :__git_objects' && ret=0
   fi
@@ -4385,7 +4487,7 @@ _git-show-branch () {
       if compset -P '[[:digit:]]##,'; then
         _alternative \
           'counts: :__git_guard_number count' \
-          'dates::__git_datetimes' && ret=0
+          'dates::_git_approxidates' && ret=0
       else
         __git_guard_number limit
       fi
@@ -4564,6 +4666,8 @@ _git-send-email () {
     '--relogin-delay=[specify delay between successive logins]:delay (seconds)' \
     '--cc-cmd=[specify command to generate Cc\: header with]:Cc\: command:_cmdstring' \
     '--to-cmd=[specify command to generate To\: header with]:To\: command:_cmdstring' \
+    '--header-cmd=[specify command to generate headers with]:header command:_cmdstring' \
+    '--no-header-cmd[disable any header command in use]' \
     '(                 --no-chain-reply-to)--chain-reply-to[send each email as a reply to previous one]' \
     '(--chain-reply-to                    )--no-chain-reply-to[send all emails after first as replies to first one]' \
     '--identity=[specify configuration identity]: :__git_sendemail_identities' \
@@ -4891,7 +4995,7 @@ _git-apply () {
 
   _arguments -S -s $endopt \
     $apply_options \
-    '(--index --cached --reject)'{-3,--3way}'[fall back on 3-way merge if patch fails]' \
+    '(--index --cached --reject)'{-3,--3way}'[attempt three-way merge, fall back on normal patch if that fails]' \
     '--stat[output diffstat for input (turns off "apply")]' \
     '--numstat[same as --stat but in decimal notation and complete pathnames (turns off "apply")]' \
     '--summary[output summary of git-diff extended headers (turns off "apply")]' \
@@ -4906,8 +5010,10 @@ _git-apply () {
     '--no-add[ignore additions made by the patch]' \
     '--allow-overlap[allow overlapping hunks]' \
     '--inaccurate-eof[work around missing-new-line-at-EOF bugs]' \
-    '(-v --verbose)'{-v,--verbose}'[display progress on stderr]' \
+    '(-v --verbose -q --quiet)'{-v,--verbose}'[display progress on stderr]' \
+    '(-q --quiet -v --verbose)'{-q,--quiet}'[be more quiet]' \
     '--recount[do not trust line counts in hunk headers]' \
+    "--allow-empty[don't return error for empty patches]" \
     '*:patch:_files'
 }
 
@@ -4924,8 +5030,9 @@ _git-checkout-index () {
     '(-q --quiet)'{-q,--quiet}'[no warning for existing files and files not in index]' \
     '(-f --force)'{-f,--force}'[force overwrite of existing files]' \
     '(-a --all --stdin *)'{-a,--all}'[check out all files in index]' \
-    '(-n --no-create)'{-n,--no-create}'[do not checkout new files]' \
+    '(-n --no-create)'{-n,--no-create}"[don't checkout new files]" \
     '--temp[write content to temporary files]' \
+    "--ignore-skip-worktree-bits[don't skip files with skip-worktree set]" \
     '(-a --all *)--stdin[read list of paths from the standard input]' \
     '--prefix=[prefix to use when creating files]:directory:_directories' \
     '--stage=[check out files from named stage]:stage:(1 2 3 all)' \
@@ -4947,7 +5054,7 @@ _git-commit-graph() {
       '(--reachable --stdin-packs)--stdin-commits[walk commits starting at commits read from input]'
       '(--append)--size-multiple=:commits [2]'
       '(--append)--max-commits=:commits'
-      '(--append)--expire-time=:date/time:__git_datetimes'
+      '(--append)--expire-time=: :_git_approxidates'
       '--max-new-filters=[specify maximum number of changed-path bloom filters to compute]:'
     )
   elif [[ $words[2] = verify ]]; then
@@ -5034,7 +5141,8 @@ _git-merge-file () {
     '(--ours          --union)--theirs[resolve conflicts favoring their side of the lines]' \
     '(--ours --theirs        )--union[resolve conflicts favoring both sides of the lines]' \
     '--marker-size[specify length of conflict markers]: :__git_guard_number "marker length"' \
-    '--diff3[use a diff3 based merge]' \
+    '(--zdiff3)--diff3[show conflicts in "diff3" style]' \
+    '(--diff3)--zdiff3[show conflicts in "zdiff3" style]' \
     ':current file:_files' \
     ':base file:_files' \
     ':other file:_files'
@@ -5116,7 +5224,9 @@ _git-pack-objects () {
     '--include-tag[include unasked-for annotated tags if object they reference is included]' \
     '(--revs --stdin-packs --unpack-unreachable)--keep-unreachable[add objects unreachable from refs in packs named with --unpacked to resulting pack]' \
     '(--revs --stdin-packs)--pack-loose-unreachable[pack unreachable loose objects]' \
-    '(--revs --stdin-packs --keep-unreachable)--unpack-unreachable=-[keep unreachable objects in loose form]::time' \
+    '(--revs --stdin-packs --keep-unreachable)--unpack-unreachable=-[keep unreachable objects in loose form]:: :_git_approxidates' \
+    '--cruft[create a cruft pack]' \
+    '--cruft-expiration=[expire cruft objects older than specified time]: :_git_approxidates' \
     '--sparse[use sparse reachability algorithm]' \
     '--include-tag[include tag objects that refer to objects to be packed]' \
     $thin_opt \
@@ -5194,6 +5304,7 @@ _git-symbolic-ref () {
     '(-q --quiet)'{-q,--quiet}'[do not issue error if specified name is not a symbolic ref]' \
     '--short[shorten the ref name (eg. refs/heads/master -> master)]' \
     '-m[update reflog for specified name with specified reason]:reason for update' \
+    '--no-recurse[stop after dereferencing a single level of symbolic ref]' \
     ':symbolic reference:__git_heads' \
     ':: :__git_references'
 }
@@ -5289,8 +5400,8 @@ _git-cat-file () {
   _arguments -S -s \
     '(-t -s -e -p --allow-unknown-type 1)--textconv[show content as transformed by a textconv filter]' \
     '(-t -s -e -p --allow-unknown-type 1)--filters[show content as transformed by filters]' \
-    '(-t -s -e -p --allow-unknown-type 1)--path=[use a specific path for --textconv/--filters]:path:_directories' \
     - query \
+    '(-t -s -e -p --allow-unknown-type 1)--path=[use a specific path for --textconv/--filters]:path:_directories' \
     '(-s -e -p --textconv --filters 1)-t[show type of given object]' \
     '(-t -e -p --textconv --filters 1)-s[show size of given object]' \
     '(-e -p --textconv --filters 1)--allow-unknown-type[allow query of broken/corrupt objects of unknown type]' \
@@ -5299,12 +5410,14 @@ _git-cat-file () {
     '(-):object type:(blob commit tag tree)' \
     ': :__git_objects' \
     - batch \
-    '(--batch-check)--batch=-[print SHA1, type, size and contents (or in specified format)]::format' \
-    '(--batch)--batch-check=-[print SHA1, type and size (or in specified format)]::format' \
+    '(--batch-check --batch-command)--batch=-[print SHA1, type, size and contents (or in specified format)]::format' \
+    '(--batch --batch-command)--batch-check=-[print SHA1, type and size (or in specified format)]::format' \
+    '(--batch-check --batch)--batch-command=-[enter a command mode that reads commands and arguments from stdin]::format' \
     '--follow-symlinks[follow in-tree symlinks (used with --batch or --batch-check)]' \
     '--batch-all-objects[show all objects with --batch or --batch-check]' \
     "--unordered[don't order --batch-all-objects output]" \
-    '--buffer[disable flushing of output after each object]'
+    '--buffer[disable flushing of output after each object]' \
+    '-Z[input and output is NUL-delimited instead of newline-delimited]'
 }
 
 (( $+functions[_git-diff-files] )) ||
@@ -5332,8 +5445,11 @@ _git-diff-index () {
   # to given tree-ish?  This should be done for git-diff as well, in that case.
   _arguments -S \
     $revision_options \
+    '--exit-code[report exit code 1 if differences, 0 otherwise]' \
+    '(--exit-code)--quiet[disable all output]' \
     "--cached[don't consider the work tree at all]" \
     '-m[flag non-checked-out files as up-to-date]' \
+    '--merge-base[use merge base instead of comparing directly]' \
     ': :__git_tree_ishs' \
     '*: :__git_cached_files'
 }
@@ -5350,16 +5466,18 @@ _git-diff-tree () {
   # __git_setup_revision_options, but only used by this command, so only have
   # them here.
   _arguments -C -S -s \
-    $revision_options \
+    ${revision_options:#*--cc\[*} \
+    '--exit-code[report exit code 1 if differences, 0 otherwise]' \
+    '(--exit-code)--quiet[disable all output]' \
     '-r[recurse into subdirectories]' \
     '(-r   )-t[display tree objects in diff output]' \
     '--root[display root diff]' \
+    '--merge-base[use merge base instead of comparing directly]' \
     '-m[do not ignore merges]' \
     '-s[do not show differences]' \
     '(--pretty --header)-v[display commit message before differences]' \
     '--no-commit-id[do not display commit IDs]' \
-    '(-c --cc)-c[show differences from each of parents to merge result]' \
-    '(-c --cc)--cc[how differences from each of parents and omit differences from only one parent]' \
+    '(-c)--cc[combined diff format for merge commits, further omitting uninteresting hunks]' \
     '--combined-all-paths[show name of file in all parents for combined diffs]' \
     '--always[always show commit itself and commit log message]' \
     ': :__git_tree_ishs' \
@@ -5396,21 +5514,24 @@ _git-for-each-ref () {
   # is, %(refname), %(objecttype), %(objectsize), %(objectname) with optional '*'
   # in front.
   _arguments -S -s \
+    "--omit-empty[don't output a newline after empty formatted refs]" \
     '--count=[maximum number of refs to iterate over]: :__git_guard_number "maximum number of refs"' \
     '*--sort=[key to sort refs by]: :__git_ref_sort_keys' \
     '--format=-[output format of ref information]:format:__git_format_ref' \
     '--color=-[respect any colors specified in the format]::when:(always never auto)' \
+    '--exclude=[exclude refs which match pattern]:pattern:_git_full_references' \
     '*--points-at=[print only refs which point at the given object]:object:__git_commits' \
     '*--merged=[print only refs that are merged]:object:__git_commits' \
     '*--no-merged=[print only refs that are not merged]:object:__git_commits' \
     '*--contains=[print only refs that contain specified commit]:object:__git_commits' \
     "*--no-contains=[print only refs that don't contain specified commit]:object:__git_commits" \
     '--ignore-case[sorting and filtering are case-insensitive]' \
+    '(1)--stdin[read reference patterns from stdin]' \
     '(-s --shell -p --perl --python --tcl)'{-s,--shell}'[use string literals suitable for sh]' \
     '(-s --shell -p --perl --python --tcl)'{-p,--perl}'[use string literals suitable for Perl]' \
     '(-s --shell -p --perl          --tcl)'--python'[use string literals suitable for Python]' \
     '(-s --shell -p --perl --python      )'--tcl'[use string literals suitable for Tcl]' \
-    ':: :_guard "([^-]?#|)" pattern'
+    ':: :_git_full_references'
 }
 
 (( $+functions[_git-for-each-repo] )) ||
@@ -5435,15 +5556,15 @@ _git-ls-files () {
     '(-c --cached)'{-c,--cached}'[show cached files in output]' \
     '(-d --deleted)'{-d,--deleted}'[show deleted files in output]' \
     '(-m --modified)'{-m,--modified}'[show modified files in output]' \
-    '(-o --others)'{-o,--others}'[show other files in output]' \
+    '(-o --others --format)'{-o,--others}'[show other files in output]' \
     '(-i --ignored)'{-i,--ignored}'[show ignored files in output]' \
-    '(-s --stage --with-tree)'{-s,--stage}'[show stage files in output]' \
+    '(-s --stage --with-tree --format)'{-s,--stage}'[show stage files in output]' \
     '--directory[if a whole directory is classified as "other", show just its name]' \
-    '--eol[show line endings of files]' \
+    '(--format)--eol[show line endings of files]' \
     $no_empty_directory_opt \
     '(-s --stage -u --unmerged --with-tree)'{-u,--unmerged}'[show unmerged files in output]' \
-    '--resolve-undo[show resolve-undo information]' \
-    '(-k --killed)'{-k,--killed}'[show killed files in output]' \
+    '(--format)--resolve-undo[show resolve-undo information]' \
+    '(-k --killed --format)'{-k,--killed}'[show killed files in output]' \
     '-z[separate paths with the NUL character]' \
     '*'{-x,--exclude=-}'[skip files matching given pattern]:file pattern' \
     '*'{-X,--exclude-from=-}'[skip files matching patterns in given file]: :_files' \
@@ -5458,6 +5579,8 @@ _git-ls-files () {
     '--abbrev=[use specified digits to display object names]:digits' \
     '--debug[show debugging data]' \
     '--deduplicate[suppress duplicate entries]' \
+    '--sparse[show sparse directories in the presence of a sparse index]' \
+    '(-s --stage -o --others -k --killed --resolve-undo --eol)--format=[specify format to use for the output]:format' \
     '*:: :_files'
 }
 
@@ -5488,9 +5611,11 @@ _git-ls-tree () {
     '(-t)-d[do not show children of given tree (implies -t)]' \
     '-r[recurse into subdirectories]' \
     '-t[show tree entries even when going to recurse them]' \
-    '(-l --long --name-only --name-status)'{-l,--long}'[show object size of blob entries]' \
+    '(-l --long --name-only --name-status --format)'{-l,--long}'[show object size of blob entries]' \
     '-z[use NUL termination on output]' \
-    '(--name-only --name-status --abbrev)'{--name-only,--name-status}'[list only filenames, one per line]' \
+    '(--name-only --name-status -l --long --object-only --format --abbrev)'{--name-only,--name-status}'[list only filenames, one per line]' \
+    '(--name-only --name-status --format)--object-only[list only objects]' \
+    '(--name-only --name-status -l --long --object-only)--format=[specify format to use for the output]:format' \
     '(--name-only --name-status)--abbrev=[use specified digits to display object names]:digits' \
     '--full-name[output full path-names]' \
     '(--full-name)--full-tree[do not limit listing to current working-directory]' \
@@ -5525,12 +5650,13 @@ _git-name-rev () {
     '*--refs=[only use refs matching given pattern]: :_guard "?#" "shell pattern"' \
     '--no-refs[clear any previous ref patterns given]' \
     '*--exclude=[ignore refs matching specified pattern]:pattern' \
-    '(--stdin :)--all[list all commits reachable from all refs]' \
-    '(--all :)--stdin[read from stdin and append revision-name]' \
+    '(--annotate-stdin :)--all[list all commits reachable from all refs]' \
+    '(--all :)--annotate-stdin[annotate text from stdin]' \
+    '!(--all : --annotate-stdin)--stdin' \
     '--name-only[display only name of commits]' \
     '--no-undefined[die with non-zero return when a reference is undefined]' \
     '--always[show uniquely abbreviated commit object as fallback]' \
-    '(--stdin --all)*: :__git_commits'
+    '(--annotate-stdin --all)*: :__git_commits'
 }
 
 (( $+functions[_git-pack-redundant] )) ||
@@ -5548,7 +5674,7 @@ _git-rev-list () {
   declare -A opt_args
 
   declare -a revision_options
-  __git_setup_revision_options
+  __git_setup_revision_options -d
 
   _arguments -C -S $endopt \
     $revision_options \
@@ -5563,6 +5689,8 @@ _git-rev-list () {
     "--no-object-names[don't print the names of the object IDs that are found]" \
     '!(--no-object-names)--object-names)' \
     '--timestamp[print raw commit timestamp]' \
+    "*--exclude-hidden=[don't include refs that would be hidden by git-receive-pack or git-upload-pack]:value:(fetch receive uploadpack)" \
+    '--disk-usage=-[print space used for storage by the selected commits or objects]::value:(human)' \
     '(         --bisect-vars --bisect-all)--bisect[show only middlemost commit object]' \
     '(--bisect)--bisect-vars[same as --bisect, displaying shell-evalable code]' \
     '(--bisect)--bisect-all[display all commit objects between included and excluded commits]' \
@@ -5847,46 +5975,51 @@ _git-upload-pack () {
 
 (( $+functions[_git-check-attr] )) ||
 _git-check-attr () {
-  local z_opt=
-
-  local curcontext=$curcontext state line ret=1
+  local curcontext="$curcontext" z_opt ret=1
+  local -a state line
   declare -A opt_args
 
   if (( words[(I)--stdin] )); then
-    z_opt='-z[paths are separated with NUL character when reading from stdin]'
+    z_opt='-z[terminate input file list and output records by a NUL character]'
+  else
+    z_opt='-z[separate output records with NUL character]'
   fi
 
-  _arguments -C \
-    {-a,--all}'[list all attributes that are associated with the specified paths]' \
+  _arguments -C $z_opt \
     '--stdin[read file names from stdin instead of from command line]' \
-    '--cached[consider .gitattributes in the index only, ignoring the working tree.]' \
-    '-z[terminate input and output records by a NUL character]' \
-    $z_opt \
+    '(--source)--cached[consider .gitattributes in the index only, ignoring the working tree]' \
+    '(--cached)--source=[specify tree to scan for .gitattributes (useful in bare repo)]:tree object:__git_tree_ishs' \
+    - files \
+    '(-a --all --)'{-a,--all}'[list all attributes that are associated with the specified paths]' \
     '(-)--[interpret preceding arguments as attributes and following arguments as path names]' \
-    '*:: :->attribute-or-file' && ret=0
+    '*: :__git_cached_files' \
+    - attrs \
+    '*:::attribute:->attributes' && ret=0
 
   case $state in
-    (attribute-or-file)
-      local -a attributes
-
-      attributes=(crlf ident filter diff merge)
-
-      local only_attributes=1
-      for (( i = 2; i < $#words; i++ )); do
-        if (( attributes[(I)$words[i]] == 0 )); then
-          only_attributes=0
-          break
-        fi
-      done
-
-      if (( !only_attributes )) || [[ -n ${opt_args[(I)--]} ]]; then
-        __git_cached_files && ret=0
-      else
-        _alternative \
-          'attributes::__git_attributes' \
-          'files::__git_cached_files' && ret=0
-      fi
-      ;;
+    attributes)
+      local -a attributes plain dedup
+      attributes=(
+        crlf:"line-ending convention (deprecated)"
+        text:"line-ending normalization"
+        eol:"line-ending style"
+        working-tree-encoding:"text encoding in working directory"
+        ident:'$Id$ substitution'
+        filter:"filters"
+        diff:"textual diff"
+        merge:"merging strategy"
+        conflict-marker-size:"length of markers left in the work tree"
+        whitespace:"control over what diff and apply should consider whitespace errors"
+        export-ignore:"exclude from archive files"
+        export-subst:"expand placeholders when adding to an archive"
+        delta:"don't attempt compression of blobs"
+        encoding:"character encoding that should be used by GUI tools"
+      )
+      plain=( ${attributes%%:*} )
+      dedup=( "${(@)words[1,CURRENT-1]}" )
+      (( ! ${#dedup:|plain} )) && _describe -t git-attributes \
+          attribute attributes -F dedup && ret=0
+    ;;
   esac
 
   return ret
@@ -5910,9 +6043,28 @@ _git-fmt-merge-msg () {
     '(      --no-log)--log=-[display one-line descriptions from actual commits being merged]::number of commits [20]' \
     '(--log         )--no-log[do not display one-line descriptions from actual commits being merged]' \
     '(-m --message)'{-m+,--message=}'[use given message instead of branch names for first line in log message]:message' \
-    '(-F --file)'{-F,--file}'[specify list of merged objects from file]: :_files'
+    '--into-name=[specify substitute name for the real target branch to use]:name' \
+    '(-F --file)'{-F+,--file=}'[specify list of merged objects from file]: :_files'
+}
+
+(( $+functions[_git-hook] )) ||
+_git-hook() {
+  local -a args
+  local gitdir=$(_call_program gitdir git rev-parse --git-dir)
+  [[ -f $gitdir/gitdir ]] && gitdir=$(<$gitdir/gitdir) # needed in worktrees
+
+  (( ${(M)#words[1,CURRENT-1]:#[^-]*} >= 3 )) && args=(
+    {--,--end-of-options}'[end options to git hook, allowing options to the hook itself]'
+  )
+  [[ -n ${(M)words[1,CURRENT-1]:#--(|end-of-options)} ]] && args=( '*:: :_default' )
+  _arguments $args \
+    '--ignore-missing[ignore any missing hook by quietly returning zero]' \
+    "--to-stdin=[specify file which will be redirected to hook's stdin]:file:_files" \
+    '1:subcommand:(run)' \
+    '2:hook name:compadd $gitdir/hooks/*(x\:t)'
 }
 
+
 (( $+functions[_git-mailinfo] )) ||
 _git-mailinfo () {
   # TODO: --no-inbody-headers is undocumented.
@@ -5952,7 +6104,8 @@ _git-merge-one-file () {
 _git-patch-id () {
    _arguments \
      '--stable[use a sum of hashes unaffected by diff ordering]' \
-     '--unstable[use patch-id compatible with git 1.9 and older]'
+     '--unstable[use patch-id compatible with git 1.9 and older]' \
+     "--verbatim[don't strip whitespace from the patch]"
 }
 
 # NOTE: git-sh-setup isn't a user command.
@@ -6167,6 +6320,7 @@ _git_commands () {
     blame:'show what revision and author last modified each line of a file'
     bugreport:'collect information for user to file a bug report'
     count-objects:'count unpacked objects and display their disk consumption'
+    diagnose:'generate an archive of diagnostic information'
     difftool:'show changes using common diff tools'
     fsck:'verify connectivity and validity of objects in database'
     help:'display help information about git'
@@ -6196,7 +6350,7 @@ _git_commands () {
     checkout-index:'copy files from index to working directory'
     commit-graph:'write and verify Git commit-graph files'
     commit-tree:'create new commit object'
-    hash-object:'compute object ID and optionally create a blob from a file'
+    hash-object:'compute object ID and optionally create an object from a file'
     index-pack:'build pack index file for an existing packed archive'
     merge-file:'run a three-way file merge'
     merge-index:'run merge for files needing merging'
@@ -6258,6 +6412,7 @@ _git_commands () {
     check-ref-format:'ensure that a reference name is well formed'
     column:'display data in columns'
     fmt-merge-msg:'produce merge commit message'
+    hook:'run git hooks'
     mailinfo:'extract patch and authorship from a single email message'
     mailsplit:'split mbox file into a list of files'
     merge-one-file:'standard helper-program to use with git merge-index'
@@ -6301,6 +6456,18 @@ _git_commands () {
   _alternative $alts
 }
 
+(( $+functions[_git_help_guides] )) ||
+_git_help_guides() {
+  local -a guides userint devint
+  guides=( ${${${(M)${(f)"$(_call_program git-guides git help -g)"}:# *}## #}/ ##/:} )
+  userint=( ${${${(M)${(f)"$(_call_program git-guides git help --user-interfaces)"}:# *}## #}/ ##/:} )
+  devint=( ${${${(M)${(f)"$(_call_program git-guides git help --developer-interfaces)"}:# *}## #}/ ##/:} )
+  _alternative \
+    'git-guides: : _describe -t git-guides guide guides' \
+    'user-interfaces: : _describe -t user-interfaces "user interface" userint' \
+    'developer-interfaces: : _describe -t developer-interfaces "developer interfaces" devint'
+}
+
 (( $+functions[__git_aliases] )) ||
 __git_aliases () {
   local -a aliases
@@ -6338,7 +6505,7 @@ __git_date_formats () {
   declare -a date_formats
 
   if compset -P 'format(-local|):'; then
-    _strftime
+    _date_formats
     return
   fi
 
@@ -6565,20 +6732,6 @@ __git_compression_levels () {
     '9:maximum compression'
 }
 
-(( $+functions[__git_attributes] )) ||
-__git_attributes () {
-  local -a attributes
-
-  attributes=(
-    'crlf:line-ending convention'
-    'ident:ident substitution'
-    'filter:filters'
-    'diff:textual diff'
-    'merge:merging strategy')
-
-  _describe -t attributes attribute attributes $*
-}
-
 (( $+functions[__git_daemon_service] )) ||
 __git_daemon_service () {
   local -a services
@@ -6994,7 +7147,6 @@ __git_heads_remote () {
 
 (( $+functions[__git_commit_objects] )) ||
 __git_commit_objects () {
-  local gitdir expl start
   declare -a commits
 
   if [[ -n $PREFIX[(r)@] ]] || [[ -n $SUFFIX[(r)@] ]]; then
@@ -7016,7 +7168,7 @@ __git_commit_objects () {
 
 (( $+functions[__git_recent_commits] )) ||
 __git_recent_commits () {
-  local gitdir expl start
+  local expl
   declare -a descr tags heads commits argument_array_names commit_opts
   local h i j k ret
   integer distance_from_head
@@ -7300,6 +7452,16 @@ __git_remote_references () {
   __git_references
 }
 
+(( $+functions[_git_full_references] )) ||
+_git_full_references() {
+
+  if [[ $_git_full_refs_cache_pwd != $PWD ]]; then
+    _git_full_refs_cache=( ${(f)"$(_call_program references 'git for-each-ref --format=%\(refname\)')"} )
+    _git_full_refs_cache_pwd=$PWD
+  fi
+  _multi_parts "$@" / _git_full_refs_cache
+}
+
 (( $+functions[__git_notes_refs] )) ||
 __git_notes_refs () {
   local expl
@@ -7395,6 +7557,19 @@ __git_deleted_files () {
   __git_files --deleted deleted-files 'deleted file' $*
 }
 
+(( $+functions[__git_trailers_tokens] )) ||
+__git_trailers_tokens() {
+  declare -a trailers
+  local i
+
+  local -a gtrailers=( $(_call_program trailers git config --name-only --get-regexp '^trailer\..*\.key$') )
+  for i in $gtrailers; do
+    i=( ${${(@s:.:)i}[2,-2]} )
+    trailers+=( ${(j|.|)i} )
+  done
+  _wanted trailers expl "trailer" compadd -a trailers
+}
+
 (( $+functions[__git_modified_files] )) ||
 __git_modified_files () {
   __git_files --modified modified-files 'modified file' $*
@@ -7616,10 +7791,65 @@ __git_guard_bytes () {
   _numbers -u bytes ${*:-size} k m g
 }
 
-(( $+functions[__git_datetimes] )) ||
-__git_datetimes () {
-  # TODO: Use this in more places.
-  _guard '*' 'time specification'
+(( $+functions[_git_approxidates] )) ||
+_git_approxidates() {
+  local MATCH MBEGIN MEND
+  local match mbegin mend
+  local -i date time num
+  local -a months=( January February March April May June July August September
+      October November December )
+  local -a weekdays=( Sunday Monday Tuesday Wednesday Thursday Friday Saturday )
+  local -a numbers=( zero one two three four five six seven eight nine ten )
+  local -a periods=( second minute hour day week month year )
+  local -a suf=( -S. -r "._,+\\ \t\n\-" )
+
+  local -a pexpl
+  zparseopts -D -E X+:=pexpl
+
+  local -a query=(
+    \( /$'*\0[ \t\n]#'/ \)
+    \( '/[]/' ':dates:date:compadd "${pexpl[@]:/-X/-x}"'
+    \| '/(@|[0-9](#c9))/' ':specials:special:compadd -S "" @' '/[]/' ': _message -e epochtimes "seconds since Unix epoch"'
+    \| '/(#i)(now|never)/' '%?%' ':specials:special:(now never)' '/[]/'
+    \| \)
+    \(
+      \( '/(#i)(one|last)/' '%[ ._,+]%' -'num=1'
+      \| '/[0-9](#c2,4)(-|/|.|)[0-9](#c1,2)(-|/|.|)[0-9](#c1,4)(|T)/' -'date=3'
+      \| '/[0-9](#c2)(:|)[0-9](#c2)(:|)[0-9](#c2)(.<->|)/' -'time=1'
+      \| '/20/' -'((!date))' '/[]/' ':dates:date:_dates -f "%y-%m-%d"'
+      \| '/1/' -'num=1'
+      \| '/<->/' -'num=2'
+      \| "/(#i)(${(j.|.)numbers})/" '%[ ._,+]%' -'num=2'
+      \| "/(#i)(${(j.|.)${(@)months//(#b)(???)(*)/$match[1]${match[2]//(#m)?/(|$MATCH}${match[2]//?/)}}})/"
+         '%[ ._,+]%' -'(( num = 0, date |= 2 ))'
+      \| "/(#i)(${(j.|.)${(@)weekdays//(#b)(???)(*)/$match[1]${match[2]//(#m)?/(|$MATCH}${match[2]//?/)}}})(|s)/"
+         '%[ ._,+]%' -'(( num = 0, date |= 1 ))'
+      \| '/(#i)yesterday/' '%[ ._,+]%' -'date=3'
+      \| "/(#i)(${(j.|.)${(@)periods%s}})(|s)/" '%[ ._,+]%' -'num=0'
+      \| '/(#i)(noon|midnight|tea|[ap]m)/' '%[ ._,+]%' -'time=1'
+      \|
+        \( // -'(( !(date&2) ))' // ':months:month:compadd -o nosort $suf -a months' \| \)
+        \( // -'(( num <= 1 && !(date&1) ))' // ':weekdays:weekday:compadd $suf -o nosort -a weekdays' \| \)
+        \( // -'(( num > 1 ))'
+          \( // -'(( date < 3 ))' // ':periods:period:compadd $suf -o nosort ${^periods[4,-1]}s' \| \)
+          \( // -'(( !(date&1) ))' // ':weekdays:weekday:compadd $suf -o nosort ${^weekdays}s' \| \)
+          \( // -'(( !time ))' // ':periods:period:compadd $suf -o nosort ${^periods[1,3]}s' \| \)
+        \| // -'(( num == 1 ))'
+          \( // -'(( date < 3 ))' // ':periods:period:compadd $suf -o nosort -a "periods[4,-1]"' \| \)
+          \( // -'(( !time ))' // ':periods:period:compadd $suf -o nosort -a "periods[1,3]"' \| \)
+        \| // -'(( num == 0 ))'
+          \( // -'(( !time ))' // ':specials:special:compadd $suf noon midnight tea AM PM' \| \)
+          \( // -'(( !date ))' // ':specials:special:compadd $suf yesterday' \| \)
+          // ':specials:special:compadd $suf last' # "last" is equivalent to "one"
+          // ':numbers:number:compadd $suf -n -o nosort -a numbers'
+        \)
+        '/[]/'
+      \) '/([ ._,+]|)/'
+    \) \#
+  )
+
+  _regex_arguments _git_dates "$query[@]"
+  _git_dates
 }
 
 (( $+functions[__git_stages] )) ||
@@ -7639,6 +7869,7 @@ __git_setup_log_options () {
   # TODO: Need to implement -<n> for limiting the number of commits to show.
   log_options=(
     '(- *)-h[display help]'
+    '--clear-decorations[clear all previously-defined decoration filters]'
     '--decorate-refs=[only decorate refs that match pattern]:pattern'
     "--decorate-refs-exclude=[don't decorate refs that match pattern]:pattern"
     '(           --no-decorate)--decorate=-[print out ref names of any commits that are shown]: :__git_log_decorate_formats'
@@ -7679,8 +7910,9 @@ __git_setup_diff_options () {
   local exclusive_diff_options='(--name-only --name-status --check -s --no-patch)'
 
   diff_options=(
-    {-p,-u,--patch}'[generate diff in patch format]'
-    {-U,--unified=}'[generate diff with given lines of context]: :__git_guard_number lines'
+    '(-p -u --patch)'{-p,-u,--patch}'[generate diff in patch format]'
+    '(-U --unified -W --function-context)'{-U-,--unified=-}'[generate diff with given lines of context]:: :__git_guard_number lines'
+    '(-U --unified -W --function-context)'{-W,--function-context}'[show whole function where a match was found]' \
     '--raw[generate default raw diff output]'
     '--patch-with-raw[generate patch but also keep the default raw diff output]'
     $exclusive_diff_options{-s,--no-patch}'[suppress diff output]'
@@ -7761,7 +7993,6 @@ __git_setup_diff_options () {
     '--output-indicator-new=[specify the character to indicate a new line]:character [+]'
     '--output-indicator-old=[specify the character to indicate a old line]:character [-]'
     '--output-indicator-context=[specify the character to indicate a context line]:character [ ]'
-    '--exit-code[report exit code 1 if differences, 0 otherwise]'
     '(           --no-ext-diff)--ext-diff[allow external diff helper to be executed]'
     '(--ext-diff              )--no-ext-diff[disallow external diff helper to be executed]'
     '(--textconv --no-textconv)--textconv[allow external text conversion filters to be run when comparing binary files]'
@@ -7770,9 +8001,13 @@ __git_setup_diff_options () {
     '(--no-prefix)--src-prefix=[use given prefix for source]:prefix'
     '(--no-prefix)--dst-prefix=[use given prefix for destination]:prefix'
     '--line-prefix=[prepend additional prefix to every line of output]:prefix'
-    '(--src-prefix --dst-prefix)--no-prefix[do not show any source or destination prefix]'
+    "(--src-prefix --dst-prefix)--no-prefix[don't show any source or destination prefix]"
+    '!(--src-prefix --dst-prefix --no-prefix)--default-prefix'
     '(-c --cc)'{-c,--cc}'[combined diff format for merge commits]'
-    '--output=[output to a specific file]: :_files')
+    '--output=[output to a specific file]: :_files'
+    '--expand-tabs=-[replace each tab with spaces]::tab width [8]'
+    '!(--expand-tabs)--no-expand-tabs'
+  )
 }
 
 (( $+functions[__git_setup_diff_stage_options] )) ||
@@ -7882,11 +8117,15 @@ __git_format_placeholders() {
 
 (( $+functions[__git_setup_revision_options] )) ||
 __git_setup_revision_options () {
-  local -a diff_options
-  __git_setup_diff_options
+  if [[ $1 = "-d" ]]; then # don't include diff options if passed -d
+    revision_options=()
+  else
+    local -a diff_options
+    __git_setup_diff_options
+    revision_options=( $diff_options )
+  fi
 
-  revision_options=(
-    $diff_options
+  revision_options+=(
     '(-v --header)'{--pretty=-,--format=-}'[pretty print commit messages]::format:__git_format_placeholders'
     '(--abbrev-commit --no-abbrev-commit)--abbrev-commit[show only partial prefixes of commit object names]'
     '(--abbrev-commit --no-abbrev-commit)--no-abbrev-commit[show the full 40-byte hexadecimal commit object name]'
@@ -7906,8 +8145,8 @@ __git_setup_revision_options () {
     '--count[display how many commits would have been listed]'
     '(-n --max-count)'{-n+,--max-count=}'[maximum number of commits to display]: :__git_guard_number'
     '--skip=[skip given number of commits before output]: :__git_guard_number'
-    '(--max-age --since --after)'{--since=,--after=}'[show commits more recent than given date]:date'
-    '(--min-age --until --before)'{--until=,--before=}'[show commits older than given date]: :__git_guard_number timestamp'
+    '(--max-age --since --after)'{--since=,--after=}'[show commits more recent than given date]: :_git_approxidates'
+    '(--min-age --until --before)'{--until=,--before=}'[show commits older than given date]: :_git_approxidates'
     '(          --since --after)--max-age=-[maximum age of commits to output]: :__git_guard_number timestamp'
     '(          --until --before)--min-age[minimum age of commits to output]: :__git_guard_number timestamp'
     '*--author=[limit commits to those by given author]:author'
@@ -7934,8 +8173,7 @@ __git_setup_revision_options () {
     '--tags=-[show all commits from refs/tags]::pattern'
     '--remotes=-[show all commits from refs/remotes]::pattern'
     '--glob=[show all commits from refs matching glob]:pattern'
-    '--exclude=[do not include refs matching glob]:pattern'
-    '--exclude=[do not include refs matching glob]:pattern'
+    "--exclude=[don't include refs matching glob]:pattern"
     '--ignore-missing[ignore invalid object an ref names on command line]'
     '--bisect[pretend as if refs/bisect/bad --not refs/bisect/good-* was given on command line]'
     '(-g --walk-reflogs --reverse)'{-g,--walk-reflogs}'[walk reflog entries from most recent to oldest]'
@@ -8021,6 +8259,7 @@ __git_setup_fetch_options () {
     '--refmap=[specify refspec to map refs to remote tracking branches]:refspec'
     '(-4 --ipv4 -6 --ipv6)'{-4,--ipv4}'[use IPv4 addresses only]'
     '(-4 --ipv4 -6 --ipv6)'{-6,--ipv6}'[use IPv6 addresses only]'
+    '--porcelain[machine-readable output]'
     '--dry-run[show what would be done, without making any changes]'
     '(-f --force)'{-f,--force}'[force overwrite of local reference]'
     '(-k --keep)'{-k,--keep}'[keep downloaded pack]'
@@ -8415,7 +8654,7 @@ _git() {
     # TODO: This needs an update
     # TODO: How do we fix -c argument?
     _arguments -C \
-      '(- :)--version[display version information]' \
+      '(- :)'{-v,--version}'[display version information]' \
       '(- :)--help[display help message]' \
       '-C[run as if git was started in given path]: :_directories' \
       \*{-c,--config-env=}'[pass configuration parameter to command]: :->configuration' \
@@ -8428,7 +8667,6 @@ _git() {
       '--git-dir=[path to repository]: :_directories' \
       '--work-tree=[path to working tree]: :_directories' \
       '--namespace=[set the Git namespace]:namespace' \
-      '--super-prefix=[set a prefix which gives a path from above a repository down to its root]:path:_directories' \
       '--bare[use $PWD as repository]' \
       '--no-replace-objects[do not use replacement refs to replace git objects]' \
       '--literal-pathspecs[treat pathspecs literally, rather than as glob patterns]' \
diff --git a/Completion/Unix/Command/_global b/Completion/Unix/Command/_global
index ffd8c0dce..4ffd7f8ce 100644
--- a/Completion/Unix/Command/_global
+++ b/Completion/Unix/Command/_global
@@ -9,15 +9,18 @@ _arguments \
   "$cmds"{-I,--idutils}'[print all lines which match pattern using id-utils]:pattern' \
   "$cmds"{-p,--print-dbpath}'[print location of GTAGS]' \
   "$cmds"{-P,--path}'[print paths matching pattern]:pattern:' \
+  "$cmds"'--print[print locate of root/dbpath/conf]:name:(root dbpath conf)' \
   "$cmds"{-u,--update}'[locate tag files and update incrementally]' \
   '(-a --absolute)'{-a,--absolute}'[print absolute path names]' \
   '(--color)--color=-[color matches]::color:(always auto never)' \
+  '(-C --directory)'{-C,--directory}'[change the directory before doing all the work]:dir:_files -/' \
   '(-d --definition)'{-d,--definition}'[print locations of definitions]' \
   '(-e --regexp :)'{-e,--regexp}'[specify pattern]:pattern:_global_tags' \
+  '(-E --extended-regexp -G --basic-regexp)'{-E,--extended-regexp}'[interpret pattern as a extended regular expression]' \
   '(--encode-path)--encode-path=-[encode path characters in hexadecimal representation]:format' \
   '(-F --first-match)'{-f,--first-match}'[stop searching if tag is found in current tag file]' \
   '(--from-here)--from-here=-[decide tag type by context]:line_path:' \
-  '(-G --basic-regexp :)'{-G,--basic-regexp}'[specify basic regexp to use]:word:_global_tags' \
+  '(-E --extended-regexp -G --basic-regexp)'{-G,--basic-regexp}'[interpret pattern as a basic regular expression]' \
   '(--gtagsconf)--gtagsconf=-[set environment variable GTAGSCONF]:file:_files' \
   '(--gtagslabel)--gtagslabel=-[set environment variable GTAGSLABEL]:file:_files' \
   '(-i --ignore-case)'{-i,--ignore-case}'[ignore case in patterns]' \
@@ -27,6 +30,7 @@ _arguments \
   '(-M --match-case)'{-m,--match-case}'[enable case sensitive search]' \
   '(--match-part)--match-part=-[specify how path name completion should match]::part:(first last all)' \
   '(-n --nofilter)'{-n,--nofilter}'[suppress sort filter and path conversion filter]' \
+  '(-N --nearness)'{-N,--nearness=-}'[use nearness sort method for the output]:start:_files' \
   '(-O --only-other)'{-O,--only-other}'[search only text files]' \
   '(-o --other)'{-o,--other}'[search in other files, not just source files (with -g)]' \
   '(--path-style)--path-style=-[specify path style]::style:(relative absolute shorter abslib through)' \
@@ -34,11 +38,12 @@ _arguments \
   '(-q --quiet)'{-q,--quiet}'[quiet mode]' \
   '(-r --reference --rootdir)'{-r,--reference,--rootdir}'[find object references instead of definitions]' \
   '(--result)--result=-[specify result format]::format:(path ctags ctags-x grep cscope)' \
-  '(- :)--single-update=-[updata tag for specified file]:file:_files' \
+  '(- :)--single-update=-[update tag for specified file]:file:_files' \
   '(-s --symbol)'{-s,--symbol}'[find symbols instead of function names]:pattern' \
   '(-t --tags)'{-t,--tags}'[output in standard ctags format]' \
   '(-T --through -s -r -l)'{-T,--through}'[search through all tag files in GTAGSLIBPATH]' \
   '(-v --verbose)'{-v,--verbose}'[verbose mode]' \
+  '(-V --invert-match)'{-V,--invert-match}'[invert the sense of matching, to select non-matching lines]' \
   '(-x --cxref)'{-x,--cxref}'[additionally list line number and contents]' \
   '(- :)--version[display version information]' \
   '(- :)--help[display help information]' \
diff --git a/Completion/Unix/Command/_gnutls b/Completion/Unix/Command/_gnutls
index b9f91264d..9b8bcf6ea 100644
--- a/Completion/Unix/Command/_gnutls
+++ b/Completion/Unix/Command/_gnutls
@@ -4,8 +4,7 @@ local -a args
 
 args=(
   '(- :)'{-h,--help}'[display help information]'
-  '(- :)--version=[display version information]:information:((v\:simple c\:copyright n\:full))'
-  '(- :)-v[display version information]'
+  '(- :)'{-v+,--version=-}'[display version information]:information:((v\:simple c\:copyright n\:full))'
   '(- :)'{-\!,--more-help}'[display help information through a pager]'
   '(-d --debug)'{-d,--debug}'[enable debugging]:debug level'
   \*{-V,--verbose}'[more verbose output]'
@@ -17,6 +16,11 @@ case "$service" in
       '(-p --port)'{-p,--port}'[specify port or service to connect to]:port:_ports'
     )
   ;|
+  gnutls-*|certtool)
+    args+=(
+      '--attime=[perform validation at the timestamp instead of the system time]:timestamp'
+    )
+  ;|
   gnutls-cli*)
     args+=(
       '(--app-proto --starttls-proto)'{--app-proto,--starttls-proto}"=[specify application protocol to use to obtain the server's certificate]:protocol:(https ftp smtp imap ldap xmpp lmtp pop3 nntp sieve postgres)"
@@ -30,6 +34,7 @@ case "$service" in
       '(-u --udp)'{-u,--udp}'[use DTLS (datagram TLS) over UDP]'
       '--mtu=[set MTU for datagram TLS]:mtu'
       '--srtp-profiles=[offer SRTP profiles]:string'
+      '*--compress-cert=[compress certificate]:compression method'
       '(-b --heartbeat)'{-b,--heartbeat}'[activate heartbeat support]'
       '--x509fmtder[use DER format for certificates to read from]'
       '--priority=[specify TLS algorithms and protocols to enable]:(NORMAL PFS SECURE128 SECURE192 SUITEB128 SUITEB192 LEGACY PERFORMANCE NONE)'
@@ -94,7 +99,8 @@ case "$service" in
       '--post-handshake-auth[enable post-handshake authentication under TLS1.3]'
       '--inline-commands[inline commands of the form ^<cmd>^]'
       '--inline-commands-prefix=[change delimiter used for inline commands]:delimiter [^]'
-      '--fips140-mode[report status of FIPS140-2 mode in gnutls library]'
+      '--fips140-mode[report status of FIPS140-3 mode in gnutls library]'
+      '--list-config[report configuration of the library]'
       '--logfile=[redirect informational messages to a specific file]:file:_files'
       '--waitresumption[block waiting for the resumption data under TLS1.3]'
       '--ca-auto-retrieve[enable automatic retrieval of missing CA certificates]'
@@ -127,6 +133,7 @@ case "$service" in
       '--ignore-ocsp-response-errors[ignore any errors when setting the OCSP response]'
       '--recordsize=[specify maximum record size to advertise]:record size (0-16384)'
       '--httpdata=[specify data to use as HTTP response]:file:_files'
+      '--timeout=[specify he timeout period for server]:timeout'
     )
   ;;
 
diff --git a/Completion/Unix/Command/_gpg b/Completion/Unix/Command/_gpg
index 5d54865d5..2161d2d24 100644
--- a/Completion/Unix/Command/_gpg
+++ b/Completion/Unix/Command/_gpg
@@ -93,6 +93,7 @@ fi
   '--no-default-recipient[reset default recipient]'
   '*--encrypt-to[specify recipient]:key:->public-keys'
   '(--encrypt-to)--no-encrypt-to[disable the use of all --encrypt-to keys]'
+  '--group[set up email aliases]:spec'
   '-z[specify compression level]:compression level:((0\:no\ compression 1\:minimum 2 3 4 5 6\:default 7 8 9\:maximum))'
   '(-t --textmode)'{-t,--textmode}'[use canonical text mode]'
   '(-n --dry-run)'{-n,--dry-run}"[don't make any changes]"
@@ -117,6 +118,7 @@ fi
   '--utf8-strings' '--no-utf8-strings[arguments are not in UTF8]'
   '(--no-options)--options[specify file to read options from]:options file:_files'
   "(--options)--no-options[don't read options file]"
+  '--log-file[write server mode logs to file]:file:_files'
   '--'{attribute,passphrase,command}'-fd:file descriptor:_file_descriptors'
   '--sk-comments[include secret key comments when exporting keys]'
   '(--emit-version)--no-emit-version[omit version string in clear text signatures]'
@@ -170,6 +172,9 @@ fi
   '--ctapi-driver[file to use to access smartcard reader]:file:_files'
   '--pcsc-driver[file to use to access smartcard reader]:file:_files'
   '--auto-key-locate:parameters'
+  '--auto-key-import[import missing key from a signature]'
+  '--include-key-block[include the public key in signatures]'
+  '--disable-dirmngr[disable all access to the dirmngr]'
   '--dump-options[show all options]'
 )
 
diff --git a/Completion/Unix/Command/_gprof b/Completion/Unix/Command/_gprof
index a7e602fd5..6b97506a6 100644
--- a/Completion/Unix/Command/_gprof
+++ b/Completion/Unix/Command/_gprof
@@ -4,7 +4,7 @@ local curcontext="$curcontext" state line ret=1
 typeset -A opt_args
 
 _arguments -C -s -{a,b,c,D,h,i,l,L,r,s,T,v,w,x,y,z} \
-           -{A,C,e,E,f,F,J,n,N,O,p,P,q,Q,R,S,t,Z}:'function name:->funcs' \
+           -{A,B,C,e,E,f,F,J,n,N,O,p,P,q,Q,R,S,t,Z}:'function name:->funcs' \
 	   '-I:directory:_dir_list' \
 	   '-d-:debug level:' '-k:function names:->pair' \
 	   '-m:minimum execution count:' \
diff --git a/Completion/Unix/Command/_gradle b/Completion/Unix/Command/_gradle
index c1f7c05ee..280aa243f 100644
--- a/Completion/Unix/Command/_gradle
+++ b/Completion/Unix/Command/_gradle
@@ -92,7 +92,7 @@ if [[ $state == task && ! -prefix - ]]; then
                 zle -R "Generating cache from $gradle_buildfile"
 
                 # Run gradle/gradlew and retrieve possible tasks.
-                for outputline in ${(f)"$($service --build-file $gradle_buildfile -q tasks --all)"}; do
+                for outputline in ${(f)"$($words[1] --build-file $gradle_buildfile -q tasks --all)"}; do
 
                     # Tasks and subprojects each start with a lowercase letter, but whereas tasks are in camelCase, each
                     # subproject consists of one or more sections of kebab-case, with each section ending in a ':'.
diff --git a/Completion/Unix/Command/_grep b/Completion/Unix/Command/_grep
index 2dcbff4a3..0f1e712fd 100644
--- a/Completion/Unix/Command/_grep
+++ b/Completion/Unix/Command/_grep
@@ -89,7 +89,7 @@ case $variant:$OSTYPE in
   ;|
   gpl2:(freebsd|darwin)*)
     arguments+=(
-      '(--null --no-filename -h)--null[print 0 byte after each filename]'
+      '(--no-filename -h)--null[print 0 byte after each filename]'
       '(-Z --decompress -J --bz2decompress)'{-J,--bz2decompress}"[decompress bzip2'ed input before searching]"
       '(-Z --decompress -J --bz2decompress)'{-Z,--decompress}"[decompress gzip'ed input before searching]"
     )
@@ -129,6 +129,7 @@ case $variant:$OSTYPE in
     arguments=(
       ${(M)arguments:#((#s)|*\))--(context|binary-files|line-buffered|label|max-count)*}
       ${${arguments:#((#s)|*\))(\*|)-[d-]*}/\)-r/\)-R}
+      '(-h)--null[print 0 byte after each filename]'
       "-U[search binary files but don't print them]"
       '-Z[behave as zgrep]'
     )
diff --git a/Completion/Unix/Command/_head b/Completion/Unix/Command/_head
index 0771b1e4d..8877600f6 100644
--- a/Completion/Unix/Command/_head
+++ b/Completion/Unix/Command/_head
@@ -9,6 +9,7 @@ if _pick_variant gnu=GNU unix --version; then
     '(-n --lines -c --bytes)'{-n+,--lines=}'[print the first (or with -, all but the last) specified lines]:number of lines:->number'
     '(-q --quiet --silent -v --verbose)'{-q,--quiet,--silent}'[never print headers giving file names]'
     '(-q --quiet --silent -v --verbose)'{-v,--verbose}'[always print headers giving file names]'
+    '(-z --zero-terminated)'{-z,--zero-terminated}'[line delimiter is NUL, not newline]'
     '(- *)--help[display help and exit]'
     '(- *)--version[output version information and exit]'
   )
diff --git a/Completion/Unix/Command/_iconv b/Completion/Unix/Command/_iconv
index bf04acfe4..fba0b9afe 100644
--- a/Completion/Unix/Command/_iconv
+++ b/Completion/Unix/Command/_iconv
@@ -63,7 +63,7 @@ else
     '1:file:_files' && return 0
 
   if [[ $state = codeset ]]; then
-    if [[ $OSTYPE = freebsd* ]]; then
+    if [[ $OSTYPE = (freebsd|dragonfly|netbsd|darwin)* ]]; then
       codeset=( $(_call_program codesets $words[1] -l) )
     elif [[ -f /usr/lib/iconv/iconv_data ]]; then  # IRIX & Solaris
       codeset=( ${${(f)"$(</usr/lib/iconv/iconv_data)"}%%[[:blank:]]*} )
diff --git a/Completion/Unix/Command/_id b/Completion/Unix/Command/_id
index a0a03faad..c123afcd7 100644
--- a/Completion/Unix/Command/_id
+++ b/Completion/Unix/Command/_id
@@ -41,13 +41,13 @@ else
     darwin*|dragonfly*|freebsd*)
       args+=( '(-)-P[print id in the form of a password file entry]' )
     ;|
-    darwin*|freebsd*)
+    freebsd*)
       args+=(
 	'(-)-A[print process audit user ID]'
 	'(-)-M[print MAC label of the current process]'
+        '(-)-c[print current login class]'
       )
     ;|
-    freebsd*) args+=( '(-)-c[print current login class]' ) ;|
     darwin*|dragonfly*|freebsd*|netbsd*|openbsd*)
       args+=( '(-)-p[human readable output]' )
     ;;
diff --git a/Completion/Unix/Command/_ifconfig b/Completion/Unix/Command/_ifconfig
index 25ddd55bd..86ec46038 100644
--- a/Completion/Unix/Command/_ifconfig
+++ b/Completion/Unix/Command/_ifconfig
@@ -13,17 +13,25 @@ updownlist=(
 
 case $OSTYPE in
   darwin*)
-    args=( -s $updownlist )
+    args=( -s $updownlist
+      '-X+[list interfaces whose names match regular expression]:regex:_net_interfaces'
+    )
     opts=(
       $alias $debug delete dest_address ipdst nsellength
       {,-}trailers {,-}link{0,1,2}
     )
-  ;;
+  ;|
   freebsd*|dragonfly*)
-    args=( -s $updown
-      '(-a -l -u -d -m -L 1 *)-C[list interface cloners]'
-      '(-l -C)-m[list supported media]'
-      '(-l -C)-L[show address lifetime as time offset]'
+    args=( -s $updownlist
+      '(-C)-f+[control the output format]: :_values -s, -S\: format
+        "addr[adjust inet address display]\:format [numeric]\:(default fqdn host numeric)"
+        "ether[adjust ethernet address display]\:format [colon]\:(colon dash dotted default)"
+        "inet[adjust inet subnet mask display]\:format [hex]\:(default cidr dotted hex)"
+        "inet6[adjust inet6 prefix display]\:format [numeric]\:(default cidr numeric)"'
+      '(-C)-G+[exclude members of the specified group]:group'
+      '(-C)-g+[limit output to members of the specified group]:group'
+      '(-C)-k[print keying information for the interface]'
+      '(-C)-n[disable automatic loading of network interface drivers]'
     )
     listopts=(
         active caps chan countries mac mesh regdomain roam txparam txpower
@@ -37,6 +45,17 @@ case $OSTYPE in
       roam roam:rssi roam:rate roaming
     )
   ;|
+  freebsd*|darwin*|dragonfly*)
+    args+=(
+      '(-a -j -f -l -G -g -u -d -m -L 1 *)-C[list interface cloners]'
+      '(-l -C)-m[list supported media]'
+      '(-l -C)-L[show address lifetime as time offset]'
+      '(-C)-v[get more verbose status for an interface]'
+    )
+  ;|
+  freebsd<14->.*)
+    args+=( '(-C)-j+[perform actions inside jail]:jail:_jails' )
+  ;;
   dragonfly*)
     args+=( '-n[disable auto-loading of kernel network interface driver]' )
   ;;
diff --git a/Completion/Unix/Command/_imagemagick b/Completion/Unix/Command/_imagemagick
index b7671fe49..6553868d9 100644
--- a/Completion/Unix/Command/_imagemagick
+++ b/Completion/Unix/Command/_imagemagick
@@ -12,7 +12,7 @@ typeset -A opt_args
 #
 # and certainly many other things...
 
-formats=(jpg jpeg jp2 j2k jpc jpx jpf tif tiff miff ras bmp cgm dcx ps eps fig fits fpx gif mpeg pbm pgm ppm pcd pcl pdf pcx png rad rgb rgba rle sgi html shtml tga ttf uil xcf xwd xbm xpm yuv)
+formats=(jpg jpeg jp2 j2k jpc jpx jpf tif tiff miff ras bmp cgm dcx ps eps fig fits fpx gif mpeg pbm pgm ppm pcd pcl pdf pcx png rad rgb rgba rle sgi html shtml tga ttf uil xcf xwd xbm xpm yuv svg webp)
 
 if (( $# )); then
   _files "$@" -g "*.(#i)(${(j:|:)formats})(-.)"
diff --git a/Completion/Unix/Command/_install b/Completion/Unix/Command/_install
index 364119961..881c99620 100644
--- a/Completion/Unix/Command/_install
+++ b/Completion/Unix/Command/_install
@@ -25,8 +25,9 @@ if _pick_variant gnu='Free Soft' unix --version; then
   args+=(
     $common_args
     '(-b --backup)--backup=[create backup; optionally specify method]:: :->controls'
-    "${lx}--context=-[like -Z, or specify SELinux security context to set]::SELinux security context:_selinux_contexts"
+    "${lx}--context=-[like -Z, or specify SELinux security context to set]::SELinux security context:_selinux_contexts -a file_type"
     '-D[create all leading destination path components]'
+    '--debug[explain how a file is copied. Implies -v]'
     '(: -)--help[display help information]'
     "${lx}--preserve-context[preserve SELinux security context]"
     '--strip-program=[specify program used to strip binaries]:strip program:_files'
diff --git a/Completion/Unix/Command/_iostat b/Completion/Unix/Command/_iostat
index 1152b0d8b..d3943fcb4 100644
--- a/Completion/Unix/Command/_iostat
+++ b/Completion/Unix/Command/_iostat
@@ -34,7 +34,6 @@ case $OSTYPE:l in
     args+=(
       '-x[show extended disk statistics]'
       '-z[omit lines for devices with no activity]'
-      '(* -)-?[display a usage statement and exit]'
     )
     ;;
   dragonfly*)
@@ -126,6 +125,7 @@ case $OSTYPE:l in
     parser=( -s )
     args=(
       '-c[display CPU utilization report]'
+      "--compact[don't break into sub-reports keeping metrics to a single line]"
       '-d[display device utilization report]'
       '--dec=-[specify the number of decimal places to use]:decimal places [2]:(0 1 2)'
       '-f[specify alternative directory to read device statistics from]:directory:_directories'
diff --git a/Completion/Unix/Command/_java b/Completion/Unix/Command/_java
index ff6e82645..325413d87 100644
--- a/Completion/Unix/Command/_java
+++ b/Completion/Unix/Command/_java
@@ -82,7 +82,10 @@ java)
     '(- 1)-X-[non-standard java option]:option' \
     '(- 1)-jar[specify a program encapsulated as jar]:jar:_files -g \*.jar\(-.\)' \
     '-splash\:-[show splash screen with specified image]:image:_files' \
-    '(-):class:_java_class -m main ${(kv)opt_args[(i)(-classpath|-cp)]}' \
+    '--source=[set the version of the source in source-file mode]:version' \
+    '(-):arg: _alternative
+      "classes\:class\:{ (( ! $+opt_args[--source] )) && _java_class -m main ${(kv)opt_args[(i)(-classpath|-cp)]} }"
+      "files\:source file\:_files -g \*.java\(-.\)"' \
     '*::args:= _normal' \
      && return 0
   ;;
@@ -438,8 +441,8 @@ classpath|sourcepath|bootstrapclasspath|docletpath)
   compset -P '*:'
   compset -S ':*'
   _alternative \
-    "classpath:$state:_path_files -qS: -g '*.(jar|zip)(-.)'" \
-    "classpath:$state:_path_files -r': ' -/" && return
+    "classpath:${state}:_path_files -qS: -g '*.(jar|zip)(-.)'" \
+    "classpath:${state}:_path_files -r': ' -/" && return
   ;;
 
 extdirs)
diff --git a/Completion/Unix/Command/_ldd b/Completion/Unix/Command/_ldd
index 3c7b088df..98ac41e14 100644
--- a/Completion/Unix/Command/_ldd
+++ b/Completion/Unix/Command/_ldd
@@ -30,8 +30,7 @@ else
     freebsd*)
       args=(
         '-a[show all objects that are needed by each loaded object]'
-	'-v[verbose listing of the dynamic linking headers]'
-	'-f+[specify format]:format:((%a\:program\ name %A\:environment\ name %o\:library\ name %p\:path\ to\ library %x\:load\ address))'
+	'*-f+[specify format]:format:((%a\:program\ name %A\:environment\ name %o\:library\ name %p\:path\ to\ library %x\:load\ address))'
       )
     ;;
   esac
diff --git a/Completion/Unix/Command/_less b/Completion/Unix/Command/_less
index 69f75fd0e..8772f5771 100644
--- a/Completion/Unix/Command/_less
+++ b/Completion/Unix/Command/_less
@@ -56,7 +56,7 @@ _arguments -S -s -A "[-+]*"  \
   '(-L --no-lessopen)'{-L,--no-lessopen}'[ignore the LESSOPEN environment variable]' \
   '(-M --LONG-PROMPT -m --long-prompt)'{-m,--long-prompt}'[prompt verbosely]' \
   '(-m --long-prompt -M --LONG-PROMPT)'{-M,--LONG-PROMPT}'[prompt very verbosely]' \
-  '(-N --LINE-NUMBERS -n --line-numbers)'{-n,--line-numbers}"[don't keep track of line numbers]" \
+  '(-N --LINE-NUMBERS -n --line-numbers)'{-n,--line-numbers}'[suppress line numbers in prompts and messages]' \
   '(-n --line-numbers -N --LINE-NUMBERS)'{-N,--LINE-NUMBERS}'[show line numbers]' \
   '(* -O --LOG-FILE -o --log-file)'{-o+,--log-file=}'[copy input to file]:file:_files' \
   '(* -o --log-file -O --LOG-FILE)'{-O+,--LOG-FILE=}'[copy input to file, overwriting if necessary]:file:_files' \
@@ -83,18 +83,39 @@ _arguments -S -s -A "[-+]*"  \
   '(-\" --quotes)'{'-\"+',--quotes=}'[change quoting character]:quoting characters' \
   '(-~ --tilde)'{-~,--tilde}"[don't display tildes after end of file]" \
   '(-\# --shift)'{'-\#+',--shift=}"[specify amount to move when scrolling horizontally]:number" \
+  '--exit-follow-on-close[exit F command on a pipe when writer closes pipe]' \
   '--file-size[automatically determine the size of the input file]' \
+  '--header=[set header size]:lines,columns' \
   '--incsearch[search file as each pattern character is typed in]' \
+  '--intr=[specify interrupt character instead of ^X]:char [^X]' \
   '--line-num-width=[set the width of line number field]:width [7]' \
+  '--modelines=[look for vim modelines]:lines to search' \
   '--follow-name[the F command changes file if the input file is renamed]' \
   '--mouse[enable mouse input]' \
   '--no-histdups[remove duplicates from command history]' \
+  "--no-number-headers[don't give line numbers to header lines]" \
+  "--no-search-headers[don't search in header lines or columns]" \
+  "--no-vbell[disable the terminal's visual bell]" \
+  '--redraw-on-quit[redraw final screen when quitting]' \
   '--rscroll=[set the character used to mark truncated lines]:character [>]' \
   '--save-marks[retain marks across invocations of less]' \
+  '--search-options=[set default options for every search]: : _values -s ""
+    "search option"
+    "E[multi-file]" "F[from first line]" "K[highlight]"
+    "N[non-matching]" "R[literal]" "W[wrap]" -' \
+  '--show-preproc-errors[display a message if preprocessor exits with an error status]' \
+  '--proc-backspace[process backspaces for bold/underline]' \
+  '--SPECIAL-BACKSPACE[treat backspaces as control characters]' \
+  '--proc-return[delete carriage returns before newline]' \
+  '--SPECIAL-RETURN[treat carriage returns as control characters]' \
+  '--proc-tab[expand tabs to spaces]' \
+  '--SPECIAL-TAB[treat tabs as control characters]' \
   '--status-col-width=[set the width of the -J status column]:width [2]' \
+  '--status-line[highlight or color the entire line containing a mark]' \
   '--use-backslash[subsequent options use backslash as escape char]' \
   '--use-color[enable colored text]' \
   '--wheel-lines=[specify lines to move for each click of the mouse wheel]:lines' \
+  '--wordwrap[wrap lines at spaces]' \
   "$files[@]" && ret=0
 
 
diff --git a/Completion/Unix/Command/_libvirt b/Completion/Unix/Command/_libvirt
index a3ab5a68a..bd605b9c9 100644
--- a/Completion/Unix/Command/_libvirt
+++ b/Completion/Unix/Command/_libvirt
@@ -20,7 +20,6 @@ typeset -A dom_opts
 dom_opts=(
   console " "
   destroy " "
-  edit " "
   managedsave " "
   reboot " "
   reset " "
diff --git a/Completion/Unix/Command/_ln b/Completion/Unix/Command/_ln
index 9d5efcabb..7bd2f7f27 100644
--- a/Completion/Unix/Command/_ln
+++ b/Completion/Unix/Command/_ln
@@ -45,9 +45,11 @@ case $variant; in
       {-h,-n}'[do not dereference destination]'
       '(-f)-i[prompt before removing destination files]')
     ;;
-  darwin*|dragonfly*|freebsd*|netbsd*|openbsd*)
+  darwin*|dragonfly*|*bsd*)
     args+=(
-      {-h,-n}'[do not dereference destination]'
+      {-h,-n}"[don't dereference destination]"
+      '(-L)-P[create hard links directly to symbolic links]'
+      '(-P)-L[create hard links to symbolic link references]'
     )
     ;|
   darwin*|dragonfly*|freebsd*|netbsd*)
@@ -57,12 +59,6 @@ case $variant; in
       '-v[print name of each linked file]'
     )
     ;|
-  dragonfly*|freebsd*|netbsd*|openbsd*)
-    args+=(
-      '(-L)-P[create hard links directly to symbolic links]'
-      '(-P)-L[create hard links to symbolic link references]'
-    )
-    ;|
   dragonfly*|freebsd*|netbsd*)
     args+=(
       "-w[warn if source of a symbolic link doesn't currently exist]"
diff --git a/Completion/Unix/Command/_ls b/Completion/Unix/Command/_ls
index df14e7e2c..392b8490b 100644
--- a/Completion/Unix/Command/_ls
+++ b/Completion/Unix/Command/_ls
@@ -75,12 +75,12 @@ if ! _pick_variant gnu=gnu unix --help; then
   if [[ $OSTYPE = (dragonfly*|freebsd*|darwin*) ]]; then
     arguments+=(
       '-G[enable colorized output]'
+      '(-A)-I[prevent -A from being automatically set for the super-user]'
       '-P[do not follow symlinks]'
     )
   fi
   if [[ $OSTYPE = (dragonfly*|freebsd*) ]]; then
     arguments+=(
-      '(-A)-I[prevent -A from being automatically set for the super-user]'
       '(-1 -C -m -x)-D+[specify format for date]:format: _date_formats'
     )
   fi
@@ -91,16 +91,19 @@ if ! _pick_variant gnu=gnu unix --help; then
     )
   fi
   if [[ $OSTYPE = (freebsd*|darwin*) ]]; then
-    arguments+=( '(-c -u)-U[file creation time]' )
-  fi
-  if [[ $OSTYPE = freebsd* ]]; then
     arguments+=(
       '-,[print file sizes grouped and separated by thousands]'
+      '(-c -u)-U[file creation time]'
       '-y[with -t, sort filenames in the same order as the time]'
-      '-Z[display MAC label]'
       '--color=-[control use of color]:color:(never always auto)'
     )
   fi
+  if [[ $OSTYPE = freebsd* ]]; then
+    arguments+=(
+      '(-S -f -t -U)-v[sort by version (filename treated numerically)]'
+      '-Z[display MAC label]'
+    )
+  fi
   if [[ $OSTYPE = darwin* ]]; then
     arguments+=(
       '-@[display extended attribute keys and sizes in long listing]'
@@ -108,6 +111,7 @@ if ! _pick_variant gnu=gnu unix --help; then
       '(-l -1 -C -m -x)-o[long listing but without group information]'
       '-O[display file flags]'
       '-v[print raw characters]'
+      '-%[distinguish dataless files and directories with a %]'
     )
   fi
   if [[ $OSTYPE = solaris* ]]; then
@@ -139,8 +143,8 @@ else
     '(--recursive -R)'{--recursive,-R}'[list subdirectories recursively]'
 
     '(--no-group -G)'{--no-group,-G}'[inhibit display of group information]'
-    '(--block-size --human-readable -h --si --kilobytes -k)'{--human-readable,-h}'[print sizes in human readable form]'
-    '(--block-size --human-readable -h --si --kilobytes -k)--si[sizes in human readable form; powers of 1000]'
+    '(--block-size --human-readable -h --si --kibibytes -k)'{--human-readable,-h}'[print sizes in human readable form]'
+    '(--block-size --human-readable -h --si --kibibytes -k)--si[sizes in human readable form; powers of 1000]'
     '(--inode -i)'{--inode,-i}'[print file inode numbers]'
 
     '(--format -l -g -o -1 -C -m -x)-l[long listing]'
@@ -148,40 +152,41 @@ else
     --group-directories-first
     '(--format -l --no-group -G -1 -C -m -x)-o[no group, long]'
     '(--format -l -g -o -C -m -x)-1[single column output]'
-    '(--format -l -g -o -1 -m -x)-C[list entries in columns sorted vertically]'
-    '(--format -l -g -o -1 -C -x)-m[comma separated]'
-    '(--format -l -g -o -1 -C -m)-x[sort horizontally]'
+    '(--format -l -g -o -1 -m -x --block-size --human-readable -h --si --kibibytes -k)-C[list entries in columns sorted vertically]'
+    '(--format -l -g -o -1 -C -x --block-size --human-readable -h --si --kibibytes -k)-m[comma separated]'
+    '(--format -l -g -o -1 -C -m --block-size --human-readable -h --si --kibibytes -k)-x[sort horizontally]'
     '(-l -g -o -1 -C -m -x)--format=[specify output format]:format:(verbose long commas horizontal across vertical single-column)'
 
     '(--size -s -f)'{--size,-s}'[display size of each file in blocks]'
 
     '(--time -u)-c[status change time]'
     '(--time -c)-u[access time]'
-    '(-c -u)--time=[specify time to show]:time:(ctime status use atime access)'
+    '(-c -u)--time=[specify time to show]:time:(ctime status use atime access birth creation)'
     '--time-style=[show times using specified style]:style: _alternative "time-styles\:time style\:(full-iso long-iso iso locale)" $datef'
 
     '(-a --all -U -l --format -s --size -t --sort --full-time)-f[unsorted, all, short list]'
     '(--reverse -r -U -f)'{--reverse,-r}'[reverse sort order]'
 
-    '(--sort -t -U -v -X)-S[sort by size]'
-    '(--sort -S -U -v -X)-t[sort by modification time]'
-    '(--sort -S -t -v -X)-U[unsorted]'
-    '(--sort -S -t -U -X)-v[sort by version (filename treated numerically)]'
-    '(--sort -S -t -U -v)-X[sort by extension]'
-    '(-S -t -U -v -X)--sort=[specify sort key]:sort key:(size time none version extension)'
+    '(--sort -f -t -U -v -X)-S[sort by size]'
+    '(--sort -f -S -U -v -X)-t[sort by modification time]'
+    '(--sort -f -S -t -v -X)-U[unsorted]'
+    '(--sort -f -S -t -U -X)-v[sort by version (filename treated numerically)]'
+    '(--sort -f -S -t -U -v)-X[sort by extension]'
+    '(-S -f -t -U -v -X)--sort=[specify sort key]:sort key:(size time none version extension)'
 
     '--color=-[control use of color]:color:(never always auto)'
     "*--hide=[like -I, but overridden by -a or -A]:pattern: "
     '--hyperlink=[output terminal codes to link files using file::// URI]::when:(none auto always)'
-    '(--classify -F --indicator-style -p --file-type)'{--classify,-F}'[append file type indicators]'
+    '(--classify -F --indicator-style -p --file-type)-F[append file type indicators]'
+    '(--classify -F --indicator-style -p --file-type)--classify=-[append file type indicators]::when [always]:(none auto always)'
     '(--file-type -p --indicator-style -F --classify)--file-type[append file type indicators except *]'
     '(--file-type -p --indicator-style -F --classify)-p[append / to directories]'
     '(-F --classify -p --file-type)--indicator-style=[specify indicator style]:indicator style:(none file-type classify slash)'
 
     '(-f)--full-time[list both full date and full time]'
 
-    '(--block-size --human-readable -h --si --kilobytes -k)'{--kilobytes,-k}'[use block size of 1k]'
-    '(--human-readable -h --si --kilobytes -k)--block-size=[specify block size]:block size (bytes):(K M G T P E Z Y KB MB TB PB EB ZB YB)'
+    '(--block-size --human-readable -h --si --kibibytes -k)'{--kibibytes,-k}'[use block size of 1k]'
+    '(--human-readable -h --si --kibibytes -k -C -x)--block-size=[specify block size]:block size (bytes):(K M G T P E Z Y KB MB TB PB EB ZB YB)'
 
     '(--numeric-uid-gid -n)'{--numeric-uid-gid,-n}'[numeric uid, gid]'
     '(--tabsize -T)'{--tabsize=,-T+}'[specify tab size]:tab size'
@@ -194,6 +199,7 @@ else
 
     '(--hide-control-chars -q --show-control-chars)'{--hide-control-chars,-q}'[hide control chars]'
     '(-q --hide-control-chars)--show-control-chars'
+    '--zero[end each output line with NUL, not newline]'
     '(- :)--help[display help information]'
     '(- :)--version[display version information]'
     '*:file:_files'
diff --git a/Completion/Unix/Command/_lsof b/Completion/Unix/Command/_lsof
index 8afb55e1d..60f59a589 100644
--- a/Completion/Unix/Command/_lsof
+++ b/Completion/Unix/Command/_lsof
@@ -9,6 +9,7 @@ case $OSTYPE in
       '-E[display endpoint info for pipes, sockets and pseudoterminal files but not files of the endpoints]'
       '+E[display endpoint info for pipes, sockets and pseudoterminal files including files of the endpoints]'
       '-X[skip reporting of info on network connections]'
+      '*-Z[display or filter by SELinux security context]::context pattern:_selinux_contexts -a domain'
     )
   ;;
   solaris*)
@@ -23,7 +24,6 @@ _arguments -C -s -S $args \
   '(-)'{-\?,-h}'[list help]' \
   '-a[AND selections]' \
   '-b[avoid kernel blocks]' \
-  '-C[disable reporting of path name components]' \
   '+c[truncate command name to specified characters]:characters' \
   '-c[list files with specified command name beginning]:command name' \
   '+d[search for open instances for contents of specified dir]:search directory:_files -/' \
@@ -31,16 +31,19 @@ _arguments -C -s -S $args \
   '+D[recursively search from specified dir]:search directory:_files -/' \
   '-D[direct use of device cache file]:function:((\?\:report\ device\ cache\ file\ paths b\:build\ the\ device\ cache\ file i\:ignore\ the\ device\ cache\ file r\:read\ the\ device\ cache\ file u\:read\ and\ update\ the\ device\ cache\ file))' \
   '*-+e[exempt filesystem from blocking kernel calls]:file system:_directories' \
+  '-+E[show endpoint information for pipes, sockets, ptys, mqueues and eventfds; with -E, omit endpoint files]' \
   '-f[inhibit listing of kernel file structure info]::info type:->file-structures' \
   '+f[enable listing of kernel file structure info]::info type:->file-structures' \
   '-F[select output fields]:fields:->fields' \
   '-g[select by process group id]::process group id:_sequence -s , _pgids' \
+  '-H[print human readable sizes]' \
   '(*)*-i[select internet files]::address:->addresses' \
   '-K+[select listing of tasks of processes]::value:((i\:ignore\ tasks))' \
   '-k[specify kernel name list file]:kernel file:_files' \
   '-l[inhibit conversion of UIDs to user names]' \
   '-L[list no link counts]' \
   '+L[list all link counts]::max link count for listed files' \
+  '+m[specify or write a mount supplement file]::mount supplement file:_files' \
   '-m[specify kernel memory file]:kernel memory file:_files' \
   '-M[disable reporting of portmapper registrations]' \
   '+M[enable reporting of portmapper registrations]' \
@@ -49,6 +52,7 @@ _arguments -C -s -S $args \
   '(-s)-o[list file offset]::digits for file offset' \
   '-O[avoid overheads of bypassing potential blocking]' \
   '-P[inhibit conversion of port numbers to port names]' \
+  '-Q[ignore failed search terms]' \
   '-p[list files for specified processes]:process ID:_sequence -s , _pids' \
   '-r[repeat listing endlessly]::delay (seconds)' \
   '+r[repeat listing until no files listed]::delay (seconds)' \
diff --git a/Completion/Unix/Command/_lua b/Completion/Unix/Command/_lua
index 7254d3819..3a1ef4fd7 100644
--- a/Completion/Unix/Command/_lua
+++ b/Completion/Unix/Command/_lua
@@ -41,6 +41,7 @@ _lua() {
   _arguments -S -A '-*' : \
     '*-e+[execute specified command string]:command string' \
     '-E[ignore environment variables]' \
+    '-W[turn warnings on]' \
     '-i[enter interactive mode]' \
     '*-l+[specify library or module to require]: :_lua_libraries' \
     '-v[display version information]' \
diff --git a/Completion/Unix/Command/_make b/Completion/Unix/Command/_make
index ae91440f0..99c786dc7 100644
--- a/Completion/Unix/Command/_make
+++ b/Completion/Unix/Command/_make
@@ -1,4 +1,4 @@
-#compdef make gmake pmake dmake freebsd-make bmake
+#compdef make gmake gnumake pmake dmake freebsd-make bmake
 
 # TODO: Based on targets given on the command line, show only variables that
 # are used in those targets and their dependencies.
@@ -118,10 +118,34 @@ _make-parseMakefile () {
   done
 }
 
+_make-parseDataBase () {
+  local input var TAB=$'\t' IFS= skip=0
+
+  while read input
+  do
+    if [[ $skip = 1 ]]; then
+      skip=0
+      continue
+    fi
+    case "$input " in
+      (\# Not a target*|\# environment*)
+        skip=1  # skip next line
+        ;;
+      ([[:alnum:]][[:alnum:]_]#[" "$TAB]#(\?|:|::|)=*)
+        var=${input%%[ $TAB]#(\?|:|::|)=*}
+        VARIABLES[$var]=1
+        ;;
+      ([[*?[:alnum:]$][^$TAB:=%]#:[^=]*)
+        TARGETS+=( ${input%%:*} )
+        ;;
+    esac
+  done
+}
+
 _make() {
 
   local prev="$words[CURRENT-1]" file expl tmp is_gnu incl match basedir nul=$'\0'
-  local context state state_descr line
+  local curcontext=$curcontext state state_descr line
   local -a option_specs
   local -A VARIABLES VAR_ARGS opt_args
   local -aU TARGETS keys
@@ -152,26 +176,28 @@ _make() {
       '(-i --ignore-errors)'{-i,--ignore-errors}'[ignore errors from recipes]'
       '*'{-I,--include-dir=}'[search specified directory for included makefiles]:search path for included makefile:->dir'
       '(-j --jobs)'{-j+,--jobs=}'[allow specified number of parallel jobs; unlimited jobs with no arg]:: : _guard "[0-9]#" "number of jobs"'
+      '--jobserver-style=[select the style of jobserver to use]:style:(fifo pipe sem)'
       '(-k --keep-going)'{-k,--keep-going}"[keep going when some targets can't be made]"
       '(-l --load-average --max-load)'{-l,--load-average=,--max-load}"[don't start multiple jobs unless load is below specified value]:load"
       '(-L --check-symlink-times)'{-L,--check-symlink-times}'[use the latest mtime between symlinks and target]'
       '(-n --just-print --dry-run --recon)'{-n,--just-print,--dry-run,--recon}"[don't actually run any recipe; just print them]"
       '*'{-o,--old-file=,--assume-old=}"[consider specified file to be old and don't remake it]:file not to remake:->file"
       '(-O --output-sync)'{-O-,--output-sync=-}'[synchronize output of parallel jobs]::granularity for grouping output:compadd -E 0 none line target recurse'
-      '(-p --print-data-base)'{-p,--print-data-base}'[print makes internal database]'
+      '(-p --print-data-base)'{-p,--print-data-base}"[print make's internal database]"
       '(-q --question)'{-q,--question}'[run no recipe; exit status says if up to date]'
       '(-r --no-builtin-rules)'{-r,--no-builtin-rules}'[disable the built-in implicit rules]'
+      '--shuffle=-[perform shuffle of prerequisites and goals]::seed (integer) or mode:(random reverse none)'
       '(-R --no-builtin-variables)'{-R,--no-builtin-variables}'[disable the built-in variable settings]'
       '(-s --silent --quiet)'{-s,--silent,--quiet}"[don't echo recipes]"
       '--no-silent[echo recipes (disable --silent mode)]'
       '(-S --no-keep-going --stop)'{-S,--no-keep-going,--stop}'[turns off -k]'
       '(-t --touch)'{-t,--touch}'[touch targets instead of remaking them]'
+      '--trace[print tracing information]'
       '(- *)'{-v,--version}'[print the version number of make and exit]'
       '(-w --print-directory)'{-w,--print-directory}'[print the current directory]'
       '--no-print-directory[turn off -w, even if it was turned on implicitly]'
       '*'{-W,--what-if=,--new-file=,--assume-new=}'[consider specified file to be infinitely new]:file to treat as modified:->file'
       '--warn-undefined-variables[warn when an undefined variable is referenced]'
-      '--warn-undefined-functions[warn when an undefined user function is called]'
     )
   else
     # Basic make options only.
@@ -185,7 +211,7 @@ _make() {
     )
   fi
 
-  _arguments -s $option_specs \
+  _arguments -C -S -s $option_specs \
     '*:make target:->target' && ret=0
 
   [[ $state = cdir ]] && cdir=-2
@@ -214,6 +240,10 @@ _make() {
     ;;
 
     (target)
+    # target name starting with '-' is allowed only after '--'
+    if [[ $words[CURRENT] = -* ]] && (( ${words[(i)--]} > CURRENT )); then
+      return ret
+    fi
     file=${(v)opt_args[(I)(-f|--file|--makefile)]}
     if [[ -n $file ]]
     then
@@ -239,7 +269,7 @@ _make() {
       if [[ $is_gnu == gnu ]] 
       then
         if zstyle -t ":completion:${curcontext}:targets" call-command; then
-          _make-parseMakefile < <(_call_program targets "$words[1]" -nsp --no-print-directory -f "$file" --always-make 2> /dev/null)
+          _make-parseDataBase < <(_call_program targets "$words[1]" -nqp --no-print-directory -f "$file" .DEFAULT 2> /dev/null)
         else
           _make-parseMakefile < $file
         fi
diff --git a/Completion/Unix/Command/_mktemp b/Completion/Unix/Command/_mktemp
index 03fc89e36..0f66d744e 100644
--- a/Completion/Unix/Command/_mktemp
+++ b/Completion/Unix/Command/_mktemp
@@ -1,43 +1,45 @@
 #compdef mktemp gmktemp
 
 local variant
-local args
+local -a args
 
-_pick_variant -r variant busybox=BusyBox gnu='Free Soft' unix --version
+_pick_variant -r variant busybox=BusyBox gnu='Free Soft' $OSTYPE --version
 
 args=(
   '(-d --directory)'{-d,--directory}'[make directory instead of file]'
-  '(: -)--help[display help information]'
-  '(-p --tmpdir)'{-p+,--tmpdir=}'[make relative to specified directory]: :_directories'
   '(-q --quiet)'{-q,--quiet}'[suppress error messages]'
-  '--suffix=[append specified suffix to template]:template suffix'
-  '-t[interpret template as single path component relative to temp dir]'
   '(-u --dry-run)'{-u,--dry-run}'[print file name only]'
-  '(: -)'{-V,--version}'[display version information]'
-  '1: :_guard "^-*" "template name"'
 )
 
-# Non-GNU variants don't support long options (except BusyBox's --help)
-if [[ $variant == *busybox* ]]; then # See also: _busybox
-  args=( ${args:#((#s)|*\))(\*|)--^help*} )
-elif [[ $variant != gnu ]]; then
-  args=( ${args:#((#s)|*\))(\*|)--*} )
-fi
-
-[[ $variant == gnu ]] || {
-  # BusyBox, OpenBSD, and Solaris have -p, but -t doesn't take an argument
-  if [[ $variant == *busybox* ]] || [[ $OSTYPE == (openbsd|solaris)* ]]; then
-    args=( ${args:#((#s)|*\))(\*|)-t*} )
-    args+=( '-t[generate template relative to temp dir]' )
-  # Dragonfly, FreeBSD, and Darwin take an argument to -t and support any number
-  # of template files. These OSes do not have -p and -V.
-  else
-    args=( ${args:#((#s)|*\))(1:*|(\*|)-[ptV]*)} )
+case $variant in
+  ^(dragonfly|darwin)*)
+    args+=( '(-p --tmpdir)'{-p+,--tmpdir=}'[make relative to specified directory]: :_directories' )
+  ;|
+  gnu)
+    args+=(
+      '--suffix=[append specified suffix to template]:template suffix'
+      '(: -)'{-V,--version}'[display version information]'
+    )
+  ;|
+  # Most variants don't support long options (except BusyBox's --help)
+  ^(gnu|freebsd*))
+    args=( ${args:#((#s)|*\))(\*|)--*} )
+  ;|
+  gnu|*busybox*)
+    args+=( '(: -)--help[display help information]' )
+  ;|
+  (gnu|*busybox|openbsd|solaris)*)
+    args+=(
+      '-t[generate template relative to temp dir]'
+      '1: :_guard "^-*" "template name"'
+    )
+  ;;
+  (dragonfly|netbsd|freebsd|darwin)*)
     args+=(
       '-t[generate template relative to temp dir using specified prefix]:template prefix'
       '*: :_guard "^-*" "template name"'
     )
-  fi
-}
+  ;;
+esac
 
 _arguments -s -S : $args
diff --git a/Completion/Unix/Command/_mosh b/Completion/Unix/Command/_mosh
index 7d1250320..6d0f746f8 100644
--- a/Completion/Unix/Command/_mosh
+++ b/Completion/Unix/Command/_mosh
@@ -7,7 +7,7 @@ _arguments -C \
   '(-)--help[display help information]' \
   '(-)--version[display version information]' \
   "--no-init[don't set terminal init string]" \
-  '--ssh=[specify ssh command to setup session]:ssh command:_normal' \
+  '--ssh=[specify ssh command to setup session]:ssh command: _cmdstring' \
   '--port=[specify server-side port range]:port:_sequence -n 2 -s \: _ports' \
   '(-a -n)--predict=[control speculative local echo]:mode:(adaptive always never)' \
   '(--predict -n)-a[synonym for --predict=always]' \
@@ -22,7 +22,7 @@ _arguments -C \
   '--local[run mosh-server locally without using ssh]' \
   '--experimental-remote-ip=[select method for discovering remote IP address to use for mosh]:method:(local remote proxy)' \
   '1:remote host name:->userhost' \
-  '*:::args:_normal' && ret=0
+  '*::: : _normal -p $service' && ret=0
 
 case $state in
   userhost)
diff --git a/Completion/Unix/Command/_mount b/Completion/Unix/Command/_mount
index 301b9e58e..bf75aa118 100644
--- a/Completion/Unix/Command/_mount
+++ b/Completion/Unix/Command/_mount
@@ -40,12 +40,13 @@ fi
 # are below these table.
 
 local curcontext="$curcontext" state line expl suf ret=1
-local args deffs=iso9660 tmp typeops=-t _nfs_access _fs_nfs _nfs_ufs \
+local deffs=iso9660 tmp typeops=-t _nfs_access _fs_nfs _nfs_ufs \
 _fs_ufs _fs_efs _fs_cd9660 _fs_iso9660 _fs_cachefs _fs_s5fs _fs_tmpfs _fs_pcfs \
 _fs_hsfs _fs_advfs _fs_cdfs _fs_affs _fs_ext2 _fs_fat _fs_ext3 _fs_msdos \
 _fs_msdosfs _fs_umsdos _fs_vfat _fs_hpfs _fs_ntfs _fs_reiserfs _fs_smbfs \
 _fs_xfs _fs_std _fs_devfs _fs_fdesc _fs_kernfs _fs_linprocfs _fs_linsysfs \
 _fs_procfs _fs_btrfs _fs_ext4
+local -a args
 
 typeset -A opt_args
 
@@ -333,9 +334,9 @@ if (( ! $+_fs_any )); then
       'keybits[set number of bits in encryption key]:key size:(64 128 160 192 256)'
       'offset[specify data start for loopback mount]:offset (bytes)'
       '(loud)silent' '(silent)loud'
-      '(fscontext defcontext)context:context'
-      '(context)'{fscontext,defcontext}':context'
-      'rootcontext:context'
+      '(fscontext defcontext)context:context:_selinux_contexts -a file_type'
+      '(context)'{fscontext,defcontext}':context:_selinux_contexts -a file_type'
+      'rootcontext:context:_selinux_contexts -a file_type'
     )
     _fs_adfs=(
       'uid[set owner of root]:user ID'
@@ -735,8 +736,11 @@ if [[ "$service" = mount ]]; then
     deffs=hsfs
     typeops=-F
     ;;
+  darwin*)
+    args=( '-k[follow no symlinks in the provided mount-on directory]' )
+    ;&
   freebsd*|dragonfly*|darwin*)
-    args=( -s
+    args=( -s $args
       '(:)-a[mount all filesystems in fstab]'
       '-d[cause everything to be done except for the actual system call]'
       '-f[forced mount]'
diff --git a/Completion/Unix/Command/_mpc b/Completion/Unix/Command/_mpc
index 7f7adc7b4..c3f93878c 100644
--- a/Completion/Unix/Command/_mpc
+++ b/Completion/Unix/Command/_mpc
@@ -26,6 +26,7 @@ _mpc_command() {
 
   mpc_cmds=(
     add:"append a song to the end of the current playlist"
+    albumart:"download album art for the given song and write to stdout"
     cdprev:"compact disk player-like previous command"
     channels:"list the channels that other clients have subscribed to"
     clear:"clear the current playlist"
@@ -57,6 +58,7 @@ _mpc_command() {
     prio:"change song priorities in the queue"
     queued:"show the next queued song"
     random:"toggle random mode, or specify state"
+    readpicture:"download a picture from the given song and write to stdout"
     repeat:"toggle repeat mode, or specify state"
     single:"toggle single mode, or specify state"
     consume:"toggle consume mode, or specify state"
@@ -205,6 +207,10 @@ _mpc_add() {
   _mpc_helper_files
 }
 
+_mpc_albumart() {
+  _mpc_helper_files
+}
+
 _mpc_del() {
   _mpc_helper_songnumbers
 }
@@ -304,8 +310,14 @@ _mpc_random() {
   _mpc_helper_bool
 }
 
+_mpc_readpicture() {
+  _mpc_helper_files
+}
+
 _mpc_single() {
-  _mpc_helper_bool
+  local state
+  _description states expl state
+  compadd "$@" "$expl[@]" on once off
 }
 
 _mpc_consume() {
diff --git a/Completion/Unix/Command/_mutt b/Completion/Unix/Command/_mutt
index 67b974a8d..82a6e5fa9 100644
--- a/Completion/Unix/Command/_mutt
+++ b/Completion/Unix/Command/_mutt
@@ -1,14 +1,15 @@
-#compdef mutt
+#compdef mutt neomutt
 
-_arguments -s -S \
+# should pass -S but that doesn't work with -- ending -a
+_arguments -s \
   '::recipient:_email_addresses -n mutt' \
   '(- :)-A[expand given alias]:alias:_email_addresses -n mutt' \
-  '*-a[attach file using MIME]::file attachment:_files' \
+  '*-a[attach file using MIME]:*--:file attachment:_files' \
   '*-b[specify a BCC recipient]:BCC recipient:_email_addresses -n mutt' \
   '*-c[specify a CC recipient]:CC recipient:_email_addresses -n mutt' \
   '(- :)-D[print the value of all variables]' \
   '(-x)-E[edit the draft (-H) or include (-i) file]' \
-  '-d+[log debugging output to ~/.muttdebug0]:level:(1 2 3 4 5)' \
+  '-d+[log debugging output to ~/.muttdebug0]:level:(-5 -4 -3 -2 -1 0 1 2 3 4 5)' \
   '-e+[specify a post-init configuration command]:post-init configuration' \
   '-f+[specify mailbox to load]:mailbox: _mailboxes' \
   '-F+[specify an init file]:init file:_files' \
diff --git a/Completion/Unix/Command/_mv b/Completion/Unix/Command/_mv
index 84e43d47e..c52e7a5e4 100644
--- a/Completion/Unix/Command/_mv
+++ b/Completion/Unix/Command/_mv
@@ -13,13 +13,17 @@ case $variant; in
         {existing,nil}"[numbered backups, if they already exist]"
         {simple,never}"[always make simple backups]"'
       '(-b --backup -n --no-clobber)-b[make a backup of each existing destination file]'
+      '(-v)--debug[explain how a file is copied]'
       '(-f --force -i --interactive -n --no-clobber)'{-f,--force}"[don't prompt before overwriting]"
       '(-f --force -i --interactive -n --no-clobber)'{-i,--interactive}'[prompt before overwriting existing file]'
+      '(-f --force -i --interactive -n --no-clobber)'{-n,--no-clobber}"[don't overwrite existing file]"
+      "--no-copy[don't copy if renaming fails]"
       '--strip-trailing-slashes[remove any trailing slashes from each source argument]'
       '(-S --suffix)'{-S+,--suffix=}'[specify the backup suffix]:backup suffix [~]'
       '(-t --target-directory)'{-t+,--target-directory=}'[move all source arguments into specified directory]:directory:_directories'
       '(-T --no-target-directory)'{-T,--no-target-directory}'[treat final argument as a normal file]'
-      '(-u --update)'{-u,--update}'[move only when destination file is older or missing]'
+      '(-u)--update=-[move only when destination file is older or missing]::update files [older]:(all none older)'
+      '(--update)-u[move only when destination file is older or missing]'
       '(-v --verbose)'{-v,--verbose}'[show file names after they are moved]'
       '(- *)--help[display usage information]'
       '(- *)--version[display version information]'
@@ -37,6 +41,7 @@ case $variant; in
   darwin*|dragonfly*|freebsd*)
     args+=(
       "(-f -i)-n[don't overwrite existing file]"
+      "-h[if target is a symlink to a directory, don't follow it]"
     )
     ;|
   darwin*|dragonfly*|*bsd*)
@@ -44,11 +49,6 @@ case $variant; in
       '-v[show file names after they are moved]'
     )
     ;|
-  dragonfly*|freebsd*)
-    args+=(
-      "-h[if target is a symlink to a directory, don't follow it]"
-    )
-    ;;
 esac
 
 _arguments -s -S $aopts $args \
diff --git a/Completion/Unix/Command/_mysql_utils b/Completion/Unix/Command/_mysql_utils
index 9f70687b0..2f5fd3efe 100644
--- a/Completion/Unix/Command/_mysql_utils
+++ b/Completion/Unix/Command/_mysql_utils
@@ -210,6 +210,7 @@ _mysql_utils() {
     "--no-defaults[don't read default options from any options file]"
     '--defaults-file=[read defaults from the given file]:file:_files'
     '--defaults-extra-file=[read specified file after the global files]:defaults file:_files'
+    '--protocol=[connection protocol to use for connecting to the server]:protocol:(tcp socket pipe memory)'
     '(-S --socket)'{-S+,--socket=}'[specify socket file to use for connection]:server socket file:_files'
     '(-h --host)'{-h+,--host=}'[specify server hostname]:hostname:_mysql_hosts'
     '(-P --port)'{-P+,--port=}'[specify port number for connection]:server port:_mysql_ports'
diff --git a/Completion/Unix/Command/_netstat b/Completion/Unix/Command/_netstat
index 67133dc6c..35d639f99 100644
--- a/Completion/Unix/Command/_netstat
+++ b/Completion/Unix/Command/_netstat
@@ -280,7 +280,6 @@ case $OSTYPE in
       '-c+[show specified number of updates, then exit]:count'
       '-e[show only the number of errors on the interface]'
       '-q[only show interfaces that have seen packets]'
-      '-t[show current value of the watchdog timer function]'
     )
     statistics+=( $popt '-r[display routing statistics]' )
     groups+=( -n$nopt )
@@ -303,6 +302,9 @@ case $OSTYPE in
     memory+=( $Xopt) statistics+=( $Xopt )
     pcb+=( $Mopts $popt )
   ;;
+  freebsd<14->.*)
+    args+=( '-j+[run inside a jail]:jail:_jails' )
+  ;&
   freebsd<13->.*)
     sockets+=(
       '-c[show TCP stack used for each session]'
diff --git a/Completion/Unix/Command/_nice b/Completion/Unix/Command/_nice
index 29070697f..b52e5216a 100644
--- a/Completion/Unix/Command/_nice
+++ b/Completion/Unix/Command/_nice
@@ -1,14 +1,23 @@
 #compdef nice
 
-shift words
-(( CURRENT-- ))
+local -a specs=( '*:: : _normal -p $service' )
 
-if [[ $CURRENT -gt 1 && $words[1] = ([-+](-|)|-n)<-> ]]; then
-    shift words
-    (( CURRENT -- ))
-elif [[ $CURRENT -gt 2 && $words[1] = -n ]]; then
-    shift 2 words
-    (( CURRENT -= 2 ))
+# See if the 1st arg is such as -10 --10 or -+10
+if [[ $words[2] = -(-|+|)[0-9]## ]]; then
+  if (( $CURRENT == 2 )); then
+    _message 'niceness increment' && return
+  fi
+  compset -n 2  # Ignore the 1st arg
+else
+  if _pick_variant gnu=GNU unix --version; then
+    specs+=(
+      '(-)'{-n+,--adjustment=}'[adjust niceness]:niceness increment'
+      '(* -)--help[display help and exit]'
+      '(* -)--version[output version information and exit]'
+    )
+  else
+    specs+=( '-n+[specify increment of niceness]:niceness increment' )
+  fi
 fi
 
-_normal
+_arguments : $specs
diff --git a/Completion/Unix/Command/_nkf b/Completion/Unix/Command/_nkf
index 0c4f06fb5..ae79e745a 100644
--- a/Completion/Unix/Command/_nkf
+++ b/Completion/Unix/Command/_nkf
@@ -10,8 +10,8 @@ _arguments -s \
   '(-u)-b[Output is buffered]' \
   '(-b)-u[Output is unbuffered]' \
   '($outputs)'{-j,--jis}'[Output is JIS 7 bit]' \
-  '($outputs)'{-e,--sjis}'[Output is Shift JIS]' \
-  '($outputs)'{-s,--euc}'[Output is EUC-JP]' \
+  '($outputs)'{-s,--sjis}'[Output is Shift JIS]' \
+  '($outputs)'{-e,--euc}'[Output is EUC-JP]' \
   '($outputs)'{-w,--utf8}'[Output is UTF-8 (No BOM)]' \
   '($outputs)-w8[Output is UTF-8 (BOM)]' \
   '($outputs)'{-w16,-w16b0,--utf16}'[Output is UTF-16 (BigEndian; No BOM)]' \
@@ -23,8 +23,8 @@ _arguments -s \
   '($outputs)--mac[Output is for Mac]' \
   '($outputs)--windows[Output is for Windows]' \
   '($inputs)-J[Input assumption is JIS 7 bit]' \
-  '($inputs)-E[Input assumption is Shift JIS]' \
-  '($inputs)-S[Input assumption is EUC-JP]' \
+  '($inputs)-S[Input assumption is Shift JIS]' \
+  '($inputs)-E[Input assumption is EUC-JP]' \
   '($inputs)-W[Input assumption is UTF-8 (No BOM)]' \
   '($inputs)-W8[Input assumption is UTF-8 (BOM)]' \
   '($inputs)-W16[Input assumption is UTF-16 (BigEndian; No BOM)]' \
diff --git a/Completion/Unix/Command/_nm b/Completion/Unix/Command/_nm
index 888f1ef87..a78eb7068 100644
--- a/Completion/Unix/Command/_nm
+++ b/Completion/Unix/Command/_nm
@@ -17,9 +17,8 @@ if _pick_variant -r variant binutils=GNU elftoolchain=elftoolchain elfutils=elfu
     '(- *)'{-V,--version}'[display version information]'
     '(-f --format -P --portability)-B[same as --format=bsd]'
     '(-u --undefined-only)--defined-only[display only defined symbols]'
-    '(-f --format -P)--format=[specify output format]:format:(bsd sysv posix)'
     '(-n --numeric-sort -p --no-sort --size-sort -v)'{-n,--numeric-sort}'[sort symbols numerically by address]'
-    '(-p --no-sort -n -v --numeric-sort -r --reverse-sort --size-sort)'{-p,--no-sort}'[do not sort symbols]'
+    '(-p --no-sort -n -v --numeric-sort -r --reverse-sort --size-sort)'{-p,--no-sort}"[don't sort symbols]"
     '(-P --portability -B -f --format)'{-P,--portability}'[same as --format=posix]'
     '(-r --reverse-sort -p --no-sort)'{-r,--reverse-sort}'[reverse sort order]'
     '(-u --undefined-only --defined-only)'{-u,--undefined-only}'[display only undefined symbols]'
@@ -41,7 +40,7 @@ if _pick_variant -r variant binutils=GNU elftoolchain=elftoolchain elfutils=elfu
       args=( ${args:#*(-C|-o|--portability)\[*}
 	'(-C --demangle)'{-C,--demangle=-}'[decode symbol names]::style:(auto gnu-v2 gnu-v3 arm)'
 	'(-g --extern-only)-e[only display global and static symbols]'
-	'(--format -P)-F+[specify output format]:format:(bsd sysv posix)'
+	'(-B --format -P)'{-F,--format}'[specify output format]:format:(bsd sysv posix)'
 	'-o[with -P, same as -t o; otherwise same as -A]'
 	'(-t --radix)-x[print values in hexadecimal]'
       )
@@ -51,7 +50,7 @@ if _pick_variant -r variant binutils=GNU elftoolchain=elftoolchain elfutils=elfu
         '--mark-special[mark special symbols]'
 	'--color=[use color in output]:color:(always auto never)'
 	'(-C)--demangle[decode symbol names]'
-	'(--format -P)-f+[specify output format]:format:(bsd sysv posix)'
+	'(-B -f --format -P --portability)'{-f,--format}'[specify output format]:format:(bsd sysv posix)'
 	'(- *)--usage[give a short usage message]'
 	'(- *)-?[display help information]'
       )
@@ -61,14 +60,19 @@ if _pick_variant -r variant binutils=GNU elftoolchain=elftoolchain elfutils=elfu
       args+=(
         '!(--no-recurse-limit)--recurse-limit'
         '--no-recurse-limit[disable demangling recursion limit]'
-	'(-f --format -P)-f+[specify output format]:format:(bsd sysv posix)'
-	'(-C --no-demangle)--demangle=-[decode symbol names]::style [auto]:(auto gnu lucid arm hp edg gnu-v3 java gnat rust dlang)'
+        '(-f --format -P -j --just-symbols)'{-f+,--format=}'[specify output format]:format [bsd]:(bsd sysv posix just-symbols)'
+        '(-C --no-demangle)--demangle=-[decode symbol names]::style [auto]:(none auto gnu-v3 java gnat dlang rust)'
         '--ifunc-chars=[specify characters to use for indirect function symbols]:characters for global/local indirect function symbols [ii]'
+        '(-B -f --format -P --portability -j --just-symbols)'{-j,--just-symbols}'[same as --format=just-symbols]'
 	'--plugin[load specified plugin]:plugin'
+	'--quiet[suppress no "no symbols" diagnostic]'
 	'--special-syms[include special symbols in the output]'
 	'--synthetic[display synthetic symbols as well]'
 	"--target=[target object format]:target:(${${(@M)${(f)$(_call_program targets nm --help)}:#*supported targets:*}##*: })"
+	'--unicode=[specify how to treat UTF-8 encoded unicode characters]:how_to_treat:(default show invalid hex escape highlight)'
+	'(-W --no-weak)'{-W,--no-weak}'[ignore weak symbols]'
 	'--with-symbol-versions[display version strings after symbol names]'
+	'--without-symbol-versions[not display of symbol version information]'
       )
     ;;
   esac
diff --git a/Completion/Unix/Command/_objdump b/Completion/Unix/Command/_objdump
index e2dde7e4c..94c01eb83 100644
--- a/Completion/Unix/Command/_objdump
+++ b/Completion/Unix/Command/_objdump
@@ -38,8 +38,10 @@ case $variant in
 
       '*-W-[display DWARF info in the file]::dwarf section:->short-dwarf-names'
       '*--dwarf=-[display DWARF info in the file]::dwarf section:->dwarf-names'
+      '(-L --process-links)'{-L,--process-links}'[display the contents of non-debug sections in separate debuginfo files]'
 
-      '--ctf=[display compact C type format info for section]:section'
+      '--ctf=-[display compact C type format info for section]::section'
+      '--sframe=-[display SFrame info from section]::section name [.sframe]'
       '(-t --syms)'{-t,--syms}'[display the contents of the symbol table(s)]'
       '(-T --dynamic-syms)'{-T,--dynamic-syms}'[display the contents of the dynamic symbol table]'
       '(-R --dynamic-reloc)'{-R,--dynamic-reloc}'[display the dynamic relocation entries in the file]'
@@ -59,11 +61,13 @@ case $variant in
       \*{-I+,--include=}'[add directory to search list for source files]:directory:_files -/'
       '(-l --line-numbers)'{-l,--line-numbers}'[include line numbers and filenames in output]'
       '(-F --file-offsets)'{-F,--file-offsets}'[include file offsets when displaying information]'
-      '(-C --demangle)-C[decode mangled/processed symbol names]'
-      '(-C --demangle)--demangle=-[decode mangled/processed symbol names]::style:(auto gnu lucid arm hp edg gnu-v3 java gnat rust dlang)'
+      '(--demangle)-C[decode symbol names]'
+      '(-C)--demangle=-[decode symbol names]::style [auto]:(none auto gnu-v3 java gnat dlang rust)'
       '!(--no-recurse-limit)--recurse-limit'
       '--no-recurse-limit[disable demangling recursion limit]'
       '(-w --wide)'{-w,--wide}'[format output for more than 80 columns]'
+      '-U+[specify how to display unicode characters]:method:(d l e x h i)'
+      '--unicode=[specify how to display unicode characters]:method:(default locale escape hex highlight invalid)'
       '(-z --disassemble-zeroes)'{-z,--disassemble-zeroes}"[don't skip blocks of zeroes when disassembling]"
 
       '--start-address=[only process data whose address is >= ADDR]:address'
@@ -73,15 +77,17 @@ case $variant in
       '(--show-raw-insn --no-show-raw-insn)'--{,no-}show-raw-insn'[display hex alongside symbolic disassembly]'
       '--insn-width=[display specified number of bytes on a single line with -d]:width (bytes)'
       '--adjust-vma=[add offset to all displayed section addresses]:offset'
+      '--show-all-symbols[when disassembling, display all symbols at a given address]'
       '--special-syms[include special symbols in symbol dumps]'
       '--inlines[print all inlines for source line (with -l)]'
       '--prefix=[add prefix to absolute paths for -S]:prefix'
       '--prefix-strip=[strip initial directory names for -S]:level'
       "--dwarf-depth=[don't display DIEs at specified or greater depth]:depth"
       '--dwarf-start=[display DIEs at specified or deeper depth]:depth'
-      '--dwarf-check[perform additional dwarf internal consistency checks]'
+      '--dwarf-check[perform additional dwarf consistency checks]'
       '--ctf-parent=[use specified section as the CTF parent]:section'
       '--visualize-jumps=-[visualize jumps by drawing ASCII art lines]::color:(color extended-color off)'
+      '--disassembler-color=[control use of colored syntax highlighting in disassembly output]:color use [on]:(off terminal on extended)'
     )
   ;;
   elfutils)
diff --git a/Completion/Unix/Command/_openldap b/Completion/Unix/Command/_openldap
new file mode 100644
index 000000000..233d0950e
--- /dev/null
+++ b/Completion/Unix/Command/_openldap
@@ -0,0 +1,222 @@
+#compdef ldapadd ldapcompare ldapdelete ldapexop ldapmodify ldapmodrdn ldappasswd ldapsearch ldapurl ldapwhoami
+
+local curcontext="$curcontext" nm="$compstate[nmatches]"
+local -a args auth state line expl
+
+args=( '*-e[general extensions]:extension:->general-extensions' )
+
+case $service in
+  ldapadd|ldapcompare|ldapdelete|ldapexop|ldapmodify|ldapmodrdn|ldappasswd|ldapsearch|ldapwhoami)
+    if (( $words[(I)-[^Z]#Z[^Z]#] )); then
+      args+=( '*-Z[require success for start TLS request]' )
+    elif (( ! $words[(I)-[^Z]#Z] )); then
+      args+=( '-Z[start TLS request]' )
+    fi
+    args+=(
+      '!(-)-VV' '-V[display version information]'
+      '*-d+[set LDAP debugging level]:level:((1\:trace 2\:packets 4\:args 8\:conns 10\:ber 2048\:parse -1\:all))'
+      "-n[show what would be done but don't actually do it]"
+      '-v[verbose output]'
+      "-N[don't use reverse DNS to canonicalize SASL host name]"
+      '*-o+[specify any ldap.conf options]: : _values option
+        "ldif_wrap[specify width]\:width"
+        "nettimeout[specify timeout]\:timeout (seconds)"'
+    )
+    auth=(
+      '-D[specify bind DN]:binddn'
+      '-H[specify LDAP URIs]:uri'
+      '-P[specify protocol version]:version [3]:(2 3)'
+      + simple
+      '(sasl)-x[use simple authentication]'
+      '(sasl -W -y)-w+[specify bind password]:bind password'
+      '(sasl -w -y)-W[prompt for bind password]'
+      '(sasl -w -W)-y+[read password from file]:file:_files'
+      + sasl
+      '(simple)-O+[specify SASL security properties]: : _values -s , property
+          none noplain noactive nodict noanonymous forwardsec passcred
+          minssf\:factor maxssf\:factor maxbufsize\:factor'
+      '(simple)-X+[specify SASL authorization identity]:authzid:->authzids'
+      '(simple)-Y+[specify SASL mechanism]:mechanism:compadd -M "m:{a-zA-Z}={A-Za-z}" EXTERNAL GSSAPI' # iana has a full list but cyrus support seems limited
+      '(simple)-R+[specify SASL realm]:realm'
+      '(simple)-U+[specify SASL authentication identity]:authcid'
+      '(simple)-I[use SASL Interactive mode]'
+      '(simple)-Q[use SASL Quiet mode]'
+    )
+  ;|
+  ldapadd|ldapcompare|ldapdelete|ldapmodify|ldapmodrdn|ldapsearch)
+    if (( $words[(I)-[^M]#M[^M]#] )); then
+      args+=( '*-M[enable Manage DSA IT control critical]' )
+    elif (( ! $words[(I)-[^M]#M] )); then
+      args+=( '-M[enable Manage DSA IT control]' )
+    fi
+  ;|
+  ldapadd|ldapdelete|ldapmodify|ldapmodrdn|ldapsearch)
+    # ldapexop documents but doesn't implement this
+    args+=( '(1 2 *)-f+[read operations from file]:file:_files' )
+  ;|
+  ldapadd|ldapdelete|ldapmodify|ldapmodrdn|ldapsearch)
+    args+=( "-c[continuous operation mode (don't stop on errors)]" )
+  ;|
+  ldapdelete|ldapsearch)
+    args+=( '-z+[specify size limit]:size limit (entries)' )
+  ;|
+  ldapadd|ldapmodify)
+    args+=(
+      '-S+[write records that are skipped due to an error to file]:file:_files'
+      '*-E+[modify extensions]:extension:->modify-extensions'
+    )
+  ;|
+  ldapurl|ldapsearch)
+    args+=(
+      '(decompose)-s+[specify search scope]:search scope [sub]:(base one sub children)'
+    )
+  ;|
+  ldapdelete|ldapmodrdn|ldapurl|ldapwhoami) args+=( '!*-E+:extension' ) ;|
+
+  ldapadd) args+=( '!-a' ) ;;
+  ldapmodify) args+=( '-a[add new entries]' ) ;;
+  ldapcompare)
+    args+=(
+      '-z[quiet mode - no output aside return status]'
+      '*-E+[compare extensions]:extension:->compare-extensions'
+    )
+  ;;
+  ldapdelete)
+    args+=(
+      '-r[do a recursive delete]'
+      '*: :_guard "^-*" "distinguished name"'
+    )
+  ;;
+  ldapexop) args+=( '*:: :->extended-operations' ) ;;
+  ldapmodrdn)
+    args+=(
+      '-r[remove old RDN values from the entry]'
+      '-s[specify new superior entry to move target to]:entry'
+      '1:distinguished name'
+      '2:relative distinguished name'
+    )
+  ;;
+  ldappasswd)
+    args+=(
+      '(-a -t)-A[prompt for old password]'
+      '(-A -t)-a+[specify old password]:password'
+      '(-A -a)-t+[read old password from file]:file:_files'
+      '(-s -T)-S[prompt for new password]'
+      '(-S -T)-s+[specify new password]:password'
+      '(-S -s)-T+[read new password from file]:file:_files'
+    )
+  ;;
+  ldapsearch)
+    if (( $words[(I)-[^L]#L[^L]#L[^L]#] )); then
+      args+=( '*-L[LDIF format without comments and version]' )
+    elif (( $words[(I)-[^L]#L[^L]#] )); then
+      args+=( '*-L[LDIF format without comments]' )
+    elif ! (( $words[(I)-[^L]#L[^L]#L[^L]#L] )); then
+      args+=( '-L[LDIFv1 format]' )
+    else
+      args+=( '!*-L' )
+    fi
+    if (( $words[(I)-[^t]#t[^t]#] )); then
+      args+=( '*-t[write all retrieved values to files in temporary directory]' )
+    elif (( ! $words[(I)-[^t]#t] )); then
+      args+=( '-t[write binary values to files in temporary directory]' )
+    fi
+
+    args+=(
+      '-a+[specify how aliases dereferencing is done]:deref [never]:(never always search find)'
+      '-A[retrieve attributes only (no values)]'
+      '-b+[specify base dn for search]:basedn'
+      '*-E+[search extensions]:extension:->search-extensions'
+      '-F+[specify URL prefix for temporary files]:prefix [file:///tmp//]'
+      '-l+[specify time limit for search]:time limit (seconds)'
+      '-S+[sort results by specified attribute]:attribute:_ldap_attributes'
+      '-T[write files to specified directory]:path [/tmp]:_directories'
+      '-u[include User Friendly entry names in the output]'
+      '1: :_ldap_filters'
+      '2: : _alternative
+        "attributes:attribute:_ldap_attributes"
+        "attributes:attribute:((1.1\:no\ attributes \*\:all\ user\ attributes \+\:all\ operational\ attributes))"'
+      '*:attribute:_ldap_attributes -F line'
+    )
+  ;;
+  ldapurl)
+    args+=(
+      - compose
+      '-a+[set a list of attribute selectors]:attribute selectors (comma separated)'
+      '-b+[set the searchbase]:search base'
+      '-f+[set the URL filter]:filter:_ldap_filters'
+      '-h+[set the host]:host:_hosts'
+      '-p+[set the tcp port]:port:(389 636)'
+      '-S+[set the URL scheme]:scheme:(ldap ldaps)'
+      - decompose
+      '(-s)-H+[specify URI to be exploded]:uri'
+    )
+  ;;
+esac
+
+_arguments -C -S -s $args $auth
+
+case $state in
+  extended-operations)
+    case $CURRENT:$words[1] in
+      1:*)
+        if compset -P '*::'; then
+          _message -e data 'base64 data'
+        elif compset -P '*:'; then
+          _message -e data data
+        else
+          _alternative \
+            'oids::_guard "(<->(|.))#" oid' \
+            'operations:operation:(whoami cancel refresh)'
+        fi
+      ;;
+      2:cancel) _message -e ids 'cancel id' ;;
+      2:refresh) _message -e names 'distinguished name' ;;
+      3:refresh) _message -e times 'ttl' ;;
+      *) _message 'no more arguments' ;;
+    esac
+  ;;
+  *-extensions)
+    if ! compset -P \!; then
+      _description criticality expl critical
+      compadd -S "" "$expl[@]" \!
+    fi
+  ;|
+  modify-extensions) _values extension 'txn:txn:(abort commit)' ;;
+  compare-extensions) _values extension dontUseCopy ;;
+  search-extensions)
+    _values extension \
+      'mv[matched values filter]:filter:_ldap_filters' \
+      'pr[paged results/prompt]:size[/prompt|noprompt]' \
+      'sss[server side sorting]: :_sequence -s / _ldap_attributes' \
+      'subentries: :(true false)' \
+      'sync:sync[/cookie][/slimit]:((ro\:refreshOnly rp\:refreshAndPersist))' \
+      'vlv[virtual list view]:before/after(/offset/count|\:value' \
+      'deref:derefAttr:_sequence _ldap_attributes' \
+      dontUseCopy domainScope
+  ;;
+  general-extensions)
+    _values extension \
+      'assert:filter:_ldap_filters' \
+      'authzid:authzid:->authzids' \
+      {post,pre}'read: :_sequence _ldap_attributes' \
+      'sessiontracking:username:_users' \
+      'chaining:behavior:(chainingPreferred chainingRequired referralsPreferred referralsRequired)' \
+      bauthzid manageDSAit noop ppolicy relax abandon cancel ignore
+  ;&
+  authzids)
+    if [[ $state != authzids ]]; then
+      : # fall-through from above without the authzids state
+    elif compset -P 'u:'; then
+      _description users expl authzid
+      _users "$expl[@]"
+    elif compset -P 'dn:'; then
+      _message -e ids 'distinguished name'
+    else
+      _description prefixes expl prefix
+      compadd -S: "$expl[@]" u dn
+    fi
+  ;;
+esac
+
+[[ nm -ne "$compstate[nmatches]" ]]
diff --git a/Completion/Unix/Command/_pandoc b/Completion/Unix/Command/_pandoc
index b0fff80d6..797e73eaa 100644
--- a/Completion/Unix/Command/_pandoc
+++ b/Completion/Unix/Command/_pandoc
@@ -113,7 +113,7 @@ _pandoc_defaults_file() {
 
 # choose reference location
 (( $+functions[_pandoc_reference_location] )) ||
-_pandoc_reference_location(){
+_pandoc_reference_location() {
   local -a policies
   policies=(
     'block:place references at the end of the current (top-level) block'
@@ -123,22 +123,16 @@ _pandoc_reference_location(){
   _describe 'location' policies
 }
 
-# choose top level division
-(( $+functions[_pandoc_top_level_division] )) ||
-_pandoc_top_level_division(){
-  _values 'top level division' default section chapter part
-}
-
 # choose email obfusication
 (( $+functions[_pandoc_email_obfusication] )) ||
 _pandoc_email_obfusication(){
   local -a policies
   policies=(
-    'none:leave mailto: links as they are'
-    'javascript:obfuscates them using JavaScript'
-    'references:obfuscates them by printing their letters as decimal or hexadecimal character references'
+    'none:leave mailto: links as-is'
+    'javascript:obfuscate using JavaScript'
+    'references:obfuscate by printing letters as decimal or hexadecimal character references'
   )
-  _describe 'obfuscation policy [none]' policies
+  _describe 'e-mail obfuscation policy [none]' policies
 }
 
 # choose wrapping policy
@@ -181,26 +175,26 @@ _pandoc_track_changes() {
 _arguments -s \
   {-f+,-r+,--from=,--read=}'[specify input format]: :_pandoc_format -T input' \
   {-t+,-w+,--to=,--write=}'[specify output format]: :_pandoc_format -T output' \
-  {-o+,--output=}'[write output to FILE instead of stdout]:file:_files' \
+  {-o+,--output=}'[write output to specified file instead of stdout]:file:_files' \
   '--data-dir=[specify the user data directory to search for pandoc data files]:data directory:_files -/' \
   {-d+,--defaults=}'[read default from YAML file]: :_pandoc_defaults_file' \
   '--shift-heading-level-by=[shift heading levels by specified number]:positive or negative integer: ' \
   '!--base-header-level=:number [1]:(1 2 3 4 5)' \
-  '!--strip-empty-paragraphs[deprecated. Use the +empty_paragraphs extension instead]' \
-  '--indented-code-classes=[classes to use for indented code blocks]:class list (comma-separated)' \
+  '--indented-code-classes=[specify classes to use for indented code blocks]:class list (comma-separated)' \
   '--default-image-extension=[specify a default extension to use when image paths/URLs have no extension]:extension: ' \
   '--file-scope[parse each file individually before combining for multifile documents]' \
+  '--sandbox=-[run in a sandbox, limiting IO operations]::enable:(true false)' \
   {\*-F+,\*--filter=}'[specify an executable to be used as a filter transforming the pandoc AST after the input is parsed and before the output is written]: :_pandoc_filter' \
   {\*-L+,\*--lua-filter=}"[transform the document by using pandoc's built-in lua filtering system]: :_pandoc_lua_filter" \
   {\*-M+,\*--metadata=}'[set the metadata field KEY to the value VALUE]:key\:value: ' \
   '*--metadata-file=[read metadata from file]:YAML or JSON file:_files' \
   {-p,--preserve-tabs}'[preserve tabs instead of converting them to spaces]' \
   '--tab-stop=[specify the number of spaces per tab]:spaces [4]' \
-  '--track-changes=[specifies what to do with insertions, deletions, and comments produced by the MS Word "Track Changes" feature]: :_pandoc_track_changes' \
+  '--track-changes=[specify what to do with insertions, deletions, and comments produced by the MS Word "Track Changes" feature]: :_pandoc_track_changes' \
   '--extract-media=[extract media in source document to specified directory]:directory:_files -/' \
-  '--abbreviations=[specifies a custom abbreviations file]:file:_files ' \
+  '--abbreviations=[specify a custom abbreviations file]:file:_files ' \
   {-s,--standalone}'[produce output with an appropriate header and footer]' \
-  '--template=[use FILE as a custom template for the generated document. Implies --standalone]: :_pandoc_template' \
+  '--template=[use specified file as a custom template for the generated document. Implies --standalone]: :_pandoc_template' \
   {\*-V+,\*--variable=}'[set the variable KEY to the value VALUE]:key\:value: ' \
   '(- :)'{-D+,--print-default-template=}'[print the system default template for an output]:format:( $(pandoc --list-output-formats) )' \
   '(- :)--print-default-data-file=[print a system default data file]:file: ' \
@@ -211,43 +205,48 @@ _arguments -s \
   {--toc,--table-of-contents}'[include an automatically generated table of contents]' \
   '--toc-depth=[specify the number of section levels to include in the table of contents]:number' \
   '--strip-comments[strip out HTML comments in the Markdown or Textile source]' \
-  '--no-highlight[disables syntax highlighting for code blocks and inlines]' \
-  '--highlight-style=[specifies the coloring style to be used in highlighted source code]:style|file:_pandoc_highlight_style' \
+  '--no-highlight[disable syntax highlighting for code blocks and inlines]' \
+  '--highlight-style=[specify coloring style to be used in highlighted source code]: :_pandoc_highlight_style' \
   '(- :)--print-highlight-style=[prints a JSON version of a highlighting style]: :_pandoc_highlight_style' \
   '--syntax-definition=[load a KDE XML syntax definition file]:file:_files -g "*.xml(-.)"' \
-  {\*-H+,\*--include-in-header=}'[include contents of FILE, verbatim, at the end of the header, implies --standalone]:file:_files' \
-  {\*-B+,\*--include-before-body=}'[include contents of FILE, verbatim, at the beginning of the document body, implies --standalone]:file:_files' \
-  {\*-A+,\*--include-end-body=}'[include contents of FILE, verbatim, at the end of the document body, implies --standalone]:file:_files' \
+  \*{-H+,--include-in-header=}'[include contents of file, verbatim, at the end of the header, implies --standalone]:file:_files' \
+  \*{-B+,--include-before-body=}'[include contents of file, verbatim, at the beginning of the document body, implies --standalone]:file:_files' \
+  \*{-A+,--include-end-body=}'[include contents of file, verbatim, at the end of the document body, implies --standalone]:file:_files' \
   '--resource-path=[list of paths to search for images and other resources]:searchpath:_dir_list' \
   '--request-header=[set the request header NAME to the value VAL when making HTTP requests]:name\:val: ' \
   '--no-check-certificate[disable the certificate verification]' \
   '--self-contained[produce a standalone HTML file with no external dependencies, using data: URIs to incorporate the contents of linked scripts, stylesheets, images, and videos. Implies --standalone]' \
+  '--embed-resources=-[produce a standalone HTML document with no external dependencies]::enable:(true false)' \
   '--html-q-tags[use <q> tags for quotes in HTML]' \
   '--ascii[use only ASCII characters in output, supported only for HTML and DocBook output]' \
   '--reference-links[use reference-style links, rather than inline links]' \
   '--reference-location=[specify where footnotes (and references, if reference-links is set) are placed (block|section|document)]: :_pandoc_reference_location' \
   '--markdown-headings[specify style for level1 and 2 headings in markdown output]:style [atx]:(setext atx)' \
-  '!--atx-headers[use ATX-style headers in Markdown and AsciiDoc output]' \
-  '--top-level-division=[treat top-level headers as the given division type in LaTeX, ConTeXt, DocBook, and TEI output]: :_pandoc_top_level_division' \
+  '--list-tables=-[render tables as list tables in RST output]::enable(true false)' \
+  '--top-level-division=[treat top-level headers as given division type in LaTeX, ConTeXt, DocBook and TEI output]:top level division:(default section chapter part)' \
   {-N,--number-sections}'[number section headings in LaTeX, ConTeXt, HTML, or EPUB output]' \
-  '--number-offset=[offset for section headings in HTML output (ignored in other output formats)]:number[number,...] [0]' \
+  '--number-offset=[specify offset for section headings in HTML output (ignored in other output formats)]:number[number,...] [0]' \
   '--listings[use the listings package for LaTeX code blocks]' \
   {-i,--incremental}'[make list items in slide shows display incrementally (one by one)]' \
-  '--slide-level=[specifies that headers with the specified level create slides (for beamer, s5, slidy, slideous, dzslides)]:slide level:(1 2 3 4 5 6)' \
-  '--section-divs[wrap sections in <section> tags (or <div> tags for html4)Use the section-divs package for LaTeX code blocks]' \
-  '--email-obfusication=[treat top-level headers as the given division type in LaTeX, ConTeXt, DocBook, and TEI output (none|javascript|references)]: :_pandoc_email_obfusication' \
+  '--slide-level=[divide into slides for headers above the specified level (for beamer, s5, slidy, slideous, dzslides)]: :_pandoc_header_levels' \
+  '--section-divs[wrap sections in <section> tags (or <div> tags for html4)]' \
+  '--email-obfusication=[specify method for obfusicating mailto: links in HTML documents]: :_pandoc_email_obfusication' \
   '--id-prefix=[specify a prefix to be added to all identifiers and internal links in HTML and DocBook output]:string: ' \
   {-T+,--title-prefix=}'[specify STRING as a prefix at the beginning of the title that appears in the HTML header]:string: ' \
   {\*-c+,\*--css=}'[link to a CSS style sheet]: :_urls' \
-  '--reference-doc=[use the specified file as a style reference in producing a docx or ODT file]:file: ' \
+  '--reference-doc=[use specified file as a style reference in producing a docx or ODT file]:file:_files' \
   '--epub-subdirectory=[specify the subdirectory in the OCF container that is to hold the EPUB-specific contents]:directory:_files -/' \
   '--epub-cover-image=[use the specified image as the EPUB cover]:file:_files' \
+  '--epub-title-page=-[determine whether title page is included in EPUB]::enable [true]:(true false)' \
   '--epub-metadata=[look in the specified XML file for metadata for the EPUB]:file:_files -g "*.xml(-.)"' \
   '*--epub-embed-font=[embed the specified font in the EPUB]:file:_files ' \
+  '--split-level=[specify heading level at which to split an EPUB or chunked HTML into separate files]:heading level' \
+  '--chunk-template=[specify filename template for a chunked html document]:template' \
   '--epub-chapter-level=[specify the header level at which to split the EPUB into separate "chapter" files]:number:(1 2 3 4 5 6)' \
   '--ipynb-output=[specify how to tread ipynb output cells]:method:(all none best)' \
-  '--pdf-engine=[use the specified engine when producing PDF output]:program:_pandoc_pdf_engine' \
-  '*--pdf-engine-opt=[use the given string as a command-line argument to the pdf-engine]:string:_pandoc_pdf_engine_opts' \
+  '--pdf-engine=[use specified engine when producing PDF output]:program:_pandoc_pdf_engine' \
+  '*--pdf-engine-opt=[use given string as a command-line argument to the pdf-engine]:string:_pandoc_pdf_engine_opts' \
+  '(-C --citeproc)'{-C,--citeproc}'[process citations]' \
   "*--bibliography=[set the bibliography field in the document's metadata to specified file]:file:_files -g '*.(bib|bibtex|copac|json|yaml|enl|xml|wos|medline|mods|ris)(-.)'" \
   "--csl=[set the csl field in the document's metadata to specified file]:file:_files -g '*.csl(-.)'" \
   '--citation-abbreviations=[set the citation-abbreviations field in the document'"'"'s metadata to FILE]:file:_files' \
@@ -257,10 +256,10 @@ _arguments -s \
   '--webtex=[convert TeX formulas to <img> tags that link to an external script that converts formulas to images]:: :_urls' \
   '--mathjax=[use MathJax to display embedded TeX math in HTML output]:: :_urls' \
   '--katex=[use KaTeX to display embedded TeX math in HTML output]:: :_urls' \
-  '--gladtex[Enclose TeX math in <eq> tags in HTML output]' \
+  '--gladtex[enclose TeX math in <eq> tags in HTML output]' \
   '--trace[enable tracing]' \
-  '--dump-args[print information about command-line arguments to stdout, then exit]' \
-  '--ignore-args[ignore command-line arguments (for use in wrapper scripts)]' \
+  '!--dump-args' \
+  '!--ignore-args' \
   '--verbose[give verbose debugging output]' \
   '--quiet[suppress warning messages]' \
   '--fail-if-warnings[exit with error status if there are any warnings]' \
@@ -271,6 +270,7 @@ _arguments -s \
   '(- :)--list-extensions=[list supported extensions, one per line, preceded by a + or - indicating whether it is enabled by default in FORMAT]:format:_pandoc_all_formats' \
   '(- :)--list-highlight-languages[list supported languages for syntax highlighting, one per line]' \
   '(- :)--list-highlight-styles[list supported styles for syntax highlighting, one per line]' \
+  '(- :)--print-highlight-style=[print JSON version of a highlighting style]: :_pandoc_highlight_style' \
   '(- :)'{-v,--version}'[print version]' \
   '(- :)'{-h,--help}'[print help]' \
   '*:file:_files'
diff --git a/Completion/Unix/Command/_perl b/Completion/Unix/Command/_perl
index d7e8f1b51..1631560ce 100644
--- a/Completion/Unix/Command/_perl
+++ b/Completion/Unix/Command/_perl
@@ -17,6 +17,7 @@ _perl () {
     '(1 -e)*-E+[like -e but enable all optional features]:one line of program' \
     '-f[disable executing $Config{sitelib}/sitecustomize.pl at startup]' \
     '-F-[split() pattern for autosplit (-a)]:split() pattern, // is optional' \
+    '-g[read all input in one go (slurp), rather than line-by-line (alias for -0777)]' \
     '-h[list help summary]' \
     '-i-[edit <> files in place (make backup if extension supplied)]:backup file extension: ' \
     '*-I-[specify @INC/#include directory (may be used more than once)]:include path:_files -/' \
diff --git a/Completion/Unix/Command/_perlbrew b/Completion/Unix/Command/_perlbrew
new file mode 100644
index 000000000..8bf9ba7cc
--- /dev/null
+++ b/Completion/Unix/Command/_perlbrew
@@ -0,0 +1,315 @@
+#compdef perlbrew
+
+#
+# A zsh completion script for perlbrew (https://metacpan.org/dist/App-perlbrew/)
+#
+
+local curcontext="$curcontext" state state_descr line ret=1
+local -a args_common args_install
+typeset -A opt_args
+# others local variables
+typeset -g perlbrew_subcommands
+
+##
+## get the list of perl available versions
+##
+(( $+functions[_perlbrew_caching_policy] )) ||
+_perlbrew_caching_policy() {
+  # rebuild if cached data are more than one week old
+  local -a newer=( "$1"(Nmw-1) )
+  return $#newer
+}
+
+(( $+functions[_perl_available] )) ||
+_perl_available() {
+  local -a available_versions
+  local update_policy
+
+  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
+  if [[ -z "$update_policy" ]]; then
+    zstyle ":completion:${curcontext}:" cache-policy _perlbrew_caching_policy
+  fi
+
+  if _cache_invalid perlbrew-available-versions || ! _retrieve_cache perlbrew-available-versions; then
+    # this can be slow
+    available_versions=( ${${${${(f)"$(_call_program perl_releases perlbrew available)"}/\# (cp|p)erl/}/(#s)i /}// /} \
+                         perl-stable \
+                         perl-blead )
+    _store_cache perlbrew-available-versions available_versions
+  fi
+  _values 'available version' ${(n)available_versions}
+}
+
+##
+## get the list of local perl installations
+##
+(( $+functions[_perl_installations] )) ||
+_perl_installations() {
+  local text
+  local -a installed alias_link
+
+  case "$1" in
+    (-with-lib)
+      installed=( ${${${(f)"$(_call_program perl_installed perlbrew list)"}/(#s)\*/}// /} )
+      text="perl installation"
+      ;;
+    (-only-lib)
+      installed=( ${(M)${${${(f)"$(_call_program perl_installed perlbrew list)"}/(#s)\*/}// /}:#*@*} )
+      text="perl installation"
+      ;;
+    (-without-lib)
+      installed=( ${${${${(f)"$(_call_program perl_installed perlbrew list)"}/(#s)\*/}// /}:#*@*} )
+      text="perl installation"
+      ;;
+    (-alias)
+      if [[ -n "$PERLBREW_ROOT" ]]; then
+        if [[ -d "$PERLBREW_ROOT/perls" ]]; then
+          alias_link=( $PERLBREW_ROOT/perls/*(@) )
+        fi
+      fi
+      installed=( ${(q)${alias_link:t}[@]} )
+      text="alias"
+      ;;
+  esac
+
+  if [[ ${#installed[@]} -eq 0 ]]; then
+    _message 'no local perl installation found'
+  else
+    case "$2" in
+      (-comma-separated)
+        _values -s , "$text" $installed
+        ;;
+      (*)
+        _values "$text" $installed
+        ;;
+    esac
+  fi
+}
+
+##
+## completion for the alias subcommand
+##
+(( $+functions[_perlbrew_alias] )) ||
+_perlbrew_alias() {
+  local line state ret=1
+
+  _arguments -C \
+    -f'[force]' \
+    "1: :->actions" \
+    "*::arg:->args" && ret 0
+
+  case "$state" in
+    (actions)
+      local -a alias_actions
+      alias_actions=(
+        "create:create an alias for the installation named <name>"
+        "rename:rename the alias to a new name"
+        "delete:delete the given alias"
+      )
+      _describe -t commands 'alias action' alias_actions && ret=0
+      ;;
+    (args)
+      case $line[1] in
+        (create)
+          _arguments \
+            '1:perl installation: _perl_installations -without-lib' \
+            '2: : _message "alias name"' && ret=0
+          ;;
+        (rename)
+          _arguments \
+            '1:perl installation: _perl_installations -alias' \
+            '2: : _message "new name"' && ret=0
+          ;;
+        (delete)
+          _arguments \
+            ':perl installation: _perl_installations -alias' && ret=0
+          ;;
+      esac
+      ;;
+  esac
+}
+
+##
+## completion for the lib subcommand
+##
+(( $+functions[_perlbrew_lib] )) ||
+_perlbrew_lib() {
+  local line state ret=1
+
+  _arguments -C \
+    "1: :->actions" \
+    "*::arg:->args" && ret=0
+
+  case "$state" in
+    (actions)
+      local -a lib_actions
+      lib_actions=(
+        "list:list existing local libs"
+        "create:create a local lib"
+        "delete:delete a local lib"
+      )
+      _describe -t commands 'lib action' lib_actions && ret=0
+      ;;
+    (args)
+      case $line[1] in
+        (list)
+          _nothing && ret=0
+          ;;
+        (create)
+          _message 'lib name' && ret=0
+          ;;
+        (delete)
+          _arguments \
+            ':perl installation: _perl_installations -only-lib' && ret=0
+          ;;
+      esac
+      ;;
+  esac
+}
+
+##
+## main completion script
+##
+
+args_common=(
+  '(-q --quiet)'{-q,--quiet}'[be quiet on informative output message]' \
+  '(-v --verbose)'{-v,--verbose}'[tell me more about it]' \
+  ':perlbrew command:->subcommands' \
+  '*::: := ->option-or-argument'
+)
+
+args_install=(
+  '(-f --force)'{-f,--force}'[force installation]' \
+  -j"[number of building jobs run in parallel]::number" \
+  '(-n --notest)'{-n,--notest}'[skip testing]' \
+  --switch"[automatically switch to this perl version once installed]" \
+  --as"[install the given version of perl by a name]:alias name" \
+  --noman"[skip installation of manpages]" \
+  --thread"[build perl with usethreads enabled]" \
+  --multi"[build perl with usemultiplicity enabled]" \
+  --64int"[build perl with use64bitint enabled]" \
+  --64all"[build perl with use64bitall enabled]" \
+  --ld"[build perl with uselongdouble enabled]" \
+  --debug"[build perl with DEBUGGING enabled]" \
+  --clang"[build perl using the clang compiler]" \
+  --no-patchperl"[skip calling patchperl]" \
+  {-D,-U,-A}"[switches passed to perl Configure script]:value:" \
+  --destdir"[install perl as per 'make install DESTDIR=\$path']: :_files -/" \
+  --sitecustomize"[specify a file to be installed as sitecustomize.pl]: :_files" \
+  --mirror"[specify a CPAN-mirror url]:URL:_urls"
+)
+
+_arguments -C $args_common && ret=0
+
+case $state in
+  (subcommands)
+
+    perlbrew_subcommands=(
+      "init:initialize perlbrew environment"
+      "info:show useful information about the perlbrew installation"
+      "install:install perl"
+      "uninstall:uninstall the given installation"
+      "available:list perls available to install"
+      "lib:manage local::lib directories"
+      "alias:give perl installations a new name"
+      "upgrade-perl:upgrade the current perl"
+      "list:list perl installations"
+      "use:use the specified perl in current shell"
+      "off:turn off perlbrew in current shell"
+      "switch:permanently use the specified perl as default"
+      "switch-off:permanently turn off perlbrew (revert to system perl)"
+      "exec:exec programs with specified perl environments"
+      "clone-modules:re-installs all CPAN modules from one installation to another"
+      "self-install:install perlbrew itself under PERLBREW_ROOT/bin"
+      "self-upgrade:upgrade perlbrew itself"
+      "install-patchperl:install patchperl"
+      "install-cpanm:install cpanm, a friendly companion"
+      "install-cpm:install cpm, a faster but still friendly companion"
+      "install-multiple:install multiple versions and flavors of perl"
+      "download:download the specified perl distribution tarball"
+      "clean:purge tarballs and build directories"
+      "version:display version"
+      "help:read more detailed instructions"
+    )
+
+    _describe -t commands 'perlbrew command' perlbrew_subcommands && ret=0
+
+    ;;
+  (option-or-argument)
+    curcontext=${curcontext%:*}-$line[1]:
+    case $line[1] in
+      (info)
+        _message 'perl module name' && ret=0
+        ;;
+      (install)
+        _arguments \
+           $args_install \
+           '1:perl release: _perl_available' && ret=0
+        ;;
+      (install-multiple)
+        _arguments \
+           $args_install \
+           '*'--both"[perl flavor]: :(thread multi ld 64int 64all debug clang )" \
+           --common-variations"[equivalent to '--both thread --both ld --both 64int']" \
+           --all-variations"[generates all the possible flavor combinations]" \
+           --append"[appends the given string to the generated names]:string" \
+           '*:perl release: _perl_available' && ret=0
+        ;;
+      (uninstall)
+        _arguments \
+          ":perl installation: _perl_installations -without-lib" && ret=0
+        ;;
+      (use|switch)
+        _arguments \
+          ':perl installation: _perl_installations -with-lib' && ret=0
+        ;;
+      (available)
+        _arguments \
+          '--all[list of all perls ever released, including development and RC versions]' \
+          '*: :' && ret=0
+        ;;
+      (alias)
+        _perlbrew_alias && ret=0
+        ;;
+      (exec)
+        _arguments -C \
+          --with'[specify one or more perl installations to use]: : _perl_installations -without-lib -comma-separated' \
+          --min'[minimum perl version]:version number (n.nnnnn):' \
+          --max'[maximum perl version]:version number (n.nnnnn):' \
+          --halt-on-error'[stop on first nonzero exit status]' \
+          "1:command:" \
+          "*:args:" && ret=0
+        ;;
+      (env) # NOTE: Low level command
+        _arguments \
+          ':perl installation: _perl_installations -with-lib' && ret=0
+        ;;
+      (symlink-executables) # NOTE: Low level command
+        _arguments \
+          ':perl installation: _perl_installations -with-lib' && ret=0
+        ;;
+      (lib)
+        _perlbrew_lib && ret=0
+        ;;
+      (download)
+        _arguments \
+          ':perl release: _perl_available' && ret=0
+        ;;
+      (clone-modules)
+        _arguments \
+          '--notest[skip all module tests]' \
+          ':perl installation: _perl_installations -with-lib' \
+          ':perl installation: _perl_installations -with-lib' && ret=0
+        ;;
+      (init|list|off|switch-off|install-cpanm|install-patchperl|self-upgrade|\
+        self-install|clean|version|upgrade-perl|list-modules)
+        _nothing && ret=0
+        ;;
+      (*)
+        _default && ret=0
+        ;;
+    esac
+    ;;
+esac
+
+return ret
diff --git a/Completion/Unix/Command/_pgrep b/Completion/Unix/Command/_pgrep
index 9c3ddf039..94c1dae1a 100644
--- a/Completion/Unix/Command/_pgrep
+++ b/Completion/Unix/Command/_pgrep
@@ -34,6 +34,7 @@ arguments=(
   '(-P --parent)'{-P+,--parent=}'[match only on specified parent process IDs]: :->ppid'
   '(-l)-q[suppress normal output]'
   '(-r --runstates)'{-r+,--runstates}'[match runstates]:run state:compadd -S "" D I R S T t W X Z'
+  '(-A --ignore-ancestors)'{-A,--ignore-ancestors}'[exclude our ancestors from results]'
   '-S[search also in system processes (kernel threads)]'
   '(-s --session)'{-s+,--session=}'[match only on specified process session IDs]: :->sid'
   # _signals is OK here - we do it differently below
@@ -44,6 +45,7 @@ arguments=(
   '(-u --euid)'{-u+,--euid=}'[match only on specified effective user IDs]: :_sequence _users'
   '(-v --inverse)'{-v,--inverse}'[negate matching]'
   '(-x --exact)'{-x,--exact}'[match process name or command line (with -f) exactly]'
+  '--cgroup=[match by cgroup v2 names]:cgroup'
   '--ns=[match only on same namespaces as specified PID]: :_pids'
   '--nslist=[match only on specified namespaces (with --ns)]:namespace:(ipc mnt net pid user uts)'
   '(: * -)'{-V,--version}'[display version information]'
@@ -55,6 +57,8 @@ arguments=(
   '(-w --lightweight)'{-w,--lightweight}'[show all thread IDs instead of PID]'
 )
 [[ $service == pkill ]] && arguments+=(
+  '(-H --require-handler)'{-H,--require-handler}'[match only if signal handler is present]'
+  '(-q --queue)'{-q+,--queue=}'[specify value to be sent with the signal]:value'
   '(-e --echo)'{-e,--echo}'[display signalled process]'
   '-l[display kill command]'
 )
@@ -62,8 +66,8 @@ arguments=(
 case $OSTYPE in
   linux*)
     # Note: We deliberately exclude -v but not --inverse from pkill
-    pgopts=acdFfGghLlnoOPrstUuVvwx-
-    pkopts=ceFfGghLnoOPstUuVx-
+    pgopts=AacdFfGghLlnoOPrstUuVvwx-
+    pkopts=AceFfGgHhLnoOPstUuVx-
     arguments=(
       ${arguments:#((#s)|*\))(\*|)-[acl]*}
       '(-c --count)'{-c,--count}'[display count of matching processes]'
diff --git a/Completion/Unix/Command/_ping b/Completion/Unix/Command/_ping
index d36a0f3a9..84bd76b82 100644
--- a/Completion/Unix/Command/_ping
+++ b/Completion/Unix/Command/_ping
@@ -199,7 +199,9 @@ case ${variant}:${${service#ping}:-4} in
       '-A[adaptive]'
       '-b[allow pinging a broadcast address]'
       "-B[don't allow ping to change source address]"
+      '-C[call connect() syscall on socket creation]'
       '-D[print timestamp before each line]'
+      '-e+[define identifier for ping session]:identifier'
       '(-4)-F+[allocate and set 20-bit flow label]:flow label (hex)'
       '(-)-h[show usage information]'
       '-I+[specify source interface]:interface:_net_interfaces'
diff --git a/Completion/Unix/Command/_ps b/Completion/Unix/Command/_ps
index 9b54cbcc6..c3dfae47d 100644
--- a/Completion/Unix/Command/_ps
+++ b/Completion/Unix/Command/_ps
@@ -105,6 +105,7 @@ case $OSTYPE in
     bsdarg+=( 'M[extract values from specified core]' )
   ;|
   linux-gnu|netbsd*) bsdarg+=( 'k[specify sort order]' ) ;|
+  linux-gnu|openbsd*) bsd+=( 'f[show process hierarchy]' ) ;|
   darwin*|freebsd*)
     bsd+=( 'X[skip processes with no controlling terminal]' )
     bsdarg+=( '*G[select processes by real group]' )
@@ -162,10 +163,12 @@ case $OSTYPE in
       '(-N --deselect)'{-N,--deselect}'[negate selection: all processes except those selected]'
       '*-C[select processes by command name]:command:_sequence -s , _command_names -e'
       '*--ppid[select processes by parent process ID]:parent process:_sequence -S , _pids'
+      '(-D --date-format)'{-D,--date-format=}'[set the date format of the lstart field to format]:format:_strftime'
       '(-f)-F[extra full format listing]'
       '--context[show SELinux security context format]'
       '-M[show security data]'
       '(--forest -H)'{--forest,-H}'[show process hierarchy]'
+      '-P[add psr column]'
       '--headers[repeat header lines, one per page of output]'
       '(--cols --columns --width)'{--cols,--columns,--width}'[set screen width]:width'
       '(--lines --rows)'{--lines,--rows}'[set screen height]'
@@ -188,7 +191,6 @@ case $OSTYPE in
     done
     bsd+=(
       'c[show true command name]'
-      'f[show process hierarchy]'
       'h[suppress header]'
       'm[show threads after processes]'
       'n[numeric output for WCHAN and USER]'
diff --git a/Completion/Unix/Command/_pv b/Completion/Unix/Command/_pv
index d02d3a35d..b21625650 100644
--- a/Completion/Unix/Command/_pv
+++ b/Completion/Unix/Command/_pv
@@ -17,7 +17,9 @@ _arguments -s -S $args \
   '(-I --fineta -F --format)'{-I,--fineta}'[show absolute estimated time of arrival]' \
   '(-r --rate -F --format)'{-r,--rate}'[show data transfer rate counter]' \
   '(-a --average-rate -F --format)'{-a,--average-rate}'[show data transfer average rate counter]' \
-  '(-b --bytes -F --format)'{-b,--bytes}'[show number of bytes transferred]' \
+  '(-m --average-rate-window)'{-m+,--average-rate-window=}'[compute average rate over period]:duration (seconds) [30]' \
+  '(-b --bytes -8 --bits -F --format)'{-b,--bytes}'[show number of bytes transferred]' \
+  '(-8 --bits -b --bytes -F --format)'{-8,--bits}'[show number of bits transferred]' \
   '(-T --buffer-percent -F --format)'{-T,--buffer-percent}'[show percentage of transfer buffer in use]' \
   '(-A --last-written -F --format)'{-A+,--last-written=}'[show number of bytes last written]:number (bytes)' \
   '(-F --format -p --progress -t --timer -e --eta -I --fineta -r --rate -a --average-rate -b --bytes -T --buffer-percent -A --last-written -F --format)'{-F+,--format=}'[set output format]:format:->formats' \
diff --git a/Completion/Unix/Command/_pydoc b/Completion/Unix/Command/_pydoc
index 677c96ad6..626c528cd 100644
--- a/Completion/Unix/Command/_pydoc
+++ b/Completion/Unix/Command/_pydoc
@@ -6,13 +6,14 @@ local -a args
 
 args=(
   '(- *)-k[search keyword]:keyword'
-  '(-k -g -w *)-p[start web server on specified port]:port number'
+  '(-k -g -w)-p[start web server on specified port]:port number'
   '(-)-w[write out HTML in current directory]'
   '(-)*: :->lookup'
 )
 
 if _pick_variant pydoc3='pydoc3 -b' pydoc2 -h; then
-  args+=( '(-k -w *)-b[start server and open browser]' )
+  args+=( '(-k -w)-b[start server and open browser]' )
+  args+=( '(-k -w)-n[start web server with the given hostname]:hostname' )
 else
   args+=( '(- *)-g[start gui]' )
 fi
diff --git a/Completion/Unix/Command/_python b/Completion/Unix/Command/_python
index e5bac18bb..6e209a199 100644
--- a/Completion/Unix/Command/_python
+++ b/Completion/Unix/Command/_python
@@ -1,9 +1,9 @@
 #compdef -P python[0-9.]#
 
 # Python 2.7
-# Python 3.9
+# Python 3.11
 
-local curcontext="$curcontext" state state_descr line
+local curcontext="$curcontext" state state_descr line _compskip="$_compskip"
 typeset -A opt_args
 local -a args
 
@@ -12,7 +12,11 @@ if _pick_variant python3=Python\ 3 python2 --version; then
     '(-bb)-b[issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str]'
     '(-b)-bb[issue errors about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str]'
     '--check-hash-based-pycs[configure how Python evaluates up-to-dateness of hash-based .pyc files]:mode:(always default never)'
+    '--help-env[print help about Python environment variables and exit]'
+    '--help-xoptions[print help about implementation-specific -X options and exit]'
+    '--help-all[print complete help information and exit]'
     "-I[isolate Python from the user's environment]"
+    '-P[do not prepend a potentially unsafe path to sys.path]'
     '-q[do not print version and copyright messages]'
     '-X[set implementation-specific option]:option'
   )
diff --git a/Completion/Unix/Command/_qemu b/Completion/Unix/Command/_qemu
index 7bc02c30c..6ca11b4fb 100644
--- a/Completion/Unix/Command/_qemu
+++ b/Completion/Unix/Command/_qemu
@@ -51,5 +51,7 @@ _arguments \
   '-no-acpi[disable ACPI]' \
   '-loadvm[start right away with a saved state]:file:_files' \
   '-g[set initial graphic mode]:graphic mode:' \
+  '-enable-kvm[enable KVM full virtualization support]' \
+  '-bios[use specified BIOS image]:bios image:_files' \
   ':disk image:_files'
 
diff --git a/Completion/Unix/Command/_rake b/Completion/Unix/Command/_rake
index 10d621991..49b49c014 100644
--- a/Completion/Unix/Command/_rake
+++ b/Completion/Unix/Command/_rake
@@ -1,12 +1,11 @@
 #compdef rake
 
-# rake, version 0.8.3
+# rake, version 13.0.6
 
 local curcontext="$curcontext" state line expl ret=1
 typeset -A opt_args
 
 _arguments -C -s -S \
-  '(--classic-namespace -C)'{--classic-namespace,-C}'[put Task and FileTask in the top level namespace]' \
   '(--dry-run -n)'{--dry-run,-n}'[do a dry run without executing actions]' \
   '(- *)'{--describe,-D}'[describe the tasks (matching the specified pattern), then exit]:pattern::' \
   '(--execute -e)'{--execute,-e}'[execute some Ruby code and exit]:Ruby code:' \
@@ -15,7 +14,7 @@ _arguments -C -s -S \
   '(- *)'{--help,-h,-H}'[display help information]' \
   \*{--libdir,-I}'[include specified directory in the search path for required modules]:library directory:_files -/' \
   '(--rakelibdir --rakelib -R)'{--rakelibdir,--rakelib,-R}'[auto-import any .rake files in the specified directory. (default is 'rakelib')]:rake library directory:_files -/' \
-  '(--nosearch -N)'{--nosearch,-N}'[do not search parent directories for the Rakefile]' \
+  '(--nosearch --no-search -N)'{--nosearch,--no-search,-N}'[do not search parent directories for the Rakefile]' \
   '(- *)'{--prereqs,-P}'[display the tasks and prerequisites, then exit]' \
   '(--quiet -q --silent -s --verbose -v)'{--quiet,-q}'[do not log messages to standard output]' \
   '(--rakefile -f)'{--rakefile,-f}'[use specified file as the rakefile]:rake file:_files' \
@@ -27,6 +26,18 @@ _arguments -C -s -S \
   '(--trace -t)'{--trace,-t}'[turn on invoke/execute tracing, enable full backtrace]' \
   '(--quiet -q --silent -s --verbose -v)'{--verbose,-v}'[log message to standard output (default)]' \
   '(- *)'{--version,-V}'[display version information]' \
+  '--backtrace=-[enable full backtrace]::out:(stderr stdout)' \
+  '--comments[show commented tasks only]' \
+  '--job-stats[display job statistics]:level' \
+  '--suppress-backtrace[suppress backtrace lines matching regexp PATTERN]:pattern' \
+  '(-A -a)'{-A,--all}'[show all tasks]' \
+  '(-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]:dir:_files -/' \
+  '(-G --no-system --nosystem)'{-G,--no-system,--nosystem}'[use standard project Rakefile search paths, ignore system wide rakefiles]' \
+  '(-j --jobs)'{-j,--jobs}'[specifies the maximum number of tasks to execute in parallel]::tasks' \
+  '(-m --multitask)'{-m,--multitask}'[treat all tasks as multitasks]' \
+  '(- *)'{-W,--where}'[describe the tasks(matching optional PATTERN) then exit]::pattern' \
+  '(-X --no-deprecation-warnings)'{-X,--no-deprecation-warnings}'[disable the deprecation warnings]' \
   '*:target:->target' && ret=0
 
 case "$state" in
diff --git a/Completion/Unix/Command/_readelf b/Completion/Unix/Command/_readelf
index fc0fb7ce1..b3abdf0a5 100644
--- a/Completion/Unix/Command/_readelf
+++ b/Completion/Unix/Command/_readelf
@@ -16,10 +16,12 @@ args=(
   '(-V --version-info)'{-V,--version-info}'[show version sections (if present)]'
   '(-A --arch-specific)'{-A,--arch-specific}'[show architecture specific information (if any)]'
   '(-c --archive-index)'{-c,--archive-index}'[show symbol/file index in an archive]'
+  '(-D --use-dynamic)'{-D,--use-dynamic}'[use dynamic section info when showing symbols]'
   \*{-x,--hex-dump=}"[dump contents of specified section as bytes]:section:($sections)"
   \*{-p,--string-dump=}"[dump contents of specified section as strings]:section:($sections)"
-  '-w+[show the contents of DWARF2 debug sections]::debug section:(l L i a p r m f F s o O R t U u T g A c k K)'
-  '--debug-dump=[show the contents of DWARF2 debug sections]::section:(rawline decodedline info abbrev pubnames aranges macro frames frames-interp str loc Ranges pubtypes gdb_index trace_info trace_abbrev trace_aranges addr cu_index links follow-links)'
+  '-w+[show the contents of DWARF2 debug sections]::debug section:(a A r c L f F g i o m p t R l s O u T U k K N)'
+  '--debug-dump=[show the contents of DWARF2 debug sections]::section:(abbrev addr aranges cu_index decodedline frames frames-interp gdb_index info loc macro pubnames pubtypes Ranges rawline str str-offsets trace_abbrev trace_aranges trace_info links follow-links no-follow-links)'
+  '(-P --process-links)'{-P,--process-links}'[display the contents of non-debug sections in separate debuginfo files]'
   '(-I --histogram)'{-I,--histogram}'[show histogram of bucket list lengths]'
   '(-W --wide)'{-W,--wide}'[allow output width to exceed 80 characters]'
   '(- *)'{-H,--help}'[display help information]'
@@ -35,7 +37,6 @@ case $variant in
       '(-s --syms --symbols)'{-s,--syms,--symbols}'[show symbol table]'
       '(-n --notes)'{-n,--notes}'[show core notes (if present)]'
       '(-u --unwind)'{-u,--unwind}'[show unwind info (if present)]'
-      '(-D --use-dynamic)'{-D,--use-dynamic}'[use dynamic section info when showing symbols]'
     )
   ;|
   elfutils|binutils)
@@ -50,11 +51,14 @@ case $variant in
   ;|
   binutils)
     args+=(
+      '--sym-base=[force base for symbol sizes]:base:(0 8 10 16)'
       '!(-C --demangle)--no-demangle'
       '(--demangle)-C[decode symbol names]'
-      '(-C)--demangle=-[decode symbol names]::style [auto]:(auto gnu lucid arm hp edg gnu-v3 java gnat)'
+      '(-C)--demangle=-[decode symbol names]::style [auto]:(none auto gnu-v3 java gnat dlang rust)'
       '!(--no-recurse-limit)--recurse-limit'
       '--no-recurse-limit[disable demangling recursion limit]'
+      '-U+[specify how to display unicode characters]:method:(d l e x h i)'
+      '--unicode=[specify how to display unicode characters]:method:(default locale escape hex highlight invalid)'
       '(-L --lint --enable-checks)'{-L,--lint,--enable-checks}'[display warning messages for possible problems]'
       \*{-R,--relocated-dump=}"[dump contents of specified section as relocated bytes]:section:($sections)"
       "--dwarf-depth=[don't show DIEs at greater than specified depth]:depth"
@@ -63,6 +67,7 @@ case $variant in
       '--ctf-parent=[use specified section as the CTF parent]:section'
       '--ctf-symbols=[use specified section as the CTF external symbol table]:section'
       '--ctf-strings=[use specified section as the CTF external string table]:section'
+      '--sframe=-[display SFrame info from section]::section name [.sframe]'
       '(-T --silent-truncation)'{-T,--silent-truncation}"[if a symbol name is truncated, don't add ... suffix]"
     )
   ;;
diff --git a/Completion/Unix/Command/_ri b/Completion/Unix/Command/_ri
index 4d5a72985..fe458e25f 100644
--- a/Completion/Unix/Command/_ri
+++ b/Completion/Unix/Command/_ri
@@ -26,33 +26,22 @@ _arguments -C \
   '*:ri name:->ri-name' && return
 
 if [[ "$state" = ri-name ]]; then
-  local -a ri_dirs ri_ext ri_names ri_wants ri_names
+  local -a ri_dirs ri_names ri_wants ri_names
   local class_dir esc_name dir curtag tag descr expl
 
-  if "ruby${words[1]#ri}" -rrdoc/ri/ri_options -e 1 >/dev/null 2>&1; then
-    # Old-style Ruby 1.8.x RI
-    ri_dirs=( ${(f)"$(_call_program ri-names "ruby${words[1]#ri}" -rrdoc/ri/ri_options -e '"o = RI::Options.instance; o.parse(ARGV); o.path.each { |p| puts p }"' -- ${(kv)opt_args[(I)-d|--doc-dir|--(system|site|gems|home)]})"} )
-    ri_ext=yaml
-  elif "ruby${words[1]#ri}" -rrdoc/ri -rrdoc/ri/store -e 1 >/dev/null 2>&1; then
-    # Newer-style Ruby 1.9.2 RI
-    ri_dirs=( ${(f)"$(_call_program ri-names "$words[1]" ${(kv)opt_args[(I)-d|--doc-dir|--((no-|)(system|site|gems|home)|standard-docs)]} --list-doc-dirs -f bs -T)"} )
-    ri_ext=ri
-  else
-    # New-style Ruby 1.9+ RI
-    ri_dirs=( ${(f)"$(_call_program ri-names "$words[1]" ${(kv)opt_args[(I)-d|--doc-dir|--((no-|)(system|site|gems|home)|standard-docs)]} --list-doc-dirs -f plain -T)"} )
-    ri_ext=yaml
-  fi
+  ri_dirs=( ${(f)"$(_call_program ri-names "$words[1]" ${(kv)opt_args[(I)-d|--doc-dir|--((no-|)(system|site|gems|home)|standard-docs)]} --list-doc-dirs -f bs -T)"} )
 
-  if compset -P '?*(::|\#|.)'; then
+  if compset -P '?*(::|:|\#|.)'; then
     class_dir=${IPREFIX//(::|\#|.)/\/}
   fi
   esc_name=${${(Q)PREFIX}//(#b)([^A-Za-z0-9_])/$(printf %%%x ${(qq)match[1]})}
 
   case "$IPREFIX" in
-    (*::) ri_wants=( 'classes:class names' 'class-methods:class methods' );;
-    (*\#) ri_wants=( 'instance-methods:instance methods' );;
-    (*.) ri_wants=( 'class-methods:class methods' 'instance-methods:instance methods' );;
-    (*) ri_wants=( 'classes:class names' )
+    (*::) ri_wants=( 'classes:class name' 'class-methods:class method' );;
+    (*:) ri_wants=( 'docs:documentation file' );;
+    (*\#) ri_wants=( 'instance-methods:instance method' );;
+    (*.) ri_wants=( 'class-methods:class method' 'instance-methods:instance method' );;
+    (*) ri_wants=( 'classes:class name' 'gems:gem' )
   esac
 
   for curtag in $ri_wants; do
@@ -63,27 +52,36 @@ if [[ "$state" = ri-name ]]; then
     while _tags; do
       while _next_label "$tag" expl "$descr"; do
         ri_wants=()
+        suf=()
         case "$tag" in
+          (gems)
+            ri_wants=( ruby ${${(f)"$(_call_program gems gem${words[1]#ri} list -q --no-versions)"}%% *} )
+            suf=( -S : )
+          ;;
           (classes)
           for dir in $ri_dirs[@]; do
             ri_wants+=( $dir/$class_dir*(-/:t) )
           done
+          suf=( -S '::' )
           ;;
           (class-methods)
           for dir in $ri_dirs[@]; do
-            fnames=( $dir/$class_dir*-c.$ri_ext(-.:t) )
-            ri_wants+=( ${${fnames%-c.$ri_ext}//(#b)%(??)/$(print "\\x$match[1]")} )
+            fnames=( $dir/$class_dir*-c.ri(-.:t) )
+            ri_wants+=( ${${fnames%-c.ri}//(#b)%(??)/$(print "\\x$match[1]")} )
           done
           ;;
           (instance-methods)
           for dir in $ri_dirs[@]; do
-            fnames=( $dir/$class_dir*-i.$ri_ext(-.:t) )
-            ri_wants+=( ${${fnames%-i.$ri_ext}//(#b)%(??)/$(print "\\x$match[1]")} )
+            fnames=( $dir/$class_dir*-i.ri(-.:t) )
+            ri_wants+=( ${${fnames%-i.ri}//(#b)%(??)/$(print "\\x$match[1]")} )
           done
           ;;
+          (docs)
+            ri_wants=( ${${(f)"$(_call_program docs $words[1] ${(kv)opt_args[(I)-d|--doc-dir|--((no-|)(system|site|gems|home)|standard-docs)]} $IPREFIX)"}:#=*} )
+          ;;
         esac
         ri_names=( ${(Q)ri_wants} )
-        compadd -S '' -d ri_names -a "$expl[@]" ri_wants && ret=0
+        compadd $suf -d ri_names -a "$expl[@]" ri_wants && ret=0
       done
       (( ret )) || break
     done
diff --git a/Completion/Unix/Command/_rm b/Completion/Unix/Command/_rm
index e66b77fa4..6dddb5ece 100644
--- a/Completion/Unix/Command/_rm
+++ b/Completion/Unix/Command/_rm
@@ -47,14 +47,10 @@ case $variant; in
   darwin*|dragonfly*|freebsd*|netbsd*)
     args+=(
       '-W[attempt to undelete named files]'
-    )
-    ;|
-  dragonfly*|freebsd*|netbsd*)
-    args+=(
       "-x[don't cross file systems when removing a hierarchy]"
     )
     ;|
-  dragonfly*|freebsd*)
+  darwin*|dragonfly*|freebsd*)
     args+=(
       '(-i)-I[prompt when removing many files]'
     )
diff --git a/Completion/Unix/Command/_route b/Completion/Unix/Command/_route
index 95df6d936..f0775a5d2 100644
--- a/Completion/Unix/Command/_route
+++ b/Completion/Unix/Command/_route
@@ -196,7 +196,7 @@ if [[ -n $state ]]; then
   if [[ $line[1] = exec ]]; then
     shift words
     (( CURRENT-- ))
-    _normal
+    _normal -p $service && return
   elif [[ $line[1] = (flush|monitor) ]]; then
     sequential=()
   fi
diff --git a/Completion/Unix/Command/_rsync b/Completion/Unix/Command/_rsync
index eb906e974..c65266dbd 100644
--- a/Completion/Unix/Command/_rsync
+++ b/Completion/Unix/Command/_rsync
@@ -141,8 +141,9 @@ _rsync() {
     '(-X --xattrs)'{-X,--xattrs}'[preserve extended attributes]' \
     '--fake-super[use xattrs to save all file attributes]' \
     '(-d --dirs)'{-d,--dirs}'[transfer directories without recursing]' \
-    {--no-d,--no-dirs}'[turn off --dirs]' \
-    "--mkpath[create the destination's path component]" \
+    '(--no-d --no-dirs)'{--no-d,--no-dirs}'[turn off --dirs]' \
+    '(--old-dirs --old-d)'{--old-dirs,--old-d}'[work like --dirs when talking to old rsync]' \
+    "--mkpath[create destination's missing path components]" \
     '(-l --links)'{-l,--links}'[copy symlinks as symlinks]' \
     {--no-l,--no-links}'[turn off --links]' \
     '(-L --copy-links)'{-L,--copy-links}'[transform symlinks into referent file/dir]' \
@@ -161,8 +162,10 @@ _rsync() {
     '(-g --group)'{-g,--group}'[preserve group]' \
     {--no-g,--no-group}'[turn off --group]' \
     '(--devices --specials)-D[same as --devices --specials]' \
-    '(-D)--devices[preserve devices]' \
+    '(-D --copy-devices --write-devices)--devices[preserve devices]' \
     '--no-devices[turn off --devices]' \
+    '(-D --devices)--copy-devices[copy device contents as a regular file]' \
+    '(-D --devices)--write-devices[write to devices as files (implies --inplace)]' \
     '(-D)--specials[preserve special files]' \
     '--no-specials[turn off --specials]' \
     '--no-D[turn off --devices and --specials]' \
@@ -179,7 +182,7 @@ _rsync() {
     '(-n --dry-run)'{-n,--dry-run}'[show what would have been transferred]' \
     '(-W --whole-file)'{-W,--whole-file}'[copy files whole (without delta-transfer algorithm)]' \
     {--no-W,--no-whole-file}'[turn off --whole-file]' \
-    '(--cc --checksum-choice)'{--cc,--checksum-choice}'=[choose the checksum algorithms]:algorithm:_sequence -n 2 compadd - auto md4 md5 none' \
+    '(--cc --checksum-choice)'{--cc,--checksum-choice}'=[choose the checksum algorithms]:algorithm:_sequence -n 2 compadd - auto xxh128 xxh3 xxh64 xxhash md4 md5 sha1 none' \
     '(-x --one-file-system)'{-x,--one-file-system}"[don't cross filesystem boundaries]" \
     '(-B --block-size)'{-B+,--block-size=}'[force a fixed checksum block-size]: :_numbers -f -u bytes -d 1g "block size" B K M G T P' \
     '(-e --rsh)'{-e+,--rsh=}'[specify the remote shell to use]:remote-shell command:(rsh ssh)' \
@@ -233,7 +236,8 @@ _rsync() {
     '*--include=[do not exclude files matching pattern]:pattern' \
     '--files-from=[read list of source-file names from specified file]:file:_files' \
     '(-0 --from0)'{-0,--from0}'[all *-from file lists are delimited by nulls]' \
-    '(-s --protect-args)'{-s,--protect-args}'[no space-splitting; only wildcard special-chars]' \
+    '(-s --secluded-args)'{-s,--secluded-args}'[use the protocol to safely send arguments]' \
+    "--trust-sender[trust the remote sender's file list]" \
     '--copy-as=[specify user & optional group for the copy]:user:_rsync_users_groups' \
     '--version[print version number]' \
     '*'{-h,--human-readable}'[output numbers in a human-readable format]' \
@@ -251,6 +255,7 @@ _rsync() {
     '--list-only[list the files instead of copying them]' \
     '--stop-after=[stop copying after specified time has elapsed]:time (minutes)' \
     '--stop-at=[stop copying when specified point in time is reached]:date/time (YYYY-MM-DDTHH\:MM):_dates -F -S "T"' \
+    '--fsync[fsync every written file]' \
     '(--only-write-batch)--write-batch=[write a batched update to the specified file]:file:_files' \
     '(--write-batch)--only-write-batch=[like --write-batch but w/o updating destination]:file:_files' \
     '--protocol=[force an older protocol version to be used]:number' \
diff --git a/Completion/Unix/Command/_ruby b/Completion/Unix/Command/_ruby
index 0e1f5dbc0..9955253b3 100644
--- a/Completion/Unix/Command/_ruby
+++ b/Completion/Unix/Command/_ruby
@@ -40,38 +40,59 @@ opts=(
   '(-v)--verbose[turn on verbose mode and disable script from stdin]'
   '-x-[strip off text before #!ruby line and perhaps cd to directory]:directory:_files -/'
   '(1 * -)--copyright[print the copyright]'
-  --{en,dis}'able=[enable or disable features]:feature:(gems did_you_mean rubyopt frozen_string_literal jit all)'
+  --{en,dis}'able=[enable or disable features]:feature:(gems error_highlight did_you_mean syntax_suggest rubyopt frozen_string_literal mjit yjit all)'
   \!--{en,dis}able-{gems,rubyopt,all}
-  '--dump=[dump debug information]:information:_sequence compadd - insns yydebug parsetree parsetree_with_comment'
+  '--dump=[dump debug information]:information:_sequence compadd - insns insns_without_opt yydebug parsetree parsetree_with_comment'
   --{external,internal}'-encoding=:charset:->charsets'
+  '--backtrace-limit=[limit the maximum length of backtrace]:number'
   '!'{-y,--yydebug}
   '!--dump=:target:(version copyright usage yydebug syntax parsetree parsetree_with_comment insns)'
-  '--jit[enable jit with default options]'
-  '--jit-warnings[enable printing JIT warnings]'
-  '--jit-debug[enable JIT debugging (very slow)]'
-  '--jit-wait[wait until JIT compilation finishes every time (for testing)]'
-  '--jit-save-temps[save JIT temporary files]'
-  '--jit-verbose=-[print JIT logs of level num or less to stderr]:maximum log level [0]'
-  '--jit-max-cache=-[specify max number of methods to be JIT-ed in a cache]:number [100]'
-  '--jit-min-calls=-[specify number of calls to trigger JIT]:calls [10000]'
+  '(--mjit --yjit)--jit[enable jit for the platform]'
+  '(--jit --yjit)--mjit[enable C compiler-based JIT compiler]'
+  '(--jit --mjit)--yjit[enable in-process JIT compiler]'
+  '--mjit-warnings[enable printing JIT warnings]'
+  '--mjit-debug[enable JIT debugging (very slow)]'
+  '--mjit-wait[wait until JIT compilation finishes every time (for testing)]'
+  '--mjit-save-temps[save JIT temporary files]'
+  '--mjit-verbose=-[print JIT logs of level num or less to stderr]:maximum log level [0]'
+  '--mjit-max-cache=-[specify max number of methods to be JIT-ed in a cache]:number [100]'
+  '--mjit-min-calls=-[specify number of calls to trigger JIT]:calls [10000]'
+  '--yjit-stat[enable collecting YJIT statistics]'
+  '--yjit-exec-mem-size=-[size of executable memory block in MiB]:mem size'
+  '--yjit-call-threshold=-[number of calls to trigger JIT]:number'
+  '--yjit-max-versions=-[maximum number of versions per basic block]:versions'
+  '--yjit-greedy-versioning[greedy versioning mode]'
 )
 
 irb=(
   '-f[suppress read of ~/.irbrc]'
-  '(--noinspect)-m[bc mode (load mathn, fraction, matrix)]'
   $opts[(r)*-d\[*]
   '(--noinspect)--inspect[use inspect for output]'
   "(--inspect)--noinspect[don't use inspect for output]"
-  '(--noreadline)--readline[use readline extension]'
-  "(--readline)--noreadline[don't use readline extension]"
-  '(--prompt --prompt-mode --inf-ruby-mode --simple-prompt --noprompt)'{--prompt,--prompt-mode}'[switch prompt mode]:prompt mode:(default simple xmp inf-ruby)'
+  '(--prompt --prompt-mode --inf-ruby-mode --simple-prompt --noprompt)'{--prompt=,--prompt-mode=}'[switch prompt mode]:prompt mode:(default classic simple inf-ruby xmp null)'
   '(--prompt --prompt-mode --inf-ruby-mode --simple-prompt --noprompt)'{--inf-ruby-mode,--simple-prompt,--noprompt}
   '--tracer[display trace for each command execution]'
   '--back-trace-limit[set limit for backtraces]:limit [16]:'
   '!--irb_debug:level'
   '--context-mode:n'
+  '--extra-doc-dir[add an extra doc dir for the doc dialog]'
   '(--noecho)--echo[show result]'
   "(--echo)--noecho[don't show result]"
+  '(--noecho-on-assignment)--echo-on-assignment[show result on assignment]'
+  "(--echo-on-assignment)--noecho-on-assignment[don't show result on assignment]"
+  '--truncate-echo-on-assignment[show truncated result on assignment]'
+  '(--nomultiline)--multiline[use multiline editor module]'
+  "(--multiline)--nomultiline[don't use multiline editor module]"
+  '(--nosingleline)--singleline[use single line editor module]'
+  "(--singleline)--nosingleline[don't use single line editor module]"
+  '(--nocolorize)--colorize[use color-highlighting]'
+  "(--colorize)--nocolorize[don't use color-highlighting]"
+  '(--noautocomplete)--autocomplete[use auto-completion]'
+  "(--autocomplete)--noautocomplete[don't use auto-completion]"
+  '(--regexp-completor)--type-completor[use regexp based completion]'
+  '(--type-completor)--regexp-completor[use type based completion]'
+  '(--noscript)--script[script mode]'
+  '(--script)--noscript[no script mode]'
   '--single-irb[share self with sub-irb]'
   '(--noverbose)--verbose[show details]'
   "(--verbose)--noverbose[don't show details]"
@@ -81,8 +102,9 @@ erb=(
   "-P[don't evaluate lines which start with %]"
   '-T[specify trim mode]:mode [0]:((0\:EOL\ remains 1\:EOL\ removed\ if\ line\ ends\ with\ %\> 2\:EOL\ removed\ if\ line\ starts\ with\ \<%\ and\ ends\ with\ %\> -\:EOL\ is\ removed\ if\ line\ ends\ with\ -%\>,\ leading\ whitespace\ removed\ after\ \<%-))'
   '(-d --debug)'{-d,--debug}'[set debugging flags (set $DEBUG to true)]'
-  '-n[used with -x, prepends line number to output]'
-  '-x[convert eRuby to Ruby]'
+  '-n[print ruby script with line number]'
+  '-x[print ruby script]'
+  '-v[enable verbose mode]'
 )
 
 case "$service" in
diff --git a/Completion/Unix/Command/_samba b/Completion/Unix/Command/_samba
index 6c7a64e18..a36130cf9 100644
--- a/Completion/Unix/Command/_samba
+++ b/Completion/Unix/Command/_samba
@@ -5,16 +5,29 @@ local -a state line expl msgs args ign
 
 (( CURRENT == 2 )) || ign='!'
 args=(
+  '--debug-stdout[send debug output to stdout]'
   '(-d --debuglevel)'{-d+,--debuglevel=}'[set debug level]:debug level (1..10) [1]'
   '(-s --configfile)'{-s+,--configfile=}'[specify alternate smb.conf file]:config file:_files'
   '(-l --log-basename)'{-l+,--log-basename=}'[specify base name for log files]:base name:_files'
   '*--option=[set smb.conf option from command line]:option=value'
+  '--leak-report[enable talloc leak reporting on exit]'
+  '--leak-report-full[enable full talloc leak reporting on exit]'
   "${ign}(1 2 3 -)"{-\?,--help}'[display usage information]'
   "${ign}(1 2 3 -)--usage[display brief usage information]"
   "${ign}(1 2 3 - *)"{-V,--version}'[display version information]'
 )
 
 case $service in
+  smbclient|nmblookup)
+    args+=(
+      '(2 -R --name-resolve)'{-R+,--name-resolve=}'[specify name resolution order]:name resolution order:_values -s " " "name resolution order" lmhosts host wins bcast'
+      '(-m --max-protocol)'{-m+,--max-protocol=}'[set the max protocol level]:level'
+      '(2 -O --socket-options)'{-O+,--socket-options=}'[specify socket options]:socket options'
+      '(2)--netbios-scope=[specify NetBIOS scope]:scope'
+      '(2 -W --workgroup)'{-W+,--workgroup=}'[specify workgroup name]:workgroup name'
+      '--realm=[set the realm name]:realm'
+    )
+  ;|
   smbcontrol)
     _arguments -C -S $args \
       '(-t --timeout)'{-t+,--timeout=}'[set timeout]:timeout (seconds)' \
@@ -42,12 +55,10 @@ case $service in
   smbclient)
     args+=(
       '(-N -A)2: :_guard "^-*" password'
-      '(2 -R --name-resolve)'{-R+,--name-resolve=}'[specify name resolution order]:name resolution order:_values -s " " "name resolution order" lmhosts host wins bcast'
       '(2 -M --message -L --list -D --directory -T --tar)'{-M+,--message=}'[send message]:host:_hosts'
       '(2 -I --ip-address)'{-I+,--ip-address=}'[specify IP address of server]:IP address'
       '(2 -E --stderr)'{-E,--stderr}'[output messages to stderr]'
       '(2 -M --message -D --directory -T --tar)'{-L+,--list=}'[list services on server]:host:_hosts'
-      '(-m --max-protocol)'{-m+,--max-protocol=}'[set the max protocol level]:level'
       '(2 -T --tar -M --message -L --list)'{-T+,--tar=}'[specify tar options]:tar options'
       '(2 -D --directory -M --message -L --list)'{-D+,--directory=}'[specify initial directory]:initial directory'
       '(2 -c --command)'{-c,--command=}'[specify commands]:command string'
@@ -58,19 +69,18 @@ case $service in
       '(-q --quiet)'{-q,--quiet}'[suppress help message]'
       '(-B --browse)'{-B,--browse}'[browse SMB servers using DNS]'
       '(2 -d --debuglevel)'{-d+,--debuglevel=}'[specify debug level]:debug level:(0 1 2 3 4 5 6 7 8 9 10)'
-      '(2 -O --socket-options)'{-O+,--socket-options=}'[specify socket options]:socket options'
       '(2 -n --netbiosname)'{-n+,--netbiosname=}'[specify local NetBIOS name]:local machine name'
-      '(2 -W --workgroup)'{-W+,--workgroup=}'[specify workgroup]:workgroup'
-      '(2 -i --scope)'{-i+,--scope=}'[specify NetBIOS scope]:scope'
       '(2 -U --user)'{-U+,--user=}'[specify username]:username:_users'
       '(2 -N --no-pass)'{-N,--no-pass}'[suppress password prompt]'
-      '(-k --kerberos)'{-k,--kerberos}'[use kerberos (active directory) authentication]'
+      '--pw-nt-hash[the supplied password is the NT hash]'
       '(2 -A --authentication-file)'{-A+,--authentication-file=}'[specify file containing username/password]:file:_files'
-      '(-S --signing)'{-S+,--signing=}'[set the client signing state]:state:(on off required)'
       '(-P --machine-pass)'{-P,--machine-pass}'[use stored machine account password]'
-      '(-e --encrypt)'{-e,--encrypt}'[encrypt SMB transport]'
-      '(-C --use-ccache)'{-C,--use-ccache}'[use the winbind ccache for authentication]'
-      '--pw-nt-hash[the supplied password is the NT hash]'
+      '--simple-bind-dn=[specify DN to use for a simple bind]:DN'
+      '--use-kerberos=[use Kerberos authentication]:state:(desired required off)'
+      '--use-krb5-ccache=[specify credentials cache location for Kerberos]:file:_files'
+      '--use-winbind-ccache[use the winbind ccache for authentication]'
+      '--client-protection=[configure protection used for client connections]:protection:(sign encrypt off)'
+      '!(--use-kerberos)'{-k,--kerberos}
     )
     (( CURRENT == 2 )) && args+=( '1:service name:_hosts -P // -S /' )
     _arguments -s -S $args
@@ -81,16 +91,13 @@ case $service in
       '(-f --flags)'{-f,--flags}'[list NMB flags returned]' \
       '(-U --unicast)'{-U+,--unicast=}'[specify unicast address]:unicast address' \
       '(-M --master-browser)'{-M,--master-browser}'[search for a master browser]' \
-      '(-R --recursion)'{-R,--recursion}'[set recursion desired in packet]' \
+      '--recursion[set recursion desired in packet]' \
       '(-S --status)'{-S,--status}'[lookup node status as well]' \
       '(-T --translate)'{-T,--translate}'[perform reverse DNS on IP addresses]' \
       '(-r --root-port)'{-r,--root-port}'[use root port 137]' \
       '(-A --lookup-by-ip)'{-A,--lookup-by-ip}'[query node status on IP address]' \
       '(-d --debuglevel)'{-d+,--debuglevel=}'[specify debug level]:debug level:(0 1 2 3 4 5 6 7 8 9 10)' \
-      '(-O --socket-options)'{-O+,--socket-options=}'[specify socket options to use]:socket option' \
       '(-n --netbiosname)'{-n+,--netbiosname=}'[specify primary netbios name]:netbios name' \
-      '(-W --workgroup)'{-W+,--workgroup=}'[specify workgroup name]:workgroup name' \
-      '(-i --scope)'{-i+,--scope=}'[specify NetBIOS scope]:scope' \
       '(h)*:NetBIOS name:_hosts'
   ;;
   smbstatus)
diff --git a/Completion/Unix/Command/_sccs b/Completion/Unix/Command/_sccs
index 4083fe54e..20222a5c1 100644
--- a/Completion/Unix/Command/_sccs
+++ b/Completion/Unix/Command/_sccs
@@ -1,4 +1,4 @@
-#compdef sccs admin cdc comb delta get help prs prt rmdel sact sccsdiff unget val what
+#compdef sccs sccsdiff
 
 (( $+functions[_sccs_files] )) ||
 _sccs_files() {
diff --git a/Completion/Unix/Command/_scons b/Completion/Unix/Command/_scons
index 77fe6dfb0..2e465216c 100644
--- a/Completion/Unix/Command/_scons
+++ b/Completion/Unix/Command/_scons
@@ -24,14 +24,14 @@ _arguments -s -S \
   '(--implicit-cache --implicit-deps-changed)--implicit-deps-changed[rescan dependencies]' \
   '(--implicit-cache --implicit-deps-unchanged)--implicit-deps-unchanged[ignore changes to scanned dependencies]' \
   '--interactive[start interactive mode]' \
-  '(-j --jobs)-'{j,jobs=}'[specify no of jobs to run in parallel]' \
+  '(-j --jobs)-'{j,-jobs=}'[specify no of jobs to run in parallel]:number of jobs' \
   '(-k --keep-going)-'{k,-keep-going}'[continue after an error]' \
   '--max-drift=[set the maximum clock drift]:drift (seconds)' \
   '--md5-chunksize=[set chunksize for MD5 signature computation]:size (kB)' \
   '(-n --just-print --dry-run --recon)-'{n,-just-print,-dry-run,-recon}"[print commands but don't run them]" \
   "--no-site-dir[don't use the usual site_scons directory]" \
   '--profile=[profile scons]:output file:_files' \
-  '(-q --question)-'{q,question}'[query whether up-to-date]' \
+  '(-q --question)-'{q,-question}'[query whether up-to-date]' \
   '-Q[suppress progress messages]' \
   '--random[build dependencies in random order]' \
   '(-s --silent --quiet)-'{s,-silent,-quiet}"[don't print commands]" \
diff --git a/Completion/Unix/Command/_screen b/Completion/Unix/Command/_screen
index 6d47d2638..9336ae82d 100644
--- a/Completion/Unix/Command/_screen
+++ b/Completion/Unix/Command/_screen
@@ -107,7 +107,7 @@ if [[ -n $state ]]; then
       elif (( CURRENT > 2 )) && [[ ${words[1]} == /dev/* ]]; then
 	  _message "no more parameters"
       else
-	  _normal
+	  _normal -p $service
       fi
     ;;
     attached-sessions)
diff --git a/Completion/Unix/Command/_script b/Completion/Unix/Command/_script
index 7a3960be0..d38d56f2e 100644
--- a/Completion/Unix/Command/_script
+++ b/Completion/Unix/Command/_script
@@ -47,7 +47,7 @@ case $OSTYPE in
       '-q[be quiet: suppress display of starting and ending lines]'
       '(-a -r -k)-d[suppress sleeps when playing back a session]'
       '(-a -r -k -t)-p[play back a recorded session]'
-      '(-d -p)-r[record a session with input, output and timing data]'
+      '(-d -p -T)-r[record a session with input, output and timing data]'
     )
   ;|
   netbsd*|openbsd*)
@@ -60,7 +60,9 @@ case $OSTYPE in
   ;|
   freebsd*)
     args+=(
+      '-e[return exit status of the child process]'
       '-f[use filemon(4)]'
+      '(-a -r -k -t)-T[play back a recorded session, reporting only timestamps]: :_date_formats'
     )
   ;|
   darwin*|dragonfly*|freebsd*)
@@ -68,11 +70,9 @@ case $OSTYPE in
       '-F[send output to specified named pipe]:fifo:_files -g "*(p)"'
       '-t+[specify interval of data flushing]:interval (seconds)'
       '-k[log keys sent to the program as well as output]'
-      '*:::arguments: _normal'
+      '*:::arguments: _normal $service'
     )
   ;|
-  darwin*|freebsd*)
-  ;|
   *)
     args+=(
       '(-p -d)-a[append output]'
diff --git a/Completion/Unix/Command/_sed b/Completion/Unix/Command/_sed
index 79a010c92..ef3aaf2fd 100644
--- a/Completion/Unix/Command/_sed
+++ b/Completion/Unix/Command/_sed
@@ -104,14 +104,13 @@ else
   case $OSTYPE in
     openbsd*|freebsd*|netbsd*|darwin*|dragonfly*)
       args+=(
-	'(-r -E)'-E$extended
+	'(-r -E)'{-E,-r}$extended
 	'-a[delay opening files listed with w function]'
       )
     ;|
-    openbsd*|freebsd*|netbsd*|dragonfly*) args+=( '(-r -E)'-r$extended ) ;|
     darwin*|freebsd*|netbsd*|openbsd*|dragonfly*) args+=( '-i+'$inplace ) ;|
     darwin*|freebsd*|netbsd*|dragonfly*) args+=( '-l[make output line buffered]' ) ;|
-    freebsd*|dragonfly*) args+=( '-u[disable data buffering]' ) ;|
+    darwin*|freebsd*|dragonfly*) args+=( '-u[disable data buffering]' ) ;|
     freebsd*|netbsd*|dragonfly*)
       args+=(
         '-I+[edit files in-place, treating all files as a single input stream]:: :_guard "^(*[@/; \\\]*|?(#c6,)|-*)" "suffix for backup"'
diff --git a/Completion/Unix/Command/_service b/Completion/Unix/Command/_service
index 1216f57a8..28563429b 100644
--- a/Completion/Unix/Command/_service
+++ b/Completion/Unix/Command/_service
@@ -10,8 +10,11 @@ zstyle -T  ":completion:${ctx}" tag-order && \
   zstyle ":completion:${ctx}" tag-order init
 
 case $OSTYPE in
+  freebsd<14->.*)
+    args=( '-E+[set environment variable before executing the rc.d script]:variable:_parameters -g "*export*~*readonly*" -S=' )
+  ;&
   freebsd<11->.*)
-    args=( '-j+[perform actions in specified jail]:jail:_jails' )
+    args+=( '-j+[perform actions in specified jail]:jail:_jails' )
   ;&
   freebsd*|dragonfly*)
     actions=(
diff --git a/Completion/Unix/Command/_split b/Completion/Unix/Command/_split
index c5ab0dc9b..5d5afa436 100644
--- a/Completion/Unix/Command/_split
+++ b/Completion/Unix/Command/_split
@@ -8,7 +8,7 @@ _pick_variant -r variant gnu=GNU $OSTYPE --version
 
 args=(
   '-a+[generate suffixes of specified length]:length [2]' \
-  '(-l -p -n)-b+[put specified size in bytes in each output file]:size (bytes)' \
+  '(-l -p -n)-b+[put specified size in bytes in each output file]: :_numbers -u bytes size k m g' \
   '(-b -p -n)-l+[put specified number of lines/records in each output file]:lines' \
   '1:file:_files' \
   '2: :_guard "^-*" "prefix [x]"'
@@ -19,8 +19,8 @@ case $variant in
     args=( -C
       '(H -a --suffix-length)'{-a+,--suffix-length=}'[generate suffixes of specified length]:length [2]'
       '(H)--additional-suffix=[append an additional suffix to file names]:suffix'
-      '(H -b --bytes -C --line-bytes -l --lines -n --number)'{-b+,--bytes=}'[put specified size in bytes in each output file]:size (bytes)'
-      '(H -b --bytes -C --line-bytes -l --lines -n --number)'{-C+,--line-bytes=}'[put whole lines/records up to size limit in each output file]:size (bytes)'
+      '(H -b --bytes -C --line-bytes -l --lines -n --number)'{-b+,--bytes=}'[put specified size in each output file]: :_numbers -M "m\:{a-zA-Z}={A-Za-z}" -u bytes size {K,M,G,T,P,E,Z}{,B}' \
+      '(H -b --bytes -C --line-bytes -l --lines -n --number)'{-C+,--line-bytes=}'[put whole lines/records up to size limit in each output file]: :_numbers -M "m\:{a-zA-Z}={A-Za-z}" -u bytes size {K,M,G,T,P,E,Z}{,B}'
       '(H --numeric-suffixes -x --hex-suffixes)-d[use numeric suffixes starting at 0]'
       '(H -d -x --hex-suffixes)--numeric-suffixes=-[use numeric suffixes]::start value [0]'
       '(H -d --numeric-suffixes --hex-suffixes)-x[use hex suffixes starting at 0]'
@@ -39,15 +39,20 @@ case $variant in
       '(- 1 2)--version[display version information]'
     )
   ;;
-  (free|net)bsd*)
+  (free|net)bsd*|darwin*)
     args+=( '(-b -l -p)-n+[generate specified number of output files]:output files' )
   ;|
   darwin*|freebsd*)
     args+=(
+      '-d[use numeric suffixes]'
       '(-b -l -n)-p+[split the file whenever a line matches specified pattern]:pattern'
     )
   ;|
-  freebsd*) args+=( '-d[use numeric suffixes]' ) ;;
+  freebsd*)
+    args+=(
+      "-c[continue creating files and don't overwrite existing output files]"
+    )
+  ;;
 esac
 
 _arguments -s -S $args && ret=0
diff --git a/Completion/Unix/Command/_sqlite b/Completion/Unix/Command/_sqlite
index 7ef3c6daa..6f0b1de94 100644
--- a/Completion/Unix/Command/_sqlite
+++ b/Completion/Unix/Command/_sqlite
@@ -12,7 +12,7 @@ dashes=( '' )
 
 options=(
   '(-init --init)'$^dashes'-init[startup file]:file containing SQLite commands:_files'
-  $^dashes'-echo[echo commands]'
+  $^dashes'-echo[print inputs before execution]'
 )
 
 exclusive=( {,-}-{no,}header )
@@ -55,9 +55,13 @@ options+=(
   $^dashes'-mmap[set default mmap size]:size'
   $^dashes'-newline[set output row separator]:separator [\n]'
   $^dashes'-nofollow[refuse to open symbolic links to database files]'
+  $^dashes'-nonce[set the safe-mode escape nonce]:string'
   $^dashes'-pagecache[specify size and number of slots for page cache memory]:size (bytes): :slots'
+  $^dashes'-pcachetrace[trace all page cache operations]'
   $^dashes'-readonly[open the database read-only]'
+  $^dashes'-safe[enable safe-mode]'
   $^dashes'-stats[print memory stats before each finalize]'
+  $^dashes'-unsafe-testing[allow unsafe commands and modes for testing]'
   $^dashes'-vfs[use specified default VFS]:vfs:(unix-dotfile unix-excl unix-none unix-namedsem)'
   $^dashes'-zip[open the file as a ZIP Archive]'
 )
@@ -68,12 +72,14 @@ if [[ -n $words[(r)-A*] ]]; then
     '(1 -a --append -f --file)'{-f+,--file=}'[specify archive file]:archive file:_files'
     '(1 -a --append -f --file)'{-a,--append=}'[operate on specified file opened using the apndvfs VFS]:archive file:_files'
     '(-C --directory)'{-C+,--directory=}'[change to specified directory to read/extract files]:directory:_directories'
+    '(-g --glob)'{-g,--glob}'[use glob matching for names in archive]'
     '(-n --dryrun)'{-n,--dryrun}'[show the SQL that would have occurred]'
     '*:file:_files'
     + '(commands)' \
     '(-c --create)'{-c,--create}'[create a new archive]'
     '(-u --update)'{-u,--update}'[update or add files to an existing archive]'
     '(-i --insert)'{-i,--insert}'[like -u but always add even if mtime unchanged]'
+    '(-r --remove)'{-r,--remove}'[remove files from archive]'
     '(-t --list)'{-t,--list}'[list contents of archive]'
     '(-x --extract)'{-x,--extract}'[extract files from archive]'
   )
diff --git a/Completion/Unix/Command/_ssh b/Completion/Unix/Command/_ssh
index 2385272f1..5e6e60573 100644
--- a/Completion/Unix/Command/_ssh
+++ b/Completion/Unix/Command/_ssh
@@ -18,14 +18,18 @@ _ssh () {
     '*-o+[specify extra options]:option string:->option'
   )
   common_transfer=(
+    '(-O)-D+[connect directly to a local sftp server]:sftp server path:_command_names -e'
     '-J+[connect via a jump host]: :->userhost'
     '-l+[limit used bandwidth]:bandwidth (Kbit/s)'
     '-P+[specify port on remote host]:port number on remote host'
     '-p[preserve modification times, access times and modes]'
     '-q[disable progress meter and warnings]'
     '-r[recursively copy directories (follows symbolic links)]'
-    '-S+[specify ssh program]:path to ssh:_command_names -e' \
+    '-S+[specify ssh program]:path to ssh:_command_names -e'
     '-v[verbose mode]'
+    '(-O)*-X+[specify sftp protocol option]: : _values "sftp option"
+      "nrequests[set max concurrent SFTP read or write requests]\:requests [64]"
+      "buffer[set max buffer size for a single SFTP read/write operation]\: \:_numbers -l 0 -m 256K -d 32K -u bytes -f size \:B\:bytes \:K\:kilobytes"'
   )
   algopt='-E+[specify hash algorithm for fingerprints]:algorithm:(md5 sha256)'
 
@@ -53,12 +57,12 @@ _ssh () {
       "-N[don't execute a remote command]" \
       '-n[redirect stdin from /dev/null]' \
       '-O+[control an active connection multiplexing master process]:multiplex control command:((check\:"check master process is running" exit\:"request the master to exit" forward\:"request forward without command execution" stop\:"request the master to stop accepting further multiplexing requests" cancel\:"cancel existing forwardings with -L and/or -R" proxy))' \
-      '-P[use non privileged port]' \
+      '-P+[specify a tag name that may be used to select configuration]:tag' \
       '-p+[specify port on remote host]:port number on remote host' \
       '(-v)*-q[quiet operation]' \
       '*-R+[specify remote port forwarding]:remote port forwarding:->forward' \
       '-S+[specify location of control socket for connection sharing]:path to control socket:_files' \
-      '-Q+[query parameters]:query option:((cipher\:"supported symmetric ciphers" cipher-auth\:"supported symmetric ciphers that support authenticated encryption" mac\:"supported message integrity codes" kex\:"key exchange algorithms" key\:"key types" key-cert\:"certificate key types" key-plain\:"non-certificate key types" protocol-version\:"supported SSH protocol versions" sig\:"supported signature algorithms" help\:"show supported queries"))' \
+      '-Q+[query parameters]:query option:((cipher\:"supported symmetric ciphers" cipher-auth\:"supported symmetric ciphers that support authenticated encryption" compression mac\:"supported message integrity codes" kex\:"key exchange algorithms" kex-gss\:"GSSAPI key exchange algorithms" key\:"key types" key-cert\:"certificate key types" key-plain\:"non-certificate key types" key-sig\:"all key types and signature algorithms" protocol-version\:"supported SSH protocol versions" sig\:"supported signature algorithms" help\:"show supported queries" HostbasedAcceptedAlgorithms HostKeyAlgorithms KexAlgorithms MACs PubkeyAcceptedAlgorithms))' \
       '-s[invoke subsystem]' \
       '(-t)-T[disable pseudo-tty allocation]' \
       "(-T)*-t[force pseudo-tty allocation${tdesc}]" \
@@ -76,7 +80,8 @@ _ssh () {
   scp)
     _arguments -C -s \
       '-3[copy through local host, not directly between the remote hosts]' \
-      '-B[batch mode (don'\''t ask for passphrases)]' \
+      "-B[batch mode (don't ask for passwords or passphrases)]" \
+      '(-D -X)-O[use the original SCP protocol instead of the SFTP protocol]' \
       '-T[disable strict filename checking]' \
       '*:file:->file' "$common[@]" "$common_transfer[@]" && ret=0
     ;;
@@ -95,12 +100,15 @@ _ssh () {
       '--apple-load-keychain[add identities from keychain]'
       '--apple-use-keychain[update keychain when adding/removing identities]'
     )
-    _arguments -s : $args \
+    _arguments -C -s : $args \
+      '-C[process certificates only]' \
       '-c[identity is subject to confirmation via SSH_ASKPASS]' \
       '-D[delete all identities]' \
       '-d[remove identity]' \
       $algopt \
       '-e+[remove keys provided by the PKCS#11 shared library]:library:_files -g "*.(so|dylib)(|.<->)(-.)"' \
+      '*-H[specify a known hosts file to look up hostkeys]:known hosts file:_files' \
+      '*-h[constrain keys to specific hosts or destinations]:destination:->destinations' \
       '-k[load plain private keys only and skip certificates]' \
       '-K[load resident keys from a FIDO authenticator]' \
       '-L[list public key parameters of all identities in the agent]'\
@@ -109,14 +117,13 @@ _ssh () {
       '-M+[specify maximum number of signatures]:number' \
       '-S+[use specified library when adding FIDO authenticator-hosted keys]:library:_files' \
       '-s+[add keys provided by the PKCS#11 shared library]:library:_files -g "*.(so|dylib)(|.<->)(-.)"' \
-      '-t+[set maximum lifetime for identity]:maximum lifetime (in seconds or time format):' \
+      '-t+[set maximum lifetime for identity]: :_numbers -u seconds "maximum lifetime" \:s\:seconds m\:minutes h\:hours d\:days w\:weeks' \
       "-T[test usability of identity files' private keys]:*:public key file:_files -g '*.pub(-.)'" \
       '*-v[verbose mode]' \
       '-q[be quiet after a successful operation]' \
       '-X[unlock the agent]' \
       '-x[lock the agent with a password]' \
-      '*:SSH identity file:_files'
-    return
+      '*:SSH identity file:_files' && ret=0
     ;;
   ssh-agent)
     _arguments -s \
@@ -128,9 +135,9 @@ _ssh () {
       '-k[kill current agent]' \
       '(-k)-P[specify PKCS#11 shared library whitelist]:PKCS#11 library whitelist pattern' \
       '(-k -c)-s[force sh-style shell]' \
-      '-t[set default maximum lifetime for identities]:maximum lifetime (in seconds or time format):' \
+      '-t+[set default maximum lifetime for identities]: :_numbers -u seconds "maximum lifetime" \:s\:seconds m\:minutes h\:hours d\:days w\:weeks' \
       '-v[verbose mode]' \
-      '*::command: _normal'
+      '*::command: _normal -p $service'
     return
     ;;
   ssh-keygen)
@@ -183,15 +190,13 @@ _ssh () {
       case ${words[arg]#-Y} in
         ^find-*) sigargs+=( "$p1-n+[specify namespace]:namespace" ) ;|
 	check*|find*|verify)
-	  sigargs+=( "$p1-s+[specify signature file]:signature file:-files" )
+	  sigargs+=( "$p1-s+[specify signature file]:signature file:_files" )
 	;|
+        match*|verify) sigargs+=( '-I+[specify signer identity]:identity' ) ;|
 	sign) sigargs+=( '*:file:_files' ) ;;
 	verify)
 	  args=()
-	  sigargs+=(
-	    '-I+[specify signer identity]:identity'
-	    '-r+[specify revocation file]:revocation file:_files'
-	  )
+	  sigargs+=( '-r+[specify revocation file]:revocation file:_files' )
 	;;
       esac
     fi
@@ -210,7 +215,7 @@ _ssh () {
       "(${${(@)cmds:#-p}} -v ${${(@)cms:#-[qt]}})-N+[provide new passphrase]:new passphrase" \
       "(${${(@)cmds:#-c}} -v $cms)-C+[provide new comment]:new comment" \
       "(-D -I -h -n -V -A)-f+[$file file]:$file file:_files" \
-      "$p1(${${(@)cmds:#-[FE]}} ${${(@)cmn:#-v}} ${${(@)cms:#-E}})-l[show fingerprint of key file]" \
+      "(${${(@)cmds:#-[FE]}} ${${(@)cmn:#-v}} ${${(@)cms:#-E}})-l[show fingerprint of key file]" \
       "$p1(${${(@)cmds:#-[iep]}} $cms)-m+[specify conversion format]:format [RFC4716]:(PEM PKCS8 RFC4716)" \
       "$p1*-O+[specify a key/value option]: : _values 'option' $options" \
       "(${${(@)cmds:#-[lGT]}} ${${(@)cmn:#-[bv]}} -f)*-v[verbose mode]" \
@@ -235,12 +240,6 @@ _ssh () {
       "($cmn)-L[print the contents of a certificate]" \
       "(${${(@)cmn:#-a}})-A[generate host keys for all key types]" \
       "($cmn)-Q[test whether keys have been revoked in a KRL]" \
-      "($cmn)-Y+[signature action]:action:((
-        find-principals\:find\ the\ principal\ associated\ with\ the\ public\ key\ of\ a\ signature
-        sign\:sign\ a\ file\ using\ SSH\ key
-        verify\:verify\ a\ signature\ generated\ using\ the\ sign\ option
-        check-novalidate\:check\ signature\ structure
-      ))" \
       - finger \
       "$p1($cmn)$algopt" \
       - create \
@@ -260,6 +259,13 @@ _ssh () {
       "($cmn -I -h -n -D -O -U -V)-k[generate a KRL file]" \
       "$p1($cmn -I -h -n -D -O -U -V)-u[update a KRL]" \
       - signature \
+      "(${${(@)cmn:#-O}})-Y+[signature action]:action:((
+        find-principals\:find\ the\ principal\ associated\ with\ the\ public\ key\ of\ a\ signature
+        sign\:sign\ a\ file\ using\ SSH\ key
+        verify\:verify\ a\ signature\ generated\ using\ the\ sign\ option
+        check-novalidate\:check\ signature\ structure
+        match-principals\:find\ matching\ principal
+      ))" \
       $sigargs
     return
   ;;
@@ -271,8 +277,10 @@ _ssh () {
       '-D[print keys found as SSHFP DNS records]' \
       '*-f+[read hosts from file, one per line]:file:_files' \
       '-H[hash all hostnames and addresses in the output]' \
+      '-O+[specify a key/value option]: : _values option
+        "hashalg[select a hash algorithm to use with -D]\:algorithm [both]\:(sha1 sha256)"' \
       '-p+[specify port on remote host]:port number on remote host' \
-      '-T+[specify timeout]:timeout (seconds) [5]' \
+      '-T+[specify timeout]: :_numbers -u seconds -d 5 timeout \:s\:seconds m\:minutes h\:hours d\:days w\:weeks' \
       '-t+[specify key types to fetch from scanned hosts]:key type:_sequence compadd - rsa dsa ecdsa ed25519' \
       '-v[verbose mode]'
     return
@@ -282,7 +290,6 @@ _ssh () {
       '-a[attempt to continue interrupted transfers]' \
       '-B+[specify buffer size]:buffer size (bytes) [32768]' \
       '-b+[specify batch file to read]:batch file:_files' \
-      '-D+[connect directly to a local sftp server]:sftp server path' \
       '-f[request that files be flushed immediately after transfer]' \
       '-N[disable implicit quiet mode set by -b]' \
       '-R+[specify number of outstanding requests]:number of requests [64]' \
@@ -309,22 +316,37 @@ _ssh () {
     option)
       if compset -P 1 '*='; then
         case "${IPREFIX#-o}" in
-          (#i)(ciphers|macs|kexalgorithms|hostkeyalgorithms|pubkeyacceptedkeytypes|hostbasedkeytypes)=)
-          if ! compset -P '[+-]'; then
-            _wanted prefix expl 'relative to default' compadd - + - && ret=0
+          (#i)(ciphers|macs|kexalgorithms|hostkeyalgorithms|pubkeyacceptedalgorithms)=)
+          local sep
+          zstyle -s ":completion:${curcontext}:" list-separator sep || sep=--
+          if ! compset -P '[+-^]'; then
+            _wanted prefix expl 'relative to default' compadd -S '' -d \
+                "(
+                   +\ $sep\ append\ to\ default\ list
+                   -\ $sep\ remove\ from\ default\ list
+                   ^\ $sep\ insert\ at\ head\ of\ default\ list
+                )" - + - \^ && ret=0
           fi
           ;;
         esac
         case "${IPREFIX#-o}" in
-        (#i)(afstokenpassing|batchmode|canonicalizefallbacklocal|challengeresponseauthentication|checkhostip|clearallforwardings|compression|enablesshkeysign|exitonforwardfailure|fallbacktorsh|forward(agent|x11)|forwardx11trusted|gatewayports|gssapiauthentication|gssapidelegatecredentials|gssapikeyexchange|gssapirenewalforcesrekey|gssapitrustdns|hashknownhosts|hostbasedauthentication|identitiesonly|kbdinteractiveauthentication|(tcp|)keepalive|nohostauthenticationforlocalhost|passwordauthentication|permitlocalcommand|proxyusefdpass|pubkeyauthentication|rhosts(|rsa)authentication|rsaauthentication|streamlocalbindunlink|usersh|kerberos(authentication|tgtpassing)|useprivilegedport|visualhostkey)=*)
+        (#i)(batchmode|canonicalizefallbacklocal|checkhostip|clearallforwardings|compression|enableescapecommandline|enablesshkeysign|exitonforwardfailure|fallbacktorsh|forkafterauthentication|forward(agent|x11)|forwardx11trusted|gatewayports|gssapiauthentication|gssapidelegatecredentials|gssapikeyexchange|gssapirenewalforcesrekey|gssapitrustdns|hashknownhosts|hostbasedauthentication|identitiesonly|kbdinteractiveauthentication|tcpkeepalive|nohostauthenticationforlocalhost|passwordauthentication|permitlocalcommand|permitremoteopen|proxyusefdpass|stdinnull|streamlocalbindunlink|visualhostkey)=*)
           _wanted values expl 'truth value' compadd yes no && ret=0
           ;;
+        (#i)addkeystoagent=*)
+          _alternative \
+            'timeouts: :_numbers -u seconds "time interval" :s:seconds m:minutes h:hours d:days w:weeks' \
+            'values:value:(yes no ask confirm)' && ret=0
+        ;;
         (#i)addressfamily=*)
           _wanted values expl 'address family' compadd any inet inet6 && ret=0
           ;;
         (#i)bindaddress=*)
           _wanted bind-addresses expl 'bind address' _bind_addresses && ret=0
           ;;
+        (#i)bindinterface=*)
+          _wanted bind-interfaces expl 'bind interface' _network_interfaces && ret=0
+        ;;
         (#i)canonicaldomains=*)
           _message -e 'canonical domains (space separated)' && ret=0
           ;;
@@ -340,23 +362,27 @@ _ssh () {
         (#i)ciphers=*)
           state=ciphers
           ;;
+        (#i)certificatefile=*)
+          _description files expl 'file'
+          _files "$expl[@]" && ret=0
+        ;;
         (#i)connectionattempts=*)
           _message -e 'connection attempts' && ret=0
           ;;
         (#i)connecttimeout=*)
-          _message -e 'connection timeout' && ret=0
+          _numbers -u seconds timeout :s:seconds m:minutes h:hours d:days w:weeks && ret=0
           ;;
         (#i)controlmaster=*)
-          _wanted values expl 'truthish value' compadd yes no auto autoask && ret=0
+          _wanted values expl 'truthish value' compadd yes no auto ask autoask && ret=0
           ;;
         (#i)controlpath=*)
           _description files expl 'path to control socket'
           _files "$expl[@]" && ret=0
           ;;
         (#i)controlpersist=*)
-          _message -e 'timeout'
-          ret=0
-          _wanted values expl 'truth value' compadd yes no && ret=0
+          _alternative \
+            'timeouts: :_numbers -u seconds timeout :s:seconds m:minutes h:hours d:days w:weeks' \
+            'values:truth value:(yes no)' && ret=0
           ;;
         (#i)escapechar=*)
           _message -e 'escape character (or `none'\'')'
@@ -377,9 +403,10 @@ _ssh () {
         (#i)hostname=*)
           _wanted hosts expl 'real host name to log into' _ssh_hosts && ret=0
           ;;
-        (#i)(hostbasedkeytypes|hostkeyalgorithms|pubkeyacceptedkeytypes)=*)
-	  _wanted key-types expl 'key type' _sequence compadd - $(_call_program key-types ssh -Q key) && ret=0
-          ;;
+        (#i)identityagent=*)
+          _description files expl 'socket file'
+          _files -g "*(-=)" "$expl[@]" && ret=0
+        ;;
         (#i)identityfile=*)
           _description files expl 'SSH identity file'
           _files "$expl[@]" && ret=0
@@ -410,13 +437,16 @@ _ssh () {
           _values -s , 'keyboard-interactive authentication method' \
               'bsdauth' 'pam' 'skey' && ret=0
           ;;
-        (#i)(kexalgorithms|gssapikexalgorithms)=*)
+        (#i)kexalgorithms=*)
           _wanted algorithms expl 'key exchange algorithm' _sequence compadd - \
               $(_call_program algorithms ssh -Q kex) && ret=0
           ;;
-        (#i)localcommand=*)
-          _description commands expl 'run command locally after connecting'
-          _command_names && ret=0
+        (#i)gssapikexalgorithms=*)
+          _wanted algorithms expl 'key exchange algorithm' _sequence compadd - \
+              $(_call_program algorithms ssh -Q kex-gss) && ret=0
+        ;;
+        (#i)(local|knownhosts)command=*)
+          _command_names -e && ret=0
           ;;
         (#i)loglevel=*)
           _values 'log level' QUIET FATAL ERROR INFO VERBOSE\
@@ -429,8 +459,8 @@ _ssh () {
           _message -e 'number of password prompts'
           ret=0
           ;;
-        (#i)pkcs11provider=*)
-          _description files expl 'PKCS#11 shared library'
+        (#i)(pkcs11|securitykey)provider=*)
+          _description files expl 'shared library'
           _files -g '*.(so|dylib)(|.<->)(-.)' "$expl[@]" && ret=0
           ;;
         (#i)port=*)
@@ -441,6 +471,17 @@ _ssh () {
           _values -s , 'authentication method' gssapi-with-mic \
               hostbased publickey keyboard-interactive password && ret=0
           ;;
+        (#i)proxyjump=*)
+          compset -P "* "
+          state=userhost
+        ;;
+        (#i)(hostkey|(hostbased|pubkey)accepted)algorithms=*)
+	  _wanted key-types expl 'key type' _sequence compadd - \
+              $(_call_program key-types ssh -Q key-sig) && ret=0
+        ;;
+        (#i)pubkeyauthentication=*)
+          _wanted values expl 'enable' compadd yes no unbound host-bound && ret=0
+        ;;
         (#i)protocol=*)
           _values -s , 'protocol version' \
               '1' \
@@ -450,7 +491,13 @@ _ssh () {
           _cmdstring && ret=0
           ;;
         (#i)rekeylimit=*)
-          _message -e 'maximum number of bytes transmitted before renegotiating session key'
+          if compset -P "* "; then
+            _numbers -u seconds "maximum time before renegotiating session key" \
+                :s:seconds h:hours d:days w:weeks
+          else
+            _numbers -u bytes "maximum amount of data transmitted before renegotiating session key" \
+                K:kilobytes M:megabytes G:gigabytes
+          fi
           ret=0
           ;;
         (#i)requesttty=*)
@@ -460,6 +507,9 @@ _ssh () {
               'force[always request a TTY]' \
               'auto[request a TTY when opening a login session]' && ret=0
           ;;
+        (#i)requiredrsasize=)
+          _wanted sizes expl 'minimum size [1024]' compadd 1024 2048 4096 && ret=0
+        ;;
         (#i)revokedhostkeys=*)
           _description files expl 'revoked host keys file'
           _files "$expl[@]" && ret=0
@@ -478,6 +528,9 @@ _ssh () {
         (#i)streamlocalbindmask=*)
           _message -e 'octal mask' && ret=0
           ;;
+        (#i)sessiontype=*)
+          _wanted session-types expl "session type" compadd none subsystem default && ret=0
+        ;;
         (#i)stricthostkeychecking=*)
           _wanted values expl 'value' compadd yes no ask accept-new off && ret=0
           ;;
@@ -512,15 +565,18 @@ _ssh () {
           _description files expl 'xauth program'
           _files "$expl[@]" -g '*(-*)' && ret=0
           ;;
+        *) _message -e values value ;;
         esac
       else
-        # old options are after the empty "\"-line
+        # Include, Host and Match not supported from the command-line
+        # final GSSAPI options are not in upstream but are widely patched in
         _wanted values expl 'configure file option' \
             compadd -M 'm:{a-z}={A-Z} r:[^A-Z]||[A-Z]=* r:|=*' -q -S '=' - \
                 AddKeysToAgent \
                 AddressFamily \
                 BatchMode \
                 BindAddress \
+                BindInterface \
                 CanonicalDomains \
                 CanonicalizeFallbackLocal \
                 CanonicalizeHostname \
@@ -528,7 +584,6 @@ _ssh () {
                 CanonicalizePermittedCNAMEs \
                 CASignatureAlgorithms \
                 CertificateFile \
-                ChallengeResponseAuthentication \
                 CheckHostIP \
                 Ciphers \
                 ClearAllForwardings \
@@ -539,10 +594,12 @@ _ssh () {
                 ControlPath \
                 ControlPersist \
                 DynamicForward \
+                EnableEscapeCommandline \
                 EnableSSHKeysign \
                 EscapeChar \
                 ExitOnForwardFailure \
                 FingerprintHash \
+                ForkAfterAuthentication \
                 ForwardAgent \
                 ForwardX11 \
                 ForwardX11Timeout \
@@ -550,19 +607,13 @@ _ssh () {
                 GatewayPorts \
                 GlobalKnownHostsFile \
                 GSSAPIAuthentication \
-                GSSAPIClientIdentity \
                 GSSAPIDelegateCredentials \
-                GSSAPIKeyExchange \
-                GSSAPIRenewalForcesRekey \
-                GSSAPIServerIdentity \
-                GSSAPITrustDns \
-                GSSAPIKexAlgorithms \
                 HashKnownHosts \
+                HostbasedAcceptedAlgorithms \
                 HostbasedAuthentication \
-                HostbasedKeyTypes \
                 HostKeyAlgorithms \
                 HostKeyAlias \
-                HostName \
+                Hostname \
                 IdentitiesOnly \
                 IdentityAgent \
                 IdentityFile \
@@ -571,33 +622,38 @@ _ssh () {
                 KbdInteractiveAuthentication \
                 KbdInteractiveDevices \
                 KexAlgorithms \
+                KnownHostsCommand \
                 LocalCommand \
                 LocalForward \
                 LogLevel \
+                LogVerbose \
                 MACs \
                 NoHostAuthenticationForLocalhost \
                 NumberOfPasswordPrompts \
                 PasswordAuthentication \
                 PermitLocalCommand \
+                PermitRemoteOpen \
                 PKCS11Provider \
                 Port \
                 PreferredAuthentications \
                 ProxyCommand \
                 ProxyJump \
                 ProxyUseFdpass \
-                PubkeyAcceptedKeyTypes \
                 PubkeyAuthentication \
+                PubkeyAcceptedAlgorithms \
                 RekeyLimit \
                 RemoteCommand \
                 RemoteForward \
                 RequestTTY \
+                RequiredRSASize \
                 RevokedHostKeys \
-                RhostsRSAAuthentication \
-                RSAAuthentication \
+                SecurityKeyProvider \
                 SendEnv \
                 ServerAliveCountMax \
                 ServerAliveInterval \
                 SetEnv \
+                SessionType \
+                StdinNull \
                 StreamLocalBindMask \
                 StreamLocalBindUnlink \
                 StrictHostKeyChecking \
@@ -606,24 +662,17 @@ _ssh () {
                 Tunnel \
                 TunnelDevice \
                 UpdateHostKeys \
-                UsePrivilegedPort \
                 User \
                 UserKnownHostsFile \
                 VerifyHostKeyDNS \
                 VisualHostKey \
                 XAuthLocation \
-                \
-                AFSTokenPassing \
-                FallBackToRsh \
-                KeepAlive \
-                KerberosAuthentication \
-                KerberosTgtPassing \
-                PreferredAuthentications \
-                ProtocolKeepAlives \
-                RhostsAuthentication \
-                SetupTimeOut \
-                SmartcardDevice \
-                UseRsh \
+                GSSAPIClientIdentity \
+                GSSAPIKeyExchange \
+                GSSAPIRenewalForcesRekey \
+                GSSAPIServerIdentity \
+                GSSAPITrustDns \
+                GSSAPIKexAlgorithms \
                 && ret=0
       fi
       ;;
@@ -690,9 +739,13 @@ _ssh () {
       local -a _comp_priv_prefix
       shift 1 words
       (( CURRENT-- ))
-      _normal
+      _normal -p $service
       return
       ;;
+    destinations)
+      compset -P 1 '*>'
+      compset -S '>*'
+    ;& # fall-through
     userhost)
       if compset -P '*@'; then
         _wanted hosts expl 'remote host name' _ssh_hosts && ret=0
diff --git a/Completion/Unix/Command/_stdbuf b/Completion/Unix/Command/_stdbuf
index 4b7d98ba0..32b3cae2f 100644
--- a/Completion/Unix/Command/_stdbuf
+++ b/Completion/Unix/Command/_stdbuf
@@ -27,6 +27,6 @@ for ((i=1;i<=3;i++)); do
     "(${short[i]})${long[i]}=${(e)opt}"
   )
 done
-(( CURRENT > 2 )) && args+=( '*::command:_normal' )
+(( CURRENT > 2 )) && args+=( '*::command: _normal -p $service' )
 
 _arguments -s -S $args
diff --git a/Completion/Unix/Command/_stgit b/Completion/Unix/Command/_stgit
deleted file mode 100644
index e31af460a..000000000
--- a/Completion/Unix/Command/_stgit
+++ /dev/null
@@ -1,52 +0,0 @@
-#compdef stg
-
-typeset -a subcmds
-
-subcmds=( ${${${(M)${(f)"$(stg help 2> /dev/null)"}## *}#  }/#(#b)([^[:space:]]##)[[:space:]]##(*)/$match[1]:$match[2]} )
-
-local curcontext="$curcontext" expl
-local subcmd
-local ret=1
-
-if (( CURRENT == 2 )); then
-  _describe -t commands 'stgit command' subcmds && ret=0
-else
-  shift words
-  (( CURRENT-- ))
-  subcmd="$words[1]"
-  curcontext="${curcontext%:*}-${subcmd}:"
-
-  case $subcmd in
-    (push)
-      _wanted -V unapplied-patches expl "patch" \
-       	compadd ${${(M)${(f)"$(stg series 2> /dev/null)"}##- *}#- } \
-		&& ret=0
-    ;;
-    (pop)
-      _wanted -V applied-patches expl "patch" \
-	compadd ${${(M)${(f)"$(stg series 2> /dev/null)"}##[+>] *}#[+>] } \
-		&& ret=0
-    ;;
-    (edit|files|goto|rename|log|float|delete|sink|mail|sync|show|pick|hide|squash)
-      _wanted -V patches expl "patch" \
-	compadd $(stg series --noprefix 2> /dev/null) \
-		&& ret=0
-    ;;
-    (ref*)
-      last_word="$words[$CURRENT-1]"
-      refresh_patch_options=( -p --patch )
-      if [[ -n ${refresh_patch_options[(r)$last_word]} ]]; then
-	_wanted -V applied-patches expl "patch" \
-	  compadd ${${(M)${(f)"$(stg series 2> /dev/null)"}##[+>] *}#[+>] } \
-		  && ret=0
-      else
-	_files && ret=0
-      fi
-    ;;
-    (*)
-      _files && ret=0
-    ;;
-  esac
-fi
-
-return ret
diff --git a/Completion/Unix/Command/_strip b/Completion/Unix/Command/_strip
index 3e1a6b698..cc67ae49a 100644
--- a/Completion/Unix/Command/_strip
+++ b/Completion/Unix/Command/_strip
@@ -1,55 +1,68 @@
 #compdef strip
 
-local curcontext=$curcontext state line ret=1
+local curcontext=$curcontext state line variant ret=1
 declare -A opt_args
 declare -a args
 
-if _pick_variant gnu=GNU solaris --version; then
-  if [[ -prefix @* ]]; then
-    compset -P '@'
+if _pick_variant -r variant gnu=GNU elftoolchain=elftoolchain $OSTYPE --version; then
+  case $variant in
+    gnu|elftoolchain)
+      args=(
+        '(-g -S -d --strip-debug)'{-g,-S,-d,--strip-debug}'[remove debugging symbols]'
+        '(-I --input-target)'{-I+,--input-target=}'[object code format of input]:bfd name:->bfdnames'
+        '*'{-K+,--keep-symbol=}'[keep given symbol]:symbol name'
+        '*'{-N+,--strip-symbol=}'[strip given symbol]:symbol name'
+        '(-O --output-target)'{-O+,--output-target=}'[object code format of output]:bfd name:->bfdnames'
+        '(-p --preserve-dates)'{-p,--preserve-dates}'[preserve access and modification dates]'
+        '*'{-R+,--remove-section=}'[remove given sections]:section name'
+        '(-s --strip-all)'{-s,--strip-all}'[remove all symbols]'
+        '(-w --wildcard)'{-w,--wildcard}'[permit wildcards in symbol names]'
+        '(-X --discard-locals)'{-X,--discard-locals}'[remove compiler-generated local symbols]'
+        '(-x --discard-all)'{-x,--discard-all}'[remove non-global symbols]'
+        '--only-keep-debug[remove everything except debugging information]'
+        '--strip-unneeded[remove symbols not needed for relocation processing]'
+        '(- 1 *)'{-V,--version}'[display version information and exit]'
+      )
+    ;|
+    gnu)
+      if [[ -prefix @* ]]; then
+        compset -P '@'
 
-    local expl
+        local expl
 
-    _description files expl 'command-line-options file'
-    _files "$expl[@]"
-    return
-  fi
-  args=(
-    '(-F --target)'{-F+,--target=}'[object code format to use]:bfd name:->bfdnames'
-    '(-)--help[display usage information]'
-    '(-)--info[display list of architectures and object formats]'
-    '(-I --input-target)'{-I+,--input-target=}'[object code format of input]:bfd name:->bfdnames'
-    '(-O --output-target)'{-O+,--output-target=}'[object code format of output]:bfd name:->bfdnames'
-    '(-D --enable-deterministic-archives -U --disable-deterministic-archives)'{-U,--disable-deterministic-archives}'[disable -D behavior]'
-    '(-D --enable-deterministic-archives -U --disable-deterministic-archives)'{-D,--enable-deterministic-archives}'[produce deterministic output when stripping archives (zero file metadata)]'
-    '*'{-R+,--remove-section=}'[remove given sections]:section name'
-    '--remove-relocations=[remove relocations from specified section]:section'
-    '(-s --strip-all)'{-s,--strip-all}'[remove all symbols]'
-    '(-g -S -d --strip-debug)'{-g,-S,-d,--strip-debug}'[remove debugging symbols]'
-    '--strip-dwo[remove all DWARF .dwo sections]'
-    '--strip-unneeded[remove symbols not needed for relocation processing]'
-    '!(--no-merge-notes)'{-M,--merge-notes}
-    "--no-merge-notes[don't attempt to remove redundant notes]"
-    '*'{-K+,--keep-symbol=}'[keep given symbol]:symbol name'
-    '*'{-N+,--strip-symbol=}'[strip given symbol]:symbol name'
-    "*--keep-section=[don't strip given section]:section"
-    '(*)-o+[output file]:output file:_files'
-    '(-p --preserve-dates)'{-p,--preserve-dates}'[preserve access and modification dates]'
-    '(-w --wildcard)'{-w,--wildcard}'[permit wildcards in symbol names]'
-    '(-x --discard-all)'{-x,--discard-all}'[remove non-global symbols]'
-    '(-X --discard-locals)'{-X,--discard-locals}'[remove compiler-generated local symbols]'
-    '--keep-file-symbols[retain symbols specifying source file names]'
-    '--only-keep-debug[remove everything except debugging information]'
-    '(-)'{-V,--version}'[display version information and exit]'
-    '(-v --verbose)'{-v,--verbose}'[list all object files modified or members of archives]')
-else
-  case $OSTYPE in
+        _description files expl 'command-line-options file'
+        _files "$expl[@]"
+        return
+      fi
+      args+=(
+        '(-F --target)'{-F+,--target=}'[object code format to use]:bfd name:->bfdnames'
+        '(-)--help[display usage information]'
+        '(-)--info[display list of architectures and object formats]'
+        '(-D --enable-deterministic-archives -U --disable-deterministic-archives)'{-U,--disable-deterministic-archives}'[disable -D behavior]'
+        '(-D --enable-deterministic-archives -U --disable-deterministic-archives)'{-D,--enable-deterministic-archives}'[produce deterministic output when stripping archives (zero file metadata)]'
+        '--remove-relocations=[remove relocations from specified section]:section'
+        '--strip-dwo[remove all DWARF .dwo sections]'
+        '!(--no-merge-notes)'{-M,--merge-notes}
+        "--no-merge-notes[don't attempt to remove redundant notes]"
+        "*--keep-section=[don't strip given section]:section"
+        '(*)-o+[output file]:output file:_files'
+        '--keep-section-symbols[retain section symbols]'
+        '--keep-file-symbols[retain symbols specifying source file names]'
+        '(-v --verbose)'{-v,--verbose}'[list all object files modified or members of archives]')
+    ;;
+    elftoolchain)
+      args+=(
+        '(- 1 *)'{-h,--help}'[display usage information]'
+        '(*)'{-o+,--output-file=}'[specify output file]:output file:_files'
+      )
+    ;;
     solaris*)
       args=(
 	'-l[strip line information only]'
 	'-V[display version information on stderr and exit]'
-	'-x[do not strip the symbol table]')
-      ;;
+	'-x[do not strip the symbol table]'
+      )
+    ;;
     darwin*)
       local -a arch
       arch=( ${(z)${${"$(_call_program architectures
@@ -73,12 +86,13 @@ else
 	'-no_uuid[remove only LC_UUID load command]'
 	'-no_split_info[remove LC_SEGMENT_SPLIT_INFO load command]'
 	'-no_code_signature_warning[not warn when code signature would be invalid in the output]'
-	'-arch[specify the architecture]:architecture:( $arch )' )
-      ;;
+	'-arch[specify the architecture]:architecture:( $arch )'
+      )
+    ;;
   esac
 fi
 
-_arguments \
+_arguments -C \
   $args \
   '1:executable:_files -g "*(-*)"' \
   '*::executable:_files -g "*(-*)"' && ret=0
diff --git a/Completion/Unix/Command/_subversion b/Completion/Unix/Command/_subversion
index 8fc46a292..ccaf310fa 100644
--- a/Completion/Unix/Command/_subversion
+++ b/Completion/Unix/Command/_subversion
@@ -139,7 +139,7 @@ _svn () {
           ;;
           (commit)
             args=(
-	      ${args/(#b)(*--file*):arg:/$match[1]:file:_files}
+	      ${args/(#b)(*--file*):arg:/${match[1]}:file:_files}
               '*:file: _svn_modified "committable"'
             )
           ;;
@@ -189,7 +189,7 @@ _svn () {
 	    args=(
 	    ':propname:(svn:ignore svn:keywords svn:executable svn:eol-style svn:mime-type svn:externals svn:needs-lock svn:global-ignores svn:auto-props)'
 	    ':propval:->propset_propval'
-	    ${args/(#b)(*--file*):arg:/$match[1]:file:_files}
+	    ${args/(#b)(*--file*):arg:/${match[1]}:file:_files}
 	    '*:path or url: _alternative "files:file:_files" "urls:URL:_svn_urls"'
 	    )
 	  ;;
@@ -318,6 +318,9 @@ _svnadmin () {
           # Test cases:
           #   svnadmin freeze . rsync --<TAB> offers --file
           #   svnadmin freeze -- . rsync -<TAB> offers rsync's options
+          #   svnadmin freeze . -- rsync -<TAB> should do the same (but currently doesn't)
+          #
+          # TODO: Fix the third case.
           #
           # Note: the NORMARG calculations here include one positional argument
           # (the '.') before the command.
diff --git a/Completion/Unix/Command/_sudo b/Completion/Unix/Command/_sudo
index 29e5e6d75..c334c6765 100644
--- a/Completion/Unix/Command/_sudo
+++ b/Completion/Unix/Command/_sudo
@@ -1,9 +1,7 @@
 #compdef sudo sudoedit
 
-setopt localoptions extended_glob
-
-local environ e cmd cpp
-local -a args _comp_priv_prefix
+local curcontext="$curcontext" environ e cmd cpp ret=1
+local -a context state line args _comp_priv_prefix
 local -A opt_args
 
 zstyle -a ":completion:${curcontext}:" environ environ
@@ -20,20 +18,21 @@ args=(
   '(-g --group)'{-g+,--group=}'[run command as the specified group name or ID]:group:_groups'
   '(-)'{-h,--help}'[display help message and exit]'
   '(-h --host)'{-h+,--host=}'[run command on host]:host:_hosts'
-  '(-K --remove-timestamp)'{-K,--remove-timestamp}'[remove timestamp file completely]'
-  '(-k --reset-timestamp)'{-k,--reset-timestamp}'[invalidate timestamp file]'
+  '(-k --reset-timestamp -K --remove-timestamp -N --no-update)'{-K,--remove-timestamp}'[remove timestamp file completely]'
+  '(-k --reset-timestamp -K --remove-timestamp -N --no-update)'{-k,--reset-timestamp}'[invalidate timestamp file]'
   \*{-l,--list}"[list user's privileges or check a specific command]"
   '(-n --non-interactive)'{-n,--non-interactive}'[non-interactive mode, no prompts are used]'
+  '(-k --reset-timestamp -K --remove-timestamp -N --no-update)'{-N,--no-update}"[don't update user's cached credentials]"
   '(-p --prompt)'{-p+,--prompt=}'[use the specified password prompt]:prompt'
   '(-R --chroot)'{-R+,--chroot=}'[change the root directory before running command]:directory:_directories'
   '(-r --role)'{-r+,--role=}'[create SELinux security context with specified role]: :_selinux_roles'
   '(-S --stdin)'{-S,--stdin}'[read password from standard input]'
   '(-t --type)'{-t+,--type=}'[create SELinux security context with specified type]: :_selinux_types'
   '(-T --command-timeout)'{-T+,--command-timeout=}'[terminate command after specified time limit]:timeout'
-  '(-U --other-user)'{-U+,--other-user=}'[in list mode, display privileges for user]:user:_users'
+  '(-U --other-user -v --validate)'{-U+,--other-user=}'[in list mode, display privileges for user]:user:_users'
   '(-u --user)'{-u+,--user=}'[run command (or edit file) as specified user]:user:_users'
   '(-)'{-V,--version}'[display version information and exit]'
-  '(-v --validate)'{-v,--validate}"[update user's timestamp without running a command]"
+  '(-v --validate -U --other-user *)'{-v,--validate}"[update user's timestamp without running a command]"
 )
 
 # Does -e appears before the first word that doesn't begin with a hyphen?
@@ -45,10 +44,6 @@ if [[ $service = sudoedit ]] || (( $words[(i)-e] < $words[(i)^(*sudo|-[^-]*)] ))
   args=( -A "-*" $args '!(-V --version -h --help)-e' '*:file:_files' )
 else
   cmd="$words[1]"
-  cpp='_comp_priv_prefix=(
-    $cmd -n
-    ${(kv)opt_args[(I)(-[ugHEP]|--(user|group|set-home|preserve-env|preserve-groups))]}
-  )'
   args+=(
     '(-e --edit 1 *)'{-e,--edit}'[edit files instead of running a command]' \
     '(-s --shell)'{-s,--shell}'[run shell as the target user; a command may also be specified]' \
@@ -58,9 +53,40 @@ else
     '(-E -i --login -s --shell -e --edit)--preserve-env=-[preserve user environment when running command]::environment variable:_sequence _parameters -g "*export*"' \
     '(-H --set-home -i --login -s --shell -e --edit)'{-H,--set-home}"[set HOME variable to target user's home dir]" \
     '(-P --preserve-groups -i -login -s --shell -e --edit)'{-P,--preserve-groups}"[preserve group vector instead of setting to target's]" \
-    "(-)1: :{ $cpp; _command_names -e }"
-    "*:: :{ $cpp; _normal }"
+    '*:: :->normal'
+  )
+fi
+
+_arguments -s -S $args && ret=0
+
+if [[ $state = normal ]]; then
+  _comp_priv_prefix=(
+    $cmd -n
+    ${(kv)opt_args[(I)(-[ugHEP]|--(user|group|set-home|preserve-env|preserve-groups))]}
   )
+  if (( $+opt_args[-l] || $+opt_args[--list] )); then
+    _normal -p $service
+    return
+  fi
+  while [[ $words[1] = *=* ]]; do
+    if (( CURRENT == 1 )); then
+      compstate[parameter]="${PREFIX%%\=*}"
+      compset -P 1 '*='
+      _value && ret=0
+      return ret
+    fi
+    shift words
+    (( CURRENT-- ))
+  done
+  if (( CURRENT == 1 )); then
+    curcontext="${curcontext%:*:*}:-command-:"
+    _alternative \
+      'commands:: _command_names -e' \
+      'options:option:(-s --shell -l --login)' \
+      'parameters: :_parameters -g "*export*~*readonly*" -qS=' && ret=0
+  else
+    _normal
+  fi
 fi
 
-_arguments -s -S $args
+return ret
diff --git a/Completion/Unix/Command/_sysctl b/Completion/Unix/Command/_sysctl
index 0416ca05e..442953c4d 100644
--- a/Completion/Unix/Command/_sysctl
+++ b/Completion/Unix/Command/_sysctl
@@ -28,6 +28,12 @@ case $OSTYPE in
       '(- :)'{-V,--version}'[display version info and exit]' \
       '*:sysctl variable:_files -W /proc/sys'
   ;;
+  freebsd<14->.*)
+    args+=(
+      '-F[print the format of the variable]'
+      '(-N)-l[show the length of variables along with their values]'
+    )
+  ;|
   freebsd<11->.*)
     args+=(
       '-B[specify buffer size for reading]:buffer size'
@@ -53,7 +59,7 @@ case $OSTYPE in
       '-d[print the description of the variable instead of its value]' \
       '(-N -n)-e[separate name and value with =]' \
       "-i[silently exit if variable doesn't exist]" \
-      '(-n)-N[show only variable names]' \
+      '(-n -l)-N[show only variable names]' \
       '(-N)-n[show only variable values]' \
       '(-x)-o[show opaques as well (values suppressed)]' \
       '-q[suppress some warnings]' \
diff --git a/Completion/Unix/Command/_tail b/Completion/Unix/Command/_tail
index e54a0b06e..f8006abbc 100644
--- a/Completion/Unix/Command/_tail
+++ b/Completion/Unix/Command/_tail
@@ -16,6 +16,7 @@ if _pick_variant gnu=GNU unix --version; then
     '(-q --quiet --silent -v --verbose)'{-q,--quiet,--silent}'[never output headers giving file names]'
     '(-q --quiet --silent -v --verbose)'{-v,--verbose}'[always output headers giving file names]'
     '--retry[keep trying to open a file even when it becomes inaccessible]'
+    '(-z --zero-terminated)'{-z,--zero-terminated}'[line delimiter is NUL, not newline]'
     '(- *)--help[display help and exit]'
     '(- *)--version[output version information and exit]'
   )
diff --git a/Completion/Unix/Command/_tar b/Completion/Unix/Command/_tar
index f9901c0c9..1cabd9713 100644
--- a/Completion/Unix/Command/_tar
+++ b/Completion/Unix/Command/_tar
@@ -158,7 +158,7 @@ elif [[ ( "$_tar_cmd" = *[xt]* || -n $del ) && -n "$tf" ]]; then
   fi
 
   if [[ $tf != $_tar_cache_name && -f $tf ]]; then
-    _tar_cache_list=("${(@f)$($words[1] $largs $tf)}")
+    _tar_cache_list=("${(@f)$($words[1] ${words[(r)--force-local]} $largs $tf)}")
     _tar_cache_name=$tf
   fi
 
diff --git a/Completion/Unix/Command/_tex b/Completion/Unix/Command/_tex
index f1428c494..1a70b5058 100644
--- a/Completion/Unix/Command/_tex
+++ b/Completion/Unix/Command/_tex
@@ -1,4 +1,4 @@
-#compdef tex latex slitex pdftex pdflatex jadetex pdfjadetex xetex=tex xelatex=latex latexmk
+#compdef tex latex slitex pdftex pdflatex jadetex pdfjadetex xetex=tex xelatex=latex latexmk lualatex
 
 _arguments : \
     '-enc[enable encTeX extensions]' \
diff --git a/Completion/Unix/Command/_tiff b/Completion/Unix/Command/_tiff
index ef12777de..1aeff3ff7 100644
--- a/Completion/Unix/Command/_tiff
+++ b/Completion/Unix/Command/_tiff
@@ -159,6 +159,7 @@ tiffinfo)
     '-f+[force fill order]:fill order:(lsb2msb msb2lsb)' \
     '-w[display raw data in words]' \
     '-z[enable strip chopping]' \
+    '-M+[set the memory allocation limit]:limit (MiB), 0 for unlimited' \
     '*:input TIFF file:_files -g "*.(#i)tif(|f)(-.)"' && ret=0
   ;;
 tiffmedian)
@@ -172,6 +173,7 @@ tiffmedian)
   ;;
 tiffsplit)
   _arguments \
+    '-M+[set the memory allocation limit]:limit (MiB), 0 for unlimited' \
     ':input file:_files -g "*.(#i)tif(|f)(-.)"' \
     ':output file prefix' && ret=0
   ;;
diff --git a/Completion/Unix/Command/_timeout b/Completion/Unix/Command/_timeout
index c041283ac..9c7f1a004 100644
--- a/Completion/Unix/Command/_timeout
+++ b/Completion/Unix/Command/_timeout
@@ -17,4 +17,4 @@ _arguments -S -A "-" $args \
   '(-s --signal)'{-s,--signal}'[specify the signal to send on timeout]:signal:_signals' \
   '(-k --kill-after)'{-k,--kill-after}'[followup first signal with SIGKILL if command persists after specified time]:time' \
   '1: :_numbers -f -u seconds duration :s:seconds m:minutes h:hours d:days' \
-  '*:::command:_normal'
+  '*:::command: _normal -p $service'
diff --git a/Completion/Unix/Command/_tmux b/Completion/Unix/Command/_tmux
index 844af58fc..b9c220f17 100644
--- a/Completion/Unix/Command/_tmux
+++ b/Completion/Unix/Command/_tmux
@@ -130,6 +130,8 @@ _tmux_aliasmap=(
     popup       display-popup
 
     # buffers
+    clearphist  clear-prompt-history
+    showphist   show-prompt-history
     clearhist   clear-history
     deleteb     delete-buffer
     lsb         list-buffers
@@ -143,7 +145,6 @@ _tmux_aliasmap=(
     if          if-shell
     lock        lock-server
     run         run-shell
-    info        server-info
     wait        wait-for
 )
 
@@ -267,6 +268,11 @@ _tmux-clear-history() {
   _arguments '-t+[specify target pane]:pane:__tmux-panes'
 }
 
+_tmux-clear-prompt-history() {
+  [[ -n ${tmux_describe} ]] && print "remove history of values for command line prompts" && return
+  _arguments '-T+[specify prompt type]:prompt type:(command search target window-target)'
+}
+
 _tmux-clock-mode() {
   [[ -n ${tmux_describe} ]] && print "enter clock mode" && return
   _arguments '-t+[specify target pane]:pane:__tmux-panes'
@@ -282,8 +288,7 @@ _tmux-command-prompt() {
     '-I+[specify list of initial inputs]:initial-text (comma-separated list)' \
     '-p+[specify list of prompts]:prompts (comma-separated list)' \
     '-t+[specify target client]:client:__tmux-clients' \
-    '(-W)-T[prompt is for a target - tab complete as appropriate]' \
-    '(-T)-W[prompt is for a window - tab complete as appropriate]' \
+    '-T+[specify prompt type]:prompt type:(command search target window-target)' \
     '*:::template:= _tmux'
 }
 
@@ -388,13 +393,19 @@ _tmux-display-panes() {
 _tmux-display-popup() {
   [[ -n ${tmux_describe} ]] && print "display a popup box over a pane" && return
   _arguments -s \
+    "-B[don't surround the popup by a border]" \
     '-C[close any popup on the client]' \
     '-c+[specify target client]:client:__tmux-clients' \
     '-d+[specify working directory for the command]:directory:_directories' \
+    '*-e[specify environment variable]:environment variable:_parameters -g "*export*" -qS=' \
     '-E[close the popup when the command exits]' \
+    '(-E)-EE[only close the popup when the command exits successfully]' \
     '-w+[specify width]:width' \
     '-h+[specify height]:height' \
+    '-s+[specify the style for the popup]:style:__tmux-style' \
+    '-S+[specify the style for the popup border]:style:__tmux-style' \
     '-t+[specify target pane]:pane:__tmux-panes' \
+    '-T+[specify popup title (supports formats)]:format:__tmux-formats' \
     '-x+[specify horizontal position]:position' \
     '-y+[specify vertical position]:position' \
     ':shell command:_cmdstring'
@@ -865,7 +876,11 @@ _tmux-send-prefix() {
     '-t+[specify target pane]:pane:__tmux-panes'
 }
 
-_tmux-server-info() {
+# NOTE: this is actually an alias for "show-messages -JT", but until the
+# aliasmap system in check-tmux-state can properly handle aliases which are
+# more complex than a single word, it's best to leave this here.
+
+_tmux-server-access() {
   [[ -n ${tmux_describe} ]] && print "show server information" && return
   __tmux-nothing-else
 }
@@ -1041,6 +1056,11 @@ _tmux-show-options() {
   return ret
 }
 
+_tmux-show-prompt-history() {
+  [[ -n ${tmux_describe} ]] && print "show status prompt history" && return
+  _arguments '-T+[specify prompt type]:prompt type:(command search target window-target)'
+}
+
 _tmux-show-window-options() {
   [[ -n ${tmux_describe} ]] && print "show window options" && return
   local curcontext="$curcontext" state line ret=1
@@ -1530,7 +1550,6 @@ function __tmux-option-guard() {
             'status-right-style:__tmux-style'
             'status-style:__tmux-style'
             'update-environment:MSG:string listing env. variables'
-            'user-keys:MSG:key'
             'visual-activity:DESC:on off'
             'visual-bell:DESC:on off'
             'visual-silence:DESC:on off'
@@ -1549,6 +1568,7 @@ function __tmux-option-guard() {
             'message-limit:'${int_guard}
             'set-clipboard:DESC:on off'
             'terminal-overrides:MSG:overrides string'
+            'user-keys:MSG:key'
         )
     else
         options=(
@@ -1633,6 +1653,7 @@ function __tmux-session-options() {
         'lock-after-time:lock sessions after N seconds'
         'lock-command:command to run for locking a client'
         'message-command-style:status line message command style'
+        'message-line:status message and command prompt position'
         'message-style:status line message style'
         'mouse:enable mouse support'
         'prefix:primary prefix key'
@@ -1643,6 +1664,8 @@ function __tmux-session-options() {
         'set-titles-string:format used by set-titles'
         'silence-action:set action on window silence when monitor-silence is on'
         'status:show or hide the status bar'
+        'status-bg:set the background style used by the status bar'
+        'status-fg:set the foreground style used by the status bar'
         'status-format:specify the format to be used for each line of the status line'
         'status-interval:interval (in seconds) for status bar updates'
         'status-justify:position of the window list in status bar'
@@ -1656,7 +1679,6 @@ function __tmux-session-options() {
         'status-right-style:style of right part of status line'
         'status-style:style status line'
         "update-environment:list of variables to be copied to a session's environment"
-        'user-keys:set list of user-defined key escape sequences'
         'visual-activity:display status line messages upon activity'
         'visual-bell:use visual bell instead of audible'
         'visual-silence:print a message if monitor-silence is on'
@@ -1701,20 +1723,28 @@ function __tmux-panes() {
     fi
 }
 
+
 function __tmux-server-options() {
     local -a tmux_server_options
     tmux_server_options=(
+        'backspace:set key sent by tmux for backspace'
         'buffer-limit:number of buffers kept per session'
         'command-alias:custom command aliases'
+        'copy-command:specify the default command when "copy-pipe" is called without arguments'
         'default-terminal:default terminal definition string'
         'escape-time:set timeout to detect single escape characters (in msecs)'
+        'editor:specify the command used when tmux runs an editor'
         'exit-unattached:make server exit if it has no attached clients'
         'exit-empty:exit when there are no active sessions'
+        'extended-keys:control whether tmux will send extended keys through to the terminal'
         'focus-events:request focus events from terminal'
         'history-file:tmux command history file name'
         'message-limit:set size of message log per client'
+        'prompt-history-limit:set the number of history items to save in the history file'
         'set-clipboard:use esc sequences to set terminal clipboard'
+        'terminal-features:set terminal features not detected by terminfo'
         'terminal-overrides:override terminal descriptions'
+        'user-keys:set list of user-defined key escape sequences'
     )
     _describe -t tmux-server-options 'tmux server option' tmux_server_options
 }
@@ -1768,14 +1798,25 @@ function __tmux-window-options() {
     local -a tmux_window_options
     tmux_window_options=(
         'aggressive-resize:aggressively resize windows'
+        'allow-passthrough:allow programs in the pane to bypass tmux'
         'allow-rename:allow programs to change window titles'
         'alternate-screen:allow alternate screen feature to be used'
-        'automatic-rename:attempt to automatically rename windows'
         'automatic-rename-format:format for automatic renames'
+        'automatic-rename:attempt to automatically rename windows'
         'clock-mode-colour:set clock colour'
         'clock-mode-style:set clock hour format (12/24)'
+        'copy-mode-current-match-style:set the style of the current search match in copy mode'
+        'copy-mode-mark-style:set the style of the line containing the mark in copy mode'
+        'copy-mode-match-style:set the style of search matches in copy mode'
+        'cursor-colour:set the colour of the cursor'
+        'cursor-style:set the style of the cursor'
+        'fill-character:set the character used to fill unused window areas'
         'main-pane-height:set height for main-* layouts'
         'main-pane-width:set width for main-* layouts'
+        'menu-style:set the menu style'
+        'menu-selected-style:set the selected menu item style'
+        'menu-border-style:set the menu border style'
+        'menu-border-lines:set the type of characters used for drawing menu borders'
         'mode-keys:mode to use in copy and choice modes (vi/emacs)'
         'mode-style:set window modes style'
         'monitor-activity:monitor window activity'
@@ -1786,11 +1827,20 @@ function __tmux-window-options() {
         'pane-active-border-style:style of border of active pane'
         'pane-base-index:integer at which to start indexing panes'
         'pane-border-format:set pane border format string'
+        'pane-border-indicators:set the indicator style for the active pane in a two pane split'
+        'pane-border-lines:set the type of characters used for drawing pane borders'
         'pane-border-status:turn border status off or set its position'
         'pane-border-style:style of border pane'
+        "pane-colours:an array used to configure tmux's colour palette"
+        'popup-border-lines:set the type of line used to draw popup borders'
+        "popup-border-style:set the style for the popup's border"
+        'popup-style:set the popup style'
         "remain-on-exit:don't destroy windows after the program exits"
+        "remain-on-exit-format:set the text shown at bottom of exited panes"
+        'scroll-on-clear:scroll previous contents into history before clear'
         'synchronize-panes:send input to all panes of a window'
         'window-active-style:style of active window'
+        'window-size:indicate how to automatically size windows'
         'window-status-activity-style:style of status bar activity tag'
         'window-status-bell-style:style of status bar bell tag'
         'window-status-current-format:set status line format for active window'
@@ -1799,7 +1849,6 @@ function __tmux-window-options() {
         'window-status-last-style:style of last window in status bar'
         'window-status-separator:separator drawn between windows in status line'
         'window-status-style:general status bar style'
-        'window-size:indicate how to automatically size windows'
         'window-style:style of window'
         'wrap-search:search wrap around at the end of a pane'
         'xterm-keys:generate xterm-style function key sequences'
diff --git a/Completion/Unix/Command/_todo.sh b/Completion/Unix/Command/_todo.sh
index 99b6bb695..fc84ee076 100644
--- a/Completion/Unix/Command/_todo.sh
+++ b/Completion/Unix/Command/_todo.sh
@@ -74,7 +74,7 @@ case $state in
     "replace:replace in NUMBER the TEXT."
     "remdup:remove exact duplicates from todo.txt."
     "report:adds the number of open and done items to report.txt."
-    "showhelp:list the one-line usage of all built-in and add-on actions."
+    "shorthelp:list the one-line usage of all built-in and add-on actions."
   )
   _describe -t todo-commands 'todo.sh command' cmdlist
   ;;
@@ -97,7 +97,7 @@ case $state in
 	;;
 	(replace)
 	item=${words[CURRENT-1]##0##}
-	compadd -Q -- "${(qq)$(todo.sh -p list "^[ 0]*$item " | sed '/^--/,$d')##<-> (\([A-Z]\) |)}"
+	compadd -Q -- "${(qq)$(todo.sh -p command list "^[ 0]*$item " | sed '/^--/,$d')##<-> (\([A-Z]\) |)}"
 	;;
       esac
     fi
@@ -144,7 +144,7 @@ case $nextstate in
   ;;
 
   (item)
-  itemlist=(${${(M)${(f)"$(todo.sh -p list | sed '/^--/,$d')"}##<-> *}/(#b)(<->) (*)/${match[1]}:${match[2]}})
+  itemlist=(${${(M)${(f)"$(todo.sh -p command list | sed '/^--/,$d')"}##<-> *}/(#b)(<->) (*)/${match[1]}:${match[2]}})
   _describe -t todo-items 'todo item' itemlist
   ;;
 
@@ -173,6 +173,6 @@ case $nextstate in
   # the + or @ (which may not even be there yet).
   compset -P '*[[:space:]]'
   _wanted search expl $projmsg \
-    compadd $(todo.sh lsprj) $(todo.sh lsc)
+    compadd $(todo.sh command listproj) $(todo.sh command listcon)
   ;;
 esac
diff --git a/Completion/Unix/Command/_touch b/Completion/Unix/Command/_touch
index 9b9144756..47190c579 100644
--- a/Completion/Unix/Command/_touch
+++ b/Completion/Unix/Command/_touch
@@ -28,7 +28,7 @@ case $variant in
   darwin*|dragonfly*|freebsd*|netbsd*)
     args+=( '-h[act on symbolic links themselves]' )
   ;|
-  dragonfly*|freebsd*|openbsd*|solaris*)
+  darwin*|dragonfly*|freebsd*|openbsd*|solaris*)
     args+=( '(-r -t 1)-d+[use specified date/time]:date/time' )
   ;|
   darwin*|dragonfly*|freebsd*|netbsd*|solaris*)
diff --git a/Completion/Unix/Command/_tr b/Completion/Unix/Command/_tr
index 1cfe1200a..6d899431c 100644
--- a/Completion/Unix/Command/_tr
+++ b/Completion/Unix/Command/_tr
@@ -16,6 +16,7 @@ case $variant in
       '(-c -C --complement)'{-c,-C,--complement}"${descr[-c]}"
       '(-d --delete 2)'{-d,--delete}"${descr[-d]}"
       '(-s --squeeze-repeats)'{-s,--squeeze-repeats}"${descr[-s]}"
+      '(-t --truncate-set1)'{-t,--truncate-set1}'[first truncate ARRAY1 to length of ARRAY2]'
       '(- 1 2)--help[display help information]'
       '(- 1 2)--version[display version information]'
     )
diff --git a/Completion/Unix/Command/_trash b/Completion/Unix/Command/_trash
new file mode 100644
index 000000000..bef6e5838
--- /dev/null
+++ b/Completion/Unix/Command/_trash
@@ -0,0 +1,57 @@
+#compdef trash
+
+local variant
+
+_pick_variant -r variant ali='(Rantakari|hasseg)' steven='(Steven|vanZyl)' other --version
+
+case $variant in
+  ali)
+    # The hidden options here are options to rm that trash silently (and
+    # undocumentedly) ignores. Some options are not made mutually exclusive where
+    # they technically could be, for compatibility with aliases, etc.
+    _arguments -s -S -A '-*' : \
+      '!-'{d,f,i,r,P,R,W} \
+      '(: * -F -l -v)-e[empty trash]' \
+      '-F[use Finder instead of system API]' \
+      '(: * -e -F -s -y)-l[list items in trash]' \
+      '(: * -F -l -v)-s[securely empty trash]' \
+      '-v[increase output verbosity]' \
+      '-y[skip confirmation prompts (with -e or -s)]' \
+      '*: :_files'
+    return
+    ;;
+  steven)
+    local trash_dir="${TRASH_D_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/Trash}/files"
+
+    local -a args=(
+      '(-v --verbose)'{-v,--verbose}'[print more information]'
+
+      + options
+      '(-d --dir)'{-d,--dir}'[remove empty directories]'
+      '(-r -R --recursive)'{-r,-R,--recursive}'[delete directories and their contents]'
+      '--rm[permanently delete files]'
+
+      + '(interactive)'
+      {-i,--interactive}'[ask before each deletion]'
+      {-I,--interactive-once}'[ask before deleting 3 or more files, or deleting recursively]'
+      {-f,--force}'[don'\''t prompt and ignore errors]'
+
+      + '(actions)'
+      '(options input info interactive)--list[list out the files in the trash]'
+      '(options input info interactive)--orphans[list orphaned files in the trash]'
+      '(options input info)--restore[restore specified file from the trash]:trashed file:_files -W "$trash_dir"'
+      '(options input info)--delete[delete specified file from the trash]:trashed file:_files -W "$trash_dir"'
+      '(options input info)--empty[empty the trash bin]'
+
+      + info
+      '(- *)'{-h,--help}'[display help information]'
+      '(- *)--version[output the version and exit]'
+
+      + input
+      '(actions)*: :_files'
+    )
+    _arguments -s -S : $args
+    return
+    ;;
+  *) _default ;;
+esac
diff --git a/Completion/Unix/Command/_truss b/Completion/Unix/Command/_truss
index b798f03cb..b69e174e6 100644
--- a/Completion/Unix/Command/_truss
+++ b/Completion/Unix/Command/_truss
@@ -16,7 +16,11 @@ args=(
 
 case $OSTYPE in
   solaris2.<11->)
-    args+=( '(-c)-A[include absolute timestamps in output]' )
+    args+=(
+      '(-c)-A[include absolute timestamps in output]'
+      '-I[interpret system calls to well-known rather than underlying names]'
+      '-N[report only system calls that returned an error]'
+    )
   ;|
   aix*|solaris*)
     args+=(
diff --git a/Completion/Unix/Command/_uniq b/Completion/Unix/Command/_uniq
index e123a94cd..479b3848d 100644
--- a/Completion/Unix/Command/_uniq
+++ b/Completion/Unix/Command/_uniq
@@ -25,7 +25,7 @@ if ! _pick_variant gnu=Free\ Soft unix --version; then
   if [[ "$OSTYPE" == (darwin|dragonfly|freebsd|openbsd)* ]]; then
     optchars+=i
   fi
-  [[ $OSTYPE = freebsd* ]] && optchars+=D
+  [[ $OSTYPE = (darwin|freebsd)* ]] && optchars+=D
   args=( ${(M)args:#(|\*)(|\(*\))-[$optchars]*} )
 fi
 
diff --git a/Completion/Unix/Command/_user_admin b/Completion/Unix/Command/_user_admin
index db1c977ad..d5a53af7c 100644
--- a/Completion/Unix/Command/_user_admin
+++ b/Completion/Unix/Command/_user_admin
@@ -12,7 +12,7 @@ case ${service%???}:${(M)service%???}:$OSTYPE in
       shells=( ${(M)commands:#*/(|[abckz]|tc|ba)sh} )
     fi
     args+=(
-      '(-D -c --commend)'{-c+,--comment=}'[comment]:comment'
+      '(-D -c --comment)'{-c+,--comment=}'[comment]:comment'
       '(-D -d --home -b --base-dir)'{-d+,--home=}"[specify home directory]:home directory:_directories -W /"
       '(-D -e --expiredate)'{-e+,--expiredate}'[specify expiration date]:expiration date (YYYY-MM-DD)'
       '(-D -f --inactive)'{-f+,--inactive=}'[specify inactive days]:inactive days'
@@ -41,6 +41,8 @@ case ${service%???}:${(M)service%???}:$OSTYPE in
       SYS_GID_MIN SYS_UID_MAX SYS_UID_MIN UID_MAX UID_MIN UMASK
     )
     args+=(
+      '--btrfs-subvolume-home[use BTRFS subvolume for home directory]'
+      '(-F --add-subids-for-system)'{-F,--add-subids-for-system}'[add entries to sub[ud]id even when adding a system user]'
       '(-l --no-log-init)'{-l,--no-log-init}"[don't add user to lastlog and faillog databases]"
       '(-m --create-home -M --no-create-home)'{-M,--no-create-home}"[don't create user's home directory, regardless of /etc/login.defs]"
       '(-N --no-user-group -U --user-group)'{-N,--no-user-group}"[don't create a group with the same name as the user]"
@@ -103,6 +105,7 @@ case ${service%???}:${(M)service%???}:$OSTYPE in
   user:mod:linux*)
     args+=(
       '(-a --append)'{-a,--append}'[add user to supplementary groups without removing from other groups]'
+      '(-r --remove)'{-r,--remove}'[remove user from supplementary groups without removing from other groups]'
       \*{-v,--add-subuids}'[add a range of subordinate uids]:uids (first-last)'
       \*{-V,--del-subuids}'[remove a range of subordinate uids]:uids (first-last)'
       \*{-w,--add-subgids}'[add a range of subordinate gids]:gids (first-last)'
@@ -118,9 +121,16 @@ case ${service%???}:${(M)service%???}:$OSTYPE in
   ;|
   user:*:linux*)
     args+=(
+      '(-b --badname)'{-b,--badname}"[don't check for bad names]"
       '(-U --unlock --lock -L -p)'{-L,--lock}"[lock user's password]"
       '(-U --unlock --lock -L -p)'{-U,--unlock}"[unlock user's password]"
-      '(-Z --selinux-user)'{-Z,--selinux-user}"[specify SELinux user for the user's login]:user"
+      '(-Z --selinux-user)'{-Z,--selinux-user}"[specify SELinux user for the user's login]:user:_selinux_users"
+      "--selinux-range[specify SELinux MLS range for the user's login]:range"
+    )
+  ;|
+  group:*:linux*)
+    args+=(
+      '(-U --users)'{-U+,--users=}'[specify users to add as members of the group]:user:_sequence _users'
     )
   ;|
   group:*)
@@ -164,6 +174,9 @@ case ${service%???}:${(M)service%???}:$OSTYPE in
       ':group:_groups'
     )
   ;|
+  group:mod:linux*)
+    args+=( '(-a --append)'{-a,--append}'[append the users mentioned by -U without removing existing members]' )
+  ;|
   ^*:linux*)
     args=( ${(R)args:#(|\*)(|\(*\))--*} )    # remove long options
   ;|
diff --git a/Completion/Unix/Command/_vmstat b/Completion/Unix/Command/_vmstat
index e05bc88bc..6db776e62 100644
--- a/Completion/Unix/Command/_vmstat
+++ b/Completion/Unix/Command/_vmstat
@@ -8,7 +8,7 @@ case $OSTYPE in
       '(-t --timestamp)'{-t,--timestamp}'[show timestamp]'
       '(-n --one-header)'{-n,--one-header}'[do not redisplay header]'
       '(-S --unit)'{-S+,--unit=}'[specify unit for displayed sizes]:unit prefix [K]:((k\:1000 K\:1024 m\:1000000 M\:1048576))'
-      '(-C --full-cache)'{-C,--full-cache}'[add further cache lines to main cache]'
+      '(-y --no-first)'{-y,--no-first}'[skip first line of output]'
       '1: :_guard "[0-9]#" "interval (seconds)"' '2:count'
       + '(action)' \
       '(- :)'{-h,--help}'[display help information]'
diff --git a/Completion/Unix/Command/_vorbis b/Completion/Unix/Command/_vorbis
index 6c94469f9..fca218a51 100644
--- a/Completion/Unix/Command/_vorbis
+++ b/Completion/Unix/Command/_vorbis
@@ -32,7 +32,6 @@ case $service in
       '(-q --quality)'{-q+,--quality=}'[set encoding quality]:quality:(0 1 2 3 4 5 6 7 8 9 10)' \
       '--resample=[resample input to the given sample rate before encoding]:sample rate (Hz)' \
       '--downmix[down mix input from stereo to mono]' \
-      '--scale=[set input scaling factor]:scaling factor' \
       '(-s --serial)'{-s+,--serial=}'[force a specific serial number in the output stream]:serial number' \
       "--discard-comments[don't copy comments from FLAC file to output Ogg Vorbis file]" \
       '--ignorelength[ignore the datalength in Wave headers]' \
@@ -74,10 +73,6 @@ case $service in
       '(-q --quiet -v --verbose)'{--quiet,-q}'[quiet mode]' \
       '(-q --quiet)*'{-v,--verbose}'[increase verbosity]' \
       '(- *)'{-V,--version}'[display version information]' \
-      \*{-c-,--config=-}'[specify config options]: :_values option
-        "default_device\:device"
-        "shuffle\:value\:(0 1)"
-        "repeat\:value\:(0 1)"' \
       '*:sound file or directory:->urls-or-files' && ret=0
   ;;
   ogginfo)
diff --git a/Completion/Unix/Command/_w b/Completion/Unix/Command/_w
index 69751c5e5..e82c84f57 100644
--- a/Completion/Unix/Command/_w
+++ b/Completion/Unix/Command/_w
@@ -1,6 +1,6 @@
 #compdef w
 
-local args
+local -a args
 
 case $OSTYPE in
   linux*)
@@ -11,7 +11,7 @@ case $OSTYPE in
       '(H -o --old-style -s --short)'{-o,--old-style}'[old style output format]'
       '(H -s --short -o --old-style)'{-s,--short}'[use short output format]'
       '(H -u --no-current)'{-u,--no-current}'[ignore the username while figuring out the current process and cpu times]'
-      '(H -n --no-truncat)'{-n,--no-truncat}'[non-truncated listing (large)]'
+      '(H -p --pids)'{-p,--pids}'[show process IDs]'
       + H
       '(-)--help[display help information]'
       '(-)'{-V,--version}'[display version information]'
diff --git a/Completion/Unix/Command/_watch b/Completion/Unix/Command/_watch
index fff3d56f6..e12add520 100644
--- a/Completion/Unix/Command/_watch
+++ b/Completion/Unix/Command/_watch
@@ -18,7 +18,10 @@ case $variant in
       '(-g --chgexit)'{-g,--chgexit}'[exit on command output change]' \
       '(-n --interval)'{-n+,--interval=}'[specify update interval]:update interval (seconds) [2]' \
       '(-p --precise)'{-p,--precise}'[run command at precise intervals]' \
+      '(-q --equexit)'{-q+,--equexit=}'[exit when output of command does not change for the given cycles]:cycles' \
+      '(-r --no-rerun)'{-r,--no-rerun}'[do not run the program on terminal resize]' \
       '(-t --no-title)'{-t,--no-title}'[disable header]' \
+      '(-w --no-wrap)'{-w,--no-wrap}'[disable line wrapping]' \
       '(-x --exec)'{-x,--exec}'[pass command to exec(2) instead of `sh -c`]' \
       '(-)*::: :->cmd' \
     && ret=0
@@ -31,7 +34,7 @@ case $variant in
     then
       _cmdstring && ret=0
     else
-      _normal && ret=0
+      _normal -p watch && ret=0
     fi
     ;;
   # watch(1) has completely different semantics on freebsd compared to linux, hence:
diff --git a/Completion/Unix/Command/_wc b/Completion/Unix/Command/_wc
index 49a03ba2c..a1897e289 100644
--- a/Completion/Unix/Command/_wc
+++ b/Completion/Unix/Command/_wc
@@ -13,6 +13,7 @@ if _pick_variant gnu=GNU unix --version; then
   args+=(
     '(*)--files0-from=[read NUL-terminated file list from specified file]:file:_files'
     '(-L --max-line-length)'{-L,--max-line-length}'[print longest line lengths]'
+    '--total=[when to print a line with total counts]:when:(auto always only never)'
   )
 else
   args=( -A "-*" "${(@)args:#(|\(*\))(|\*)--*}" )
diff --git a/Completion/Unix/Command/_wget b/Completion/Unix/Command/_wget
index 50fd7791a..acc8d5c6e 100644
--- a/Completion/Unix/Command/_wget
+++ b/Completion/Unix/Command/_wget
@@ -23,6 +23,7 @@ _arguments -C -s \
   '(--config)--no-config' '--rejected-log=:file:_files' \
   '(--tries -t)'{--tries=,-t+}'[set number of retries]:number of retries' \
   '--retry-connrefused[retry even if connection is refused]' \
+  '--retry-on-host-error[consider host errors as non-fatal, transient errors]' \
   '--retry-on-http-error=[specify list of HTTP errors to retry]:http error' \
   '(--output-document -O)'{--output-document=,-O+}'[specify file to write documents to]:output file:_files' \
   '(--continue -c)'{--continue,-c}'[continue getting an existing file]'  \
@@ -98,7 +99,7 @@ _arguments -C -s \
   '--content-disposition[honor the Content-Disposition header when choosing local file names]'  \
   '--content-on-error[output received content on server errors]' \
   "--auth-no-challenge[send basic HTTP authentication without first waiting for server's challenge]" \
-  '--secure-protocol=[choose secure protocol]:protocol:(SSLv2 SSLv3 TLSv1 TLSv1_1 TLSv1_2 PFS)' \
+  '--secure-protocol=[choose secure protocol]:protocol:(SSLv2 SSLv3 TLSv1 TLSv1_1 TLSv1_2 TLSv1_3 PFS)' \
   --https-only \
   "--no-check-certificate[don't check the server certificate]" \
   '--certificate=[specify client certificate]:client certificate file:_files' \
diff --git a/Completion/Unix/Command/_xargs b/Completion/Unix/Command/_xargs
index 8e23a04bb..30e5f8daa 100644
--- a/Completion/Unix/Command/_xargs
+++ b/Completion/Unix/Command/_xargs
@@ -25,7 +25,7 @@ case $variant in
       '-R[specify maximum arguments that -I will replace in]:replacements'
     )
   ;|
-  freebsd*|netbsd*|dragonfly*)
+  darwin*|freebsd*|netbsd*|dragonfly*)
     args+=(
       '-S[space that -I can use for replacements]:size (bytes) [255]'
     )
diff --git a/Completion/Unix/Command/_xfconf-query b/Completion/Unix/Command/_xfconf-query
new file mode 100644
index 000000000..fa535401f
--- /dev/null
+++ b/Completion/Unix/Command/_xfconf-query
@@ -0,0 +1,33 @@
+#compdef xfconf-query
+local curcontext="$curcontext" state state_descr line ret=1
+typeset -A opt_args
+
+_arguments -C -s -w : \
+  '(-c --channel)'{-c,--channel}'[select channel to query/modify]:channel:( ${$(xfconf-query -l)\:#Channels\:} )' \
+  '(-p --property)'{-p,--property}'[select property to query/modify]:property:->property' \
+  '(-v --verbose)'{-v,--verbose}'[print property and value (with -l/-m)]' \
+  '(-t --type)'{-t,--type}'[specify the property value type]:type:(empty string bool {,u}int{,16,64} double array {,u}char float)' \
+  '(-R --recursive)'{-R,--recursive}'[recursively reset properties (with -r)]' \
+  + '(operations)' \
+  {-h,--help}'[show help options]' \
+  {-V,--version}'[show version information]' \
+  {-s,--set}'[define the value of a property]:value' \
+  {-l,--list}'[list properties or channels]' \
+  {-n,--create}'[create a new property]:new property name' \
+  {-r,--reset}'[reset property]' \
+  {-T,--toggle}'[invert boolean property]' \
+  {-m,--monitor}'[monitor a channel for property changes]' && return
+
+case $state in
+  property)
+    # if -c/--channel is currently on the line, use it to complete an property.
+    if [[ -v opt_args[(i)-(c|-channel)] ]]; then
+      local expl
+      _wanted properties expl property compadd "$@" -- ${(f)"$(xfconf-query -c ${(v)opt_args[(i)-(c|-channel)]} -l)"} && ret=0
+    else # just display a message
+      _message -e properties property && ret=0
+    fi
+  ;;
+esac
+
+return ret
diff --git a/Completion/Unix/Command/_xmlsoft b/Completion/Unix/Command/_xmlsoft
index 08b123e54..b8cf92700 100644
--- a/Completion/Unix/Command/_xmlsoft
+++ b/Completion/Unix/Command/_xmlsoft
@@ -40,6 +40,7 @@ case $service in
       '--maxdepth[increase the maximum depth]:depth' \
       '--maxvars[increase the maximum variables]:variables' \
       '--maxparserdepth[increase the maximum parser depth]:depth' \
+      '--huge[relax hardcoded limits of the parser]' \
       '--seed-rand[initialise random number generator]:seed' \
       '--html[input document is an HTML file]' \
       '--encoding[the input document character encoding]:encoding:(${encoding[@]})' \
diff --git a/Completion/Unix/Command/_xxd b/Completion/Unix/Command/_xxd
index 31d26ab64..e9015a081 100644
--- a/Completion/Unix/Command/_xxd
+++ b/Completion/Unix/Command/_xxd
@@ -24,7 +24,7 @@ arguments=(
   # output options
   '(-b -bits            -i -include -p -postscript -plain -ps -r -revert -u -uppercase)'{-b,-bits}'[output in binary digits, rather than hex]'
   '(         -E -EBCDIC -i -include -p -postscript -plain -ps -r -revert              )'{-E,-EBCDIC}'[print human-readable part in EBCDIC rather than ASCII]'
-  '(-i -include -p -postscript -plain -ps -r -revert)'{-e,-endian}'[little-endian dump]'
+  '(-i -include -p -postscript -plain -ps -r -revert)-e[little-endian dump]'
   '(-b -bits -E -EBCDIC -i -include -p -postscript -plain -ps -r -revert              )'{-i,-include}'[output in C include file style]'
   '(-b -bits -E -EBCDIC -i -include -p -postscript -plain -ps -C -capitalize          )'{-p,-postscript,-plain,-ps}'[read or write a plain hexdump (no line numbers or ASCII rendering)]'
 
@@ -35,12 +35,14 @@ arguments=(
   '(- :)'{-v,-version}'[show program version]'
   '*'{-a,-autoskip}"[a single '*' replaces runs of NUL (toggleable)]"
   '(-C -capitalize)'{-C,-capitalize}'[capitalize variable names in C include file style]'
-  {-c+,-cols}'[specify number of octets per line]: :_guard "[0-9a-fA-Fx]#" "number of octets per line"'
-  {-g+,-groupsize}'[specify the number of octets per group]: :_guard "[0-9]#" "number of octets per group"'
-  {-l+,-len}'[specify number of octets to output]: :_guard "[0-9]#" "number of octets to output"'
-  {-o+,-offset}'[add specified offset to displayed file position]:offset'
+  '(-c -cols)'{-c+,-cols}'[specify number of octets per line]: :_guard "(0x|)[0-9a-fA-Fx]#" "number of octets per line"'
+  '(-g -groupsize)'{-g+,-groupsize}'[specify the number of octets per group]: :_guard "(0x|)[0-9a-fA-F]#" "number of octets per group"'
+  '(-l -len)'{-l+,-len}'[specify number of octets to output]: :_guard "(0x|)[0-9a-fA-F]#" "number of octets to output"'
+  '(-n -name)'{-n+,-name}'[override the variable name output when -i is used]:variable name'
+  '(-o -offset)'{-o+,-offset}'[add specified offset to displayed file position]:offset'
   '-d[show offset in decimal instead of hex]'
-  {-s,-skip,-seek}'[specify file offset to dump from]: :_guard "[0-9]#" "file offset to dump from (absolute or relative)"'
+  '-R+[colorize the output]:when:(always auto never)'
+  '(-s -skip -seek)'{-s+,-skip,-seek}'[specify file offset to dump from]: :_guard "(0x|)[0-9a-fA-F]#" "file offset to dump from (absolute or relative)"'
 
   ': :_files'
 )
diff --git a/Completion/Unix/Command/_xz b/Completion/Unix/Command/_xz
index a4dfea1f5..6e68e0f69 100644
--- a/Completion/Unix/Command/_xz
+++ b/Completion/Unix/Command/_xz
@@ -22,20 +22,20 @@ case "$service" in
     '(I)*'{-v,--verbose}'[verbose mode]' \
     '(I * --files --files0)--files=-[read list of files to process from file]::file:_files' \
     '(I * --files --files0)--files0=-[read null terminated list of files to process from file]::file:_files' \
-    '(I -F --format)'{-F,--format}'=[specify file format]:format:(auto xz lzma raw)' \
+    '(I -F --format)'{-F+,--format=}'[specify file format]:format:(auto xz lzma lzip raw)' \
     '(I -T --threads)'{-T+,--threads=}'[use specified number of threads]:threads [1]' \
-    '(I -M --memlimit --memory)'{-M+,--memlimit=,--memory=}'[set memory usage limit]:memory usage' \
+    '(I -M --memlimit --memory)'{-M+,--memlimit=,--memory=}'[set memory usage limit]: :_numbers -u bytes "memory limit" KiB MiB GiB %\:percentage\ of\ available\ RAM' \
     '(I)--no-adjust[give error if settings exceed memory limit]' \
     '(I -Q --no-warn)'{-Q,--no-warn}'[make warnings not affect exit status]' \
     + 'comp' \
     "(I decomp)"{-z,--compress}'[compress]' \
     '(I decomp -e --extreme)'{-e,--extreme}'[try to improve compression ratio by using more CPU time]' \
     '(I decomp -S --suffix)'{-S+,--suffix=}'[use specified suffix for compressed files]:suffix [.xz]' \
-    '(I decomp -C --check)'{-C,--check}'=[integrity check type]:check type:(none crc32 crc64 sha256)' \
+    '(I decomp -C --check)'{-C+,--check=}'[integrity check type]:check type:(none crc32 crc64 sha256)' \
     '(I decomp)--block-size=[start a new .xz block after specified bytes of input]:size' \
     '(I decomp)--block-list=[start a new .xz block after specified intervals of uncompressed data]:size' \
     '(I decomp)--flush-timeout=[specify maximum time between flushing of output]:time (ms) [0]' \
-    '(I decomp)--memlimit-compress=[set memory usage limit for compression]:memory usage' \
+    '(I decomp)--memlimit-compress=[set memory usage limit for compression]: :_numbers -u bytes "memory limit" KiB MiB GiB %\:percentage\ of\ available\ RAM' \
     + 'decomp' \
     '(I comp level filters)'{-d,--decompress}'[decompress]' \
     '(I comp level filters)'{-t,--test}'[test compressed file integrity]' \
@@ -43,7 +43,8 @@ case "$service" in
     "(I comp level filters)--ignore-check[don't verify integrity when decompressing]" \
     '(I comp level filters)--single-stream[decompress only the first stream]' \
     "(I comp level filters)--no-sparse[don't create sparse files when decompressing]" \
-    '(I comp level filters)--memlimit-decompress=[set memory usage limit for decompression]:memory usage' \
+    '(I comp level filters)--memlimit-decompress=[set memory usage limit for decompression]: :_numbers -u bytes "memory limit" KiB MiB GiB %\:percentage\ of\ available\ RAM' \
+    '(I comp level filters)--memlimit-mt-decompress=[set memory usage limit for multi‐threaded decompression]: :_numbers -u bytes "memory limit" KiB MiB GiB %\:percentage\ of\ available\ RAM' \
     + '(I)' \
     '(* comp decomp level filters common)--info-memory[display amount of RAM and memory usage limits]' \
     '(- *)'{-h,--help}'[display help message]' \
@@ -52,7 +53,7 @@ case "$service" in
     + '(level)' \
     '(I filters decomp)-'{-best,-fast,1,2,3,4,5,6,7,8,9} \
     + filters \
-    '(I level decomp --extreme)'--{x86,powerpc,ia64,arm,armthumb,sparc}=-'[add a branch/call/jump filter]::option:->bcj-options' \
+    '(I level decomp --extreme)'--{x86,powerpc,ia64,arm,armthumb,arm64,sparc}=-'[add a branch/call/jump filter]::option:->bcj-options' \
     '(I level decomp --extreme)'--lzma{1,2}=-'[add lzma filter]::option:->lzma-options' \
     '(I level decomp --extreme)--delta=-[add delta filter]::option:->delta-options' && ret=0
   ;;
@@ -64,10 +65,10 @@ case $state in
     [[ -n ${(k)opt_args[(i)decomp*]} ]] && unset decompress
     if [[ -z "$decompress" ]]; then
       _description files expl 'compressed file'
-      _files "$expl[@]" -g '*.(xz|txz|lzma|tlz)(-.)' && return
+      _files "$expl[@]" -g '*.(xz|txz||lz|lzma|tlz)(-.)' && return
     else
       _description files expl 'file to compress'
-      _files "$expl[@]" -g '^*.(xz|txz|lzma|tlz)(-.)' && return
+      _files "$expl[@]" -g '^*.(xz|txz|lz|lzma|tlz)(-.)' && return
     fi
   ;;
   lzma-options)
diff --git a/Completion/Unix/Command/_zfs b/Completion/Unix/Command/_zfs
index be4a64b33..c09435a1f 100644
--- a/Completion/Unix/Command/_zfs
+++ b/Completion/Unix/Command/_zfs
@@ -1,7 +1,8 @@
-#compdef zfs zdb zpool
+#compdef zfs zdb zpool zstream
 
 local curcontext="$curcontext" implementation nm="$compstate[nmatches]"
 local -a state curstate line state_descr expl alts args
+local -a devices features
 typeset -A opt_args val_args
 local MATCH MBEGIN MEND
 local -a subcmds
@@ -13,6 +14,7 @@ local -a ds_types sum_algorithms comp_algorithms dedup_algorithms
 
 local -a ds_propnames ro_ds_props rw_ds_props ci_ds_props # dataset properties
 local -a po_propnames ro_po_props rw_po_props ci_po_props # pool properties
+local -a ro_vdev_props rw_vdev_props
 
 _pick_variant -r implementation -c 'zpool upgrade -v' openzfs='This system supports ZFS pool feature flags' solaris
 
@@ -98,14 +100,32 @@ rw_ds_props=(
   'volsize:size:_numbers -M "m:{a-zA-Z}={A-Za-z}" -u bytes size :B {k,M,G,T,P,E,Z}{,B}'
 )
 
+ro_vdev_props=(
+  capacity state guid asize psize ashift size free allocated expandsize
+  fragmentation parity devid physpath encpath fru parent children numchildren
+  read_errors write_errors checksum_errors initialize_errors
+  null_ops read_ops write_ops free_ops claim_ops trim_ops
+  null_bytes read_bytes write_bytes free_bytes claim_bytes trim_bytes
+  removing
+)
+rw_vdev_props=(
+  {checksum,io}'_n:number of errors' {checksum,io}'_t:threshold (seconds)'
+  {comment,bootsize}:value
+  {allocating,failfast}':value:(on off)'
+  'path:device path:_files -g "*(-%)" -P / -W /'
+)
+
 case $service:$implementation in
   *:openzfs)
     ds_types+=( bookmark )
-    sum_algorithms+=( noparity sha512 skein edonr )
+    sum_algorithms+=( noparity sha512 skein edonr blake3 )
     comp_algorithms+=( zstd zstd-{1..19} zstd-fast zstd-fast-{{1..9}{,0},100,500,1000} )
-    dedup_algorithms+=( {sha512,skein}{,\,verify} edonr,verify )
+    dedup_algorithms+=( {sha512,skein,blake3}{,\,verify} edonr,verify )
     share_rw_properties=( sharesmb:option sharenfs:option )
     ro_po_props+=(
+      'bcloneratio[block cloning ratio for saved space]'
+      'bclonesaved[amount of storage spared by use of block cloning]'
+      'bcloneused[amount of storage used by cloned blocks]'
       'expandsize[uninitialized space within the pool]'
       'fragmentation[amount of fragmentation in the pool]'
       'freeing[amount of space remaining to be reclaimed]'
@@ -119,6 +139,7 @@ case $service:$implementation in
       'autotrim[periodically trim recently freed space]:value:(on off)'
       'comment[text string that is available even if the pool becomes faulted]:value'
       'multihost[perform pool activity check during import]:value:(on off)'
+      'feature@'
     )
     rw_ds_props+=(
       'aclmode:value:(discard groupmask passthrough restricted)'
@@ -139,7 +160,8 @@ case $service:$implementation in
     )
     ro_ds_props+=(
       createtxg clones filesystem_count guid logicalreferenced logicalused
-      receive_resume_token refcompressratio snapshot_count volblocksize written
+      receive_resume_token refcompressratio snapshot_count snapshots_changed
+      volblocksize written
     )
     delegatable_perms=(
       bookmark load-key change-key userobjquota userobjused groupobjquota
@@ -257,6 +279,9 @@ case $service:$implementation in
       list offline online reguid remove replace scrub set split status upgrade
     )
   ;;
+  zstream:*)
+    subcmds+=( dump decompress redup token recompress )
+  ;;
 esac
 
 case $OSTYPE in
@@ -270,7 +295,7 @@ case $OSTYPE in
   linux-gnu)
     rw_ds_props+=( 'relatime:value:(on off)' )
     ci_ds_props+=(
-      {,fs,def,root}'context:SELinux context:_selinux_contexts'
+      {,fs,def,root}'context:SELinux context:_selinux_contexts -a file_type'
     )
   ;;
 esac
@@ -294,9 +319,8 @@ ci_ds_props+=( $rw_ds_props )
 ds_propnames=( ${rw_ds_props%%:*} )
 po_propnames=( ${ro_po_props%%:*} ${ci_po_props%%:*} ${rw_po_props%%:*} )
 
-
 case $service in
-  zfs|zpool)
+  zfs|zpool|zstream)
     _arguments -C -A "-*" \
       '-?[display usage information]' \
       '*::command:->subcmd' && return 0
@@ -633,7 +657,9 @@ case $service:$words[1] in
         '(-e --embed)'{-e,--embed}'[more compact stream for blocks stored with the embedded_data feature]'
         '(-c --compressed)'{-c,--compressed}'[more compact stream for compressed blocks]'
         '(-h --holds)'{-h,--holds}'[send snapshot holds]'
-        '-V[set the process title to a per-second report of how much data has been send]'
+        '(-V --proctitle)'{-V,--proctitle}'[set the process title to a per-second report of how much data has been sent]'
+        \*{-X,--exclude}'[exclude datasets (with -R)]:dataset:_sequence _zfs_dataset -t fs'
+        '(-s --skip-missing)'{-s,--skip-missing}'[continue even when snapshots missing in the hierarchy]'
         '-t[create a send stream that resumes an interrupted receive]:resume token'
         '(-w --raw)'{-w,--raw}'[keep encrypted data exactly as it exists on disk]'
         - redact
@@ -763,10 +789,10 @@ case $service:$words[1] in
   zfs:holds)
     [[ $implementation = openzfs ]] && args=(
       '-H[suppress printing of headers, tab-delimit columns]'
+      '-p[use (parsable) numeric output for timestamps]'
     )
     [[ $OSTYPE = freebsd<-12>.* ]] && args+=(
       # features were lost with the openzfs rebase
-      '-p[use exact (parsable) numeric output]'
       '(-r)-d+[depth]:value'
     )
     _arguments -A "-*" -S $args \
@@ -789,6 +815,9 @@ case $service:$words[1] in
       '-N[enumerate new child datasets (with -r)]'
       '(1 -e)-E[show difference from empty]'
     )
+    [[ $implementation = openzfs ]] && args=(
+      "-h[don't"' \\0ooo-escape non-ASCII paths]'
+    )
     _arguments -A "-*" -S $args \
       '-F[add column for filetype character, similar to ls(1)]' \
       '-H[suppress printing of headers and arrows, tab-delimit columns]' \
@@ -981,8 +1010,10 @@ case $service:$words[1] in
       '-H[suppress headers and tab-delimit fields]' \
       '-p[display numbers in parseable (exact) values]' \
       '-o+[specify fields to display]: : _values -s , field name property value source' \
-      ':property:_values -s , "property" $po_propnames' \
-      '*:pool:_zfs_pool'
+      ':property:_values -s , "property" $po_propnames ${ro_vdev_props%:*}' \
+      ':pool:_zfs_pool' \
+      '::vdev:->pool-vdevs-all' \
+      '*:pool:_zfs_pool -F line'
   ;;
 
   zpool:history)
@@ -1030,9 +1061,10 @@ case $service:$words[1] in
     _arguments -A "-*" -S \
       '(-s --suspend -c --cancel)'{-c,--cancel}'[cancel initializing on specified devices]' \
       '(-s --suspend -c --cancel)'{-s,--suspend}'[suspend initializing on specified devices]' \
+      '(-u --uninit)'{-u,--uninit}'[clear initialization state on specified devices]' \
       '(-w --wait)'{-w,--wait}'[wait until devices have finished initializing before returning]' \
       ':pool:_zfs_pool' \
-      '*:device:pool-devices'
+      '*:device:->pool-devices'
   ;;
 
   zpool:iostat)
@@ -1165,6 +1197,7 @@ case $service:$words[1] in
     [[ $implementation = openzfs ]] && args=(
       '(-s)-p[pause scrubbing]'
       '-w[wait until scrub has completed before returning]'
+      '-e[only scrub files with known data errors]'
     )
     _arguments -A "-*" -S $args \
       '(-p)-s[stop scrubbing]' \
@@ -1174,7 +1207,8 @@ case $service:$words[1] in
   zpool:set)
     _arguments -C -A "-*" -S \
       ':property:->set-pool-properties' \
-      '*:pool:_zfs_pool'
+      ':pool:_zfs_pool' \
+      ':vdev:->pool-vdevs'
   ;;
 
   zpool:split)
@@ -1235,7 +1269,7 @@ case $service:$words[1] in
 
   zpool:upgrade)
     _arguments -A "-*" -S \
-      '(- *)-v[display ZFS versions and descriptions]'
+      '(- *)-v[display ZFS versions and descriptions]' \
       "(-v)-V+[upgrade to given version]:version" \
       '(-v *)-a[upgrade all pools]' \
       '(-a -v)*:pool:_zfs_pool'
@@ -1251,6 +1285,36 @@ case $service:$words[1] in
       ':interval'
   ;;
 
+  zstream:dump)
+    _arguments -A "-*" -S \
+      '-C[suppress the validation of checksums]' \
+      '(-d)-v[print metadata for each record]' \
+      '(-v)-d[dump data contained in each record]' \
+      ':file:_files'
+  ;;
+
+  zstream:token)
+    _message -e tokens 'resume token'
+  ;;
+
+  zstream:decompress)
+    _arguments -A "-*" -S \
+      '-v[print summary of decompressed records]' \
+      '*:offset'
+  ;;
+
+  zstream:redup)
+    _arguments -A "-*" -S \
+      '-v[print summary of converted records]' \
+      ':file:stream file'
+  ;;
+
+  zstream:recompress)
+    _arguments -A "-*" -S \
+      '-l+[specify compression level]:level' \
+      '*:algorithm:compadd -a comp_algorithms'
+  ;;
+
   *)
     _default
   ;;
@@ -1259,6 +1323,7 @@ esac
 while (( $#state )); do
   curstate=$state
   state=()
+  devices=()
   case $curstate in
     virtual-devices)
       local -a vdevtypes
@@ -1278,8 +1343,15 @@ while (( $#state )); do
       _alternative $alts 'file-vdevs:file vdev:_files -W / -P /'
     ;;
 
+    pool-vdevs-all) devices=( all-vdevs ) ;&
+    pool-vdevs) # same as pool-devices but on OpenZFS 2.2+ only features
+      # path field is also valid
+      devices+=( $(_call_program devices zpool get -H -o name state $line[CURRENT-2] all-vdevs) )
+      _description devices expl "$state_descr"
+      compadd "$expl[@]" -a devices
+    ;;
+
     pool-devices)
-      local -a devices
       devices=( ${${${(M)${(f)"$(_call_program devices zpool status $line[1])"}:#$'\t' *}##[[:blank:]]#}%%[[:blank:]]*} )
       if (( $#devices )); then
         _description devices expl "$state_descr"
@@ -1321,12 +1393,13 @@ while (( $#state )); do
     create-properties) args=( $ci_ds_props ) ;|
     set-properties) args=( $rw_ds_props ) ;|
     newpool-properties) args=( $rw_po_props $ci_po_props ) ;|
-    set-pool-properties) args=( $rw_po_props ) ;|
+    set-pool-properties) args=( $rw_po_props $rw_vdev_props ) ;|
 
     *-properties)
       if compset -P 1 '(#m)*@'; then
         if compset -P 1 '*='; then
           case $MATCH in
+            *feature@) _wanted states expl state compadd active enabled disabled ;;
             *quota@) _alternative \
               'sizes: :_numbers -M "m\:{a-zA-Z}={A-Za-z}" -u bytes size \:B {k,M,G,T,P,E,Z}{,B}' \
               'properties:property:(none)'
@@ -1334,8 +1407,12 @@ while (( $#state )); do
           esac
         else
           case $MATCH in
-            user*@) _users -S = ;;
-            group*@) _groups -S = ;;
+            feature@)
+              features=( ${${${${${(f)"$(_call_program features zpool upgrade -v)"}[(r)---*,(R)VER *]}[2,-3]}:# *}%% *} )
+              _wanted features expl feature compadd -qS= -a features
+            ;;
+            user*@) _users -qS= ;;
+            group*@) _groups -qS= ;;
             project*@) _message -e projects project ;;
           esac
         fi
diff --git a/Completion/Unix/Type/_canonical_paths b/Completion/Unix/Type/_canonical_paths
index a8fbbb524..1444bc165 100644
--- a/Completion/Unix/Type/_canonical_paths
+++ b/Completion/Unix/Type/_canonical_paths
@@ -42,7 +42,8 @@ _canonical_paths_add_paths () {
     # ### Ideally, this codepath would do what the 'if' above does,
     # ### but telling compadd to pretend the "word on the command line"
     # ### is ${"the word on the command line"/$origpref/$canpref}.
-    matches+=(${${(M)files:#$canpref*}/$canpref/$origpref})
+    # ### The following approximates that.
+    matches+=(${(q)${(M)files:#$canpref*}/$canpref/$origpref})
   fi
 
   for subdir in $expref?*(@); do
diff --git a/Completion/Unix/Type/_diff_options b/Completion/Unix/Type/_diff_options
index dfa9889f2..03ea1d7fe 100644
--- a/Completion/Unix/Type/_diff_options
+++ b/Completion/Unix/Type/_diff_options
@@ -1,6 +1,6 @@
 #autoload
 
-local of ofwuc ouc oss ofwy ofwg ofwl cmd variant
+local of ofwuc ouc oss ofwy ofwg ofwl cmd variant ign
 local -a args
 
 cmd="$1"
@@ -25,7 +25,10 @@ _diff_palette() {
   return ret
 }
 
-if _pick_variant -r variant -c $cmd gnu=GNU unix -v || [[ $OSTYPE = freebsd<12->.* ]]; then
+if _pick_variant -r variant -c $cmd gnu=GNU unix -v ||
+  [[ $OSTYPE = (freebsd<12->|darwin<22->).* ]]; then
+  (( $#words > 2 )) && ign='!'
+
   # output formats
   of="-y --side-by-side -n --rcs -e -f --ed -q --brief -c -C --context -u -U \
   --unified --old-group-format --new-group-format --changed-group-format \
@@ -61,29 +64,28 @@ if _pick_variant -r variant -c $cmd gnu=GNU unix -v || [[ $OSTYPE = freebsd<12->
   --unchanged-group-format"
 
   if [[ $variant = gnu ]]; then
-    (( $#words > 2 )) || args+=(
-      '(-v --version)'{-v,--version}'[display version information]'
-      '--help[display usage information]'
-    )
     args+=(
       '(-H --speed-large-files)'{-H,--speed-large-files}'[assume large files and many small changes]'
       '(-E --ignore-tab-expansion)'{-E,--ignore-tab-expansion}'[ignore changes due to tab expansion]'
       '(-Z --ignore-trailing-space)'{-Z,--ignore-trailing-space}'[ignore white space at line end]'
-      "($ofwuc $oss -F --show-function-line)"{-F+,--show-function-line=}'[show the most recent line matching regex]:regex'
       "($ofwy $ouc)--left-column[output only left column of common lines]"
       "($ofwg $ouc $oss)--old-group-format=[set old group format]:old group format"
       "($ofwg $ouc $oss)--new-group-format=[set new group format]:new group format"
       "($ofwl $ouc $oss)--unchanged-line-format=[set unchanged line format]:unchanged line format"
-      '(--to-file)--from-file=[compare specified file to all operands]:from file:_files' \
-      '(--from-file)--to-file=[compare all operands to specified file]:to file:_files' \
-      '--color=-[use colors in output]::when [auto]:(never always auto)'
+      '(--to-file)--from-file=[compare specified file to all operands]:from file:_files'
+      '(--from-file)--to-file=[compare all operands to specified file]:to file:_files'
       '--palette=[specify colors to use]:color:_diff_palette'
+      "${ign}(1 2)-v[display version information]"
     )
   else
     args+=( '!--speed-large-files' )
+    if [[ $OSTYPE = darwin<22->.* ]]; then
+      args+=( '(-A --algorithm)'{-A+,--algorithm=}'[specify the algorithm to use]:algorithm:(myers patience stone)' )
+    fi
   fi
 
   _arguments -s $args \
+    '--color=-[use colors in output]::when [auto]:(never always auto)' \
     '(-i --ignore-case)'{-i,--ignore-case}'[case insensitive]' \
     '--ignore-file-name-case[ignore case when comparing file names]' \
     '!(--ignore-file-name-case)--no-ignore-file-name-case' \
@@ -99,6 +101,7 @@ if _pick_variant -r variant -c $cmd gnu=GNU unix -v || [[ $OSTYPE = freebsd<12->
     "($of $oss)-u[output a unified diff]" \
     "($ofwuc $oss)*"{-L+,--label=}'[set label to use instead of file name and timestamp]:label' \
     "($ofwuc $oss -p --show-c-function)"{-p,--show-c-function}'[show C function of each change]' \
+    "($ofwuc $oss -F --show-function-line)"{-F+,--show-function-line=}'[show the most recent line matching regex]:regex' \
     "($of $ouc $oss)"{-q,--brief}'[output only whether files differ]' \
     "($of $ouc $oss -e --ed)"{--ed,-e}'[output an ed script]' \
     "!($of $ouc $oss)--normal" \
@@ -127,39 +130,52 @@ if _pick_variant -r variant -c $cmd gnu=GNU unix -v || [[ $OSTYPE = freebsd<12->
     "($of $ouc)"{-y,--side-by-side}'[output in two columns]' \
     "($ofwy $ouc)--suppress-common-lines[don't output common lines]" \
     "($ofwy $ouc --width -W)"{--width=,-W+}'[set size of line]:number of characters per line' \
+    "${ign}(1 2)--version[display version information]" \
+    "${ign}(1 2)--help[display usage information]" \
     "$@"
 else
   of='-c -e -f'
   case $OSTYPE in
     openbsd*|solaris2.<9->)
       of+=' -u -U'
+    ;|
+    openbsd*|solaris*)
+      of+=' -n -C -D'
+    ;|
+    solaris*)
+      of+=' -h'
+    ;|
+    openbsd*)
+      of+=' -q'
+    ;|
+    # modifications to "$of" should be done above this line so that it is
+    # uniformly defined while constructing $args
+    openbsd*|solaris2.<9->)
       args+=(
-	"($of)-u[output a unified diff]"
-	"($of)-U+[output a unified diff]:lines of context"
+        "($of)-u[output a unified diff]"
+        "($of)-U+[output a unified diff]:lines of context"
       )
     ;|
     openbsd*|solaris*)
       args+=(
-	"($of)-C+[output a context diff]:lines of context"
-	"($of)-D+[output merged file with preprocessor directives]:preprocessor symbol"
-	'-i[case insensitive]'
-	'-l[long output format (paginate with pr(1))]'
-	'-s[report on identical files]'
-	'-t[expand tabs in output lines]'
+        "($of)-C+[output a context diff]:lines of context"
+        "($of)-D+[output merged file with preprocessor directives]:preprocessor symbol"
+        '-i[case insensitive]'
+        '-s[report on identical files]'
+        '-t[expand tabs in output lines]'
       )
     ;|
     solaris*)
-      of+=' -h -n'
       args+=(
-	'-w[ignore all white space]'
-	"($of)-h[do a fast, half-hearted job]"
-	"($of)-n[output a reversed ed script]"
+        '-w[ignore all white space]'
+        "($of)-h[do a fast, half-hearted job]"
+        "($of)-n[output a reversed ed script]"
         '-S+[set first file in comparison]:start with file:_files'
+        '-l[long output format (paginate with pr(1))]'
       )
     ;;
     openbsd*)
-      of+=' -n -q -u -C -D -U'
-      args=(
+      args+=(
         "($of)-n[output an rcsdiff(1)-compatible diff]"
         "($of)-q[only print a line when the files differ; does not produce a list of changes]"
         '-a[treat all files as ASCII text]'
@@ -173,7 +189,7 @@ else
         '-P[treat absent files in the second directory as if they were empty]'
         '-S[start a directory diff from a file name]:file name:_files'
         '*-X[exclude files and subdirectories whose basenames match lines in a file]:file name:_files'
-        '-x[exclude files and subdirectories whose basenames match a pattern]:pattern'
+        '*-x[exclude files and subdirectories whose basenames match a pattern]:pattern'
       )
     ;;
   esac
diff --git a/Completion/Unix/Type/_ldap_attributes b/Completion/Unix/Type/_ldap_attributes
new file mode 100644
index 000000000..0711cfbf1
--- /dev/null
+++ b/Completion/Unix/Type/_ldap_attributes
@@ -0,0 +1,27 @@
+#autoload
+
+local -a expl attrs
+
+# These come from dumping attributes from basic installations of both openldap
+# and FreeIPA and combining results. It is possible to have custom additions so
+# a definitive list is not possible Hence the use of -x with compadd.
+#
+attrs=(
+  associatedDomain authenticationMethod automountInformation automountKey
+  automountMapName bindTimeLimit cACertificate;binary cn dc defaultSearchBase
+  defaultServerList description displayName dn followReferrals gecos gidNumber
+  givenName homeDirectory info initials ipaCertIssuerSerial ipaCertSubject
+  ipaConfigString ipaKeyExtUsage ipaKeyTrust ipaNTSecurityIdentifier
+  ipaPublicKey ipaUniqueID ipHostNumber loginShell mail member memberUid
+  mepManagedBy nisDomain nisNetgroupTriple o objectClass objectClassMap ou
+  pwdAllowUserChange pwdAttribute pwdCheckQuality pwdExpireWarning
+  pwdFailureCountInterval pwdGraceAuthNLimit pwdInHistory pwdLockout
+  pwdLockoutDuration pwdMaxAge pwdMaxFailure pwdMinAge pwdMinLength
+  pwdMustChange pwdSafeModify searchTimeLimit serviceSearchDescriptor sn
+  telephoneNumber uid uidNumber userCertificate;binary userPKCS12
+  userSMIMECertificate
+)
+
+_description ldap-attributes expl "ldap attribute"
+compadd "${@:/-X/-x}" "${expl[@]:/-X/-x}" \
+    -M 'm:{a-zA-Z}={A-Za-z} r:[^A-Z]||[A-Z]=* r:|=*' -a attrs
diff --git a/Completion/Unix/Type/_ldap_filters b/Completion/Unix/Type/_ldap_filters
new file mode 100644
index 000000000..5e0e30f01
--- /dev/null
+++ b/Completion/Unix/Type/_ldap_filters
@@ -0,0 +1,91 @@
+#autoload
+
+# LDAP search filters conforming to RFC4515
+
+local -a expl excl optype disp end pre
+local -i nest=0
+local open='(' close=')' andop='&' orop='|'
+
+[[ -prefix - ]] && return 1
+
+local -a matchingrules=( # From RFC4517
+  bitStringMatch booleanMatch caseExactIA5Match
+  caseExactMatch caseExactOrderingMatch caseExactSubstringsMatch
+  caseIgnoreIA5Match caseIgnoreIA5SubstringsMatch caseIgnoreListMatch
+  caseIgnoreListSubstringsMatch caseIgnoreMatch caseIgnoreOrderingMatch
+  caseIgnoreSubstringsMatch directoryStringFirstComponentMatch
+  distinguishedNameMatch generalizedTimeMatch generalizedTimeOrderingMatch
+  integerFirstComponentMatch integerMatch integerOrderingMatch keywordMatch
+  numericStringMatch numericStringOrderingMatch numericStringSubstringsMatch
+  objectIdentifierFirstComponentMatch objectIdentifierMatch octetStringMatch
+  octetStringOrderingMatch telephoneNumberMatch telephoneNumberSubstringsMatch
+  uniqueMemberMatch wordMatch
+)
+local -a classes=( # Sampled from real servers, arbitrary other values allowed
+  automount automountMap cosTemplate dcObject device dnaSharedConfig domain
+  domainRelatedObject DUAConfigProfile extensibleObject groupOfNames
+  groupOfPrincipals ieee802device inetOrgPerson inetuser ipaassociation ipaca
+  ipacaacl ipaCertificate ipaCertMapConfigObject ipacertprofile ipaConfigObject
+  ipaDomainIDRange ipaDomainLevelConfig ipaGuiConfig ipahbacrule ipahbacservice
+  ipahbacservicegroup ipahost ipahostgroup ipaIDrange ipaKeyPolicy
+  ipakrbprincipal ipaNameResolutionData ipaNTDomainAttrs ipaNTGroupAttrs
+  ipaNTUserAttrs ipaobject ipaPublicKeyObject ipaReplTopoManagedServer
+  ipaservice ipaSshGroupOfPubKeys ipasshhost ipasshuser ipasudorule
+  ipaSupportedDomainLevelConfig ipaTrustedADDomainRange ipaUserAuthTypeClass
+  ipausergroup ipHost krbContainer krbprincipal krbprincipalaux
+  krbrealmcontainer krbTicketPolicyAux mepManagedEntry mepOriginEntry
+  nestedGroup nisDomainObject nisNetgroup nsContainer nsDS5Replica nshost
+  organization organizationalPerson organizationalRole organizationalUnit
+  person pilotObject pkiCA pkiuser posixAccount posixGroup pwdPolicy
+  shadowAccount simpleSecurityObject top
+)
+
+compquote open close andop orop
+open=${(q)open} close=${(q)close}
+# default to double rather than backslash quoting
+[[ -z $compstate[quote] && -z $PREFIX ]] && pre='"('
+
+zstyle -s ":completion:${curcontext}:operators" list-separator sep || sep=--
+print -v disp -f "%s $sep %s" \| or \& and \! not
+end=( ") $sep end" )
+excl=( ! \\\| \& ) # compadd -F uses globs: only | needs quoting
+
+local -a query=(
+  \( /$'*\0[ \t\n]#'/ \) # strip off any preceding arguments
+  \(
+    \( "/${open}!/" -'optype[++nest]=1;pre=""'
+    \| "/${open}${(q)orop}/" -'optype[++nest]=2;pre=""'
+    \| "/${open}${andop}/" -'optype[++nest]=3;pre=""'
+    \| '/[]/' ':operators:operator:compadd -F "( ${(q)excl[optype[nest]]} )" -d disp -P ${pre:-${(Q)open}} -S ${(Q)open} \| \& \!' \)
+  \|
+    \( "/${open}[^\\)]##/" "%$close%" # pass over whole var=value, needed due to lack of backtracking after the following
+    \| "/${open}(#i)homeDirectory=/" '/[]/' ':directories:directory:_directories -P / -W / -r ") \t\n\-"'
+    \| "/${open}(#i)loginShell=/" '/[]/' ':shells:shell:compadd -S ${(Q)close} ${(f)^"$(</etc/shells)"}(N)'
+    \| "/${open}(#i)mail=/" '/[]/' ':email-addresses:mail:_email_addresses -S ${(Q)close}'
+    \| "/${open}(#i)objectClass=/" '/[]/' ':object-classes:class:compadd -S ${(Q)close} -M "m:{a-zA-Z}={A-Za-z} r:[^A-Z]||[A-Z]=* r:|=*" -a classes'
+    \| "/${open}(#i)(automountKey|(member|)uid)=/" '/[]/' ':users:username:_users -S ${(Q)close}'
+    \| "/${open}(#i)cn=/" '/[]/' ':cn:cn: _alternative "users:user:_users -S ${close}" "groups:group:_groups -S ${close}" "hosts:host:_hosts -S ${close}"'
+    \|
+      '/[^:=<>~]##/' '%[=:<>~]%' -'pre=""'
+      ':object-types:object type:_ldap_attributes -P ${pre:-${(Q)open}}  -S = -r ":=~<> \t\n\-"'
+      \(
+        '/:/'
+        '/[^:]##:=/' ':matching-rules:matching rule:compadd -S ":=" -a matchingrules'
+      \|
+        '/([~<>]|)=/' ':operators:operator:compadd -S "" "<=" \>= \~='
+      \)
+      '/[^\\)]##/' "%$close%" ': _message -e object-values "object value (* for presence check)"'
+    \)
+    "/$close/" -'(( nest ))' ':brackets:bracket:compadd ${=query[nest]:+-S ""} \)'
+    \(
+      # This use of -P/-d and an empty match works around a limitation/bug where
+      # mixed use of -P removes any quoting
+      "/$close/" ':operators:operator:compadd ${=query[nest-1]:+-S ""} -d end -P ${(Q)close} ""'
+      \( // -'(( --nest ))' \| '//' -'((!nest))' '/[]/' ': compadd ""' \)
+    \) \#
+    // -'(( nest && optype[nest] > 1 ))'
+  \) \#
+)
+
+_regex_arguments _ldap_search_filters "$query[@]"
+_ldap_search_filters
diff --git a/Completion/Unix/Type/_ssh_hosts b/Completion/Unix/Type/_ssh_hosts
index a4a08ad91..b50e1c16a 100644
--- a/Completion/Unix/Type/_ssh_hosts
+++ b/Completion/Unix/Type/_ssh_hosts
@@ -24,7 +24,7 @@ if [[ -r $config ]]; then
   while (( idx <= $#lines )); do
     IFS=$'=\t ' read -r key line <<<"${lines[idx]}"
     if [[ "$key" == ((#i)match) ]]; then
-      match_args=(${(z)line})
+      match_args=( ${(Z.C.)line} )
       while [[ $#match_args -ge 2 ]]; do
 	if [[ "${match_args[1]}" == (#i)(canonical|final|(|original)host) ]]; then
 	  key="Host"
@@ -36,13 +36,10 @@ if [[ -r $config ]]; then
     fi
     case "$key" in
     ((#i)include)
-      lines[idx]=("${(@f)$(cd $HOME/.ssh; cat ${(z)~line})}") 2>/dev/null;;
+      lines[idx]=( "${(@f)$(cd $HOME/.ssh; cat ${(Z.C.)~line} 2>/dev/null)}" ) ;;
     ((#i)host(|name))
-      for host in ${(z)line}; do
-	case $host in
-	(*[*?]*) ;;
-	(*) config_hosts+=("$host") ;;
-	esac
+      for host in ${(Z.C.)line}; do
+        [[ $host != *[*?%]* ]] && config_hosts+=( $host )
       done ;&
     (*) (( ++idx ));;
     esac
diff --git a/Completion/Unix/Type/_umountable b/Completion/Unix/Type/_umountable
index 6e4988e2d..0111555b6 100644
--- a/Completion/Unix/Type/_umountable
+++ b/Completion/Unix/Type/_umountable
@@ -1,6 +1,6 @@
 #autoload
 local tmp
-local dev_tmp dpath_tmp mp_tmp mline
+local -a dev_tmp dpath_tmp mp_tmp mline
 
 case "$OSTYPE" in
 linux*)
@@ -15,6 +15,7 @@ irix*)
   ;;
 freebsd*|dragonfly*)
   /sbin/mount | while read mline; do
+    [[ $mline[(w)1] = map ]] && continue
     dev_tmp+=( $mline[(w)1] )
     mp_tmp+=( $mline[(w)3] )
   done
diff --git a/Completion/X/Command/_evince b/Completion/X/Command/_evince
index 21b493360..49f11f341 100644
--- a/Completion/X/Command/_evince
+++ b/Completion/X/Command/_evince
@@ -15,6 +15,7 @@ _arguments -s -S \
   '--g-fatal-warnings[make all warnings fatal]' \
   '--gtk-debug=[specify GTK+ debugging flags to set]:flag' \
   '--gtk-no-debug=[specify GTK+ debugging flags to unset]:flag' \
+  '(-o --new-window)'{-o,--new-window}'[open a new window]' \
   '(-p --page-label -i --page-index -n --named-dest)'{-p,--page-label=}'[specify page label of the document to display]' \
   '(-p --page-label -i --page-index -n --named-dest)'{-i,--page-index=}'[specify page number of the document to display]' \
   '(-p --page-label -i --page-index -n --named-dest)'{-n,--named-dest=}'[specify named destination to display]' \
diff --git a/Completion/X/Command/_qiv b/Completion/X/Command/_qiv
index 35ceec09a..5d0aa8faf 100644
--- a/Completion/X/Command/_qiv
+++ b/Completion/X/Command/_qiv
@@ -10,6 +10,7 @@ _arguments -s \
   '(-C --cycle)'{-C,--cycle}"[don't cycle after last image]" \
   '(-w --fixed_width -W --fixed_zoom)'{-w,--fixed_width}'[use window with specified width]:width' \
   '(-w --fixed_width -W --fixed_zoom)'{-W,--fixed_zoom}'[use window with specified zoom factor]:zoom (percentage)' \
+  '--highDPIfactor[specify resize factor to compensate for high (or also low) DPI screens]:factor' \
   '(-x -y -z --root --root_t --root_s -f --file *)'{-x,--root}'[use image as the current desktop background, centered]:image file:_files' \
   '(-x -y -z --root --root_t --root_s -f --file *)'{-y,--root_t}'[use image on the current desktop background, tiled]:image file:_files' \
   '(-x -y -z --root --root_t --root_s -f --file *)'{-z,--root_s}'[use image as the current desktop background, stretched]:image file:_files' \
@@ -22,6 +23,9 @@ _arguments -s \
   '(-n --no_filter)'{-n,--no_filter}'[disable filtering of images by extension]' \
   '(-i --no_statusbar -I --statusbar)'{-i,--no_statusbar}'[disable statusbar]' \
   '(-i --no_statusbar -I --statusbar)'{-I,--statusbar}'[enable statusbar]' \
+  '(-J --showJPEGcomments)'{-J,--showJPEGcomments}'[enable display of JPEG comments]' \
+  '(-E --showArtistName)'{-E,--showArtistName}'[enable display of artist (author) name]' \
+  "--artist_ignore[don't show specified artist name]:artist" \
   '(-p --transparency)'{-p,--transparency}'[enable transparency]' \
   '(-a --do_grab)'{-a,--do_grab}'[grab the pointer in windowed mode]' \
   '(-G --disable_grab)'{-G,--disable_grab}'[disable pointer grabbing in fullscreen mode]' \
@@ -47,4 +51,4 @@ _arguments -s \
   '(-Y --source_profile)'{-Y,--source_profile}'[specify colour profile file as source profile]:colour profile file:_files' \
   '(-Z --display_profile)'{-Z,--display_profile}'[specify colour profile file as display profile]:colour profile file:_files' \
   '--vikeys[enable movement with h/j/k/l]' \
-  '*:image file:_files -g "*.(#i)(bmp|eim|gif|ico|jp([eg]|eg)|pcx|png|p[pngb]m|pjpeg|svg|tif(|f)|wmf|x[pb]m)(-.)"'
+  '*:image file:_files -g "*.(#i)(bmp|eim|gif|hei[cf]|ico|jp([eg]|eg)|pcx|png|p[pngb]m|pjpeg|svg|tif(|f)|webp|wmf|x[pb]m)(-.)"'
diff --git a/Completion/X/Command/_xdvi b/Completion/X/Command/_xdvi
index c33e67bcc..ed5982bcc 100644
--- a/Completion/X/Command/_xdvi
+++ b/Completion/X/Command/_xdvi
@@ -2,15 +2,22 @@
 
 _xt_arguments \
   -+{allowshell,copy,expert,hush{,chars,checksums,specials},keep,l,no{ghostscript,grey,gssafer,makepk,postscript,scan},safer,thorough,underlink,version} \
-  +{altfont,base,browser,cr,debug,density,gamma,gspalette,hl,icongeometry,interpreter,margin,mfmode,offsets,p,paper,shrink,S,sidemargin,topmargin,xoffset,yoffset,grid{1,2,3},mgs{,1,2,3,4,5}} \
+  +{altfont,background,bg,browser,cr,debug,density,dvispath,editor,gamma,gspalette,hl,icongeometry,interpreter,margin,mfmode,offsets,p,paper,shrink,S,sidemargin,topmargin,xoffset,yoffset,grid{1,2,3},mgs{,1,2,3,4,5}} \
   '-altfont:default font' \
-  '-base:base URL' \
+  -{bg,background}':color:_x_color' \
   '-browser:WWW browser:_command_names -e' \
   '-cr:cursor color:_x_color' \
-  '-debug:debugging bitmask:((1\:bitmaps 2\:dvi\ translation 4\:pk\ reading 8\:batch\ operation 16\:events 32\:file\ opening 64\:PostScript\ communication 128\:Kpathsea\ statistics 256\:Kpathsea\ hash\ table\ lookups 512\:Kpathsea\ path\ definitions 1024\:Kpathsea\ path\ expansion 2048\:Kpathsea\ searches))' \
+  '-debug:debugging bitmask:((1\:bitmaps 2\:dvi\ translation 4\:pk\ reading 8\:batch\ operation 16\:events 32\:file\ opening 64\:PostScript\ communication 128\:Kpathsea\ statistics 256\:Kpathsea\ hash\ table\ lookups 512\:Kpathsea\ path\ definitions 1024\:Kpathsea\ path\ expansion 2048\:Kpathsea\ searches ))' \
   '-density:font shrink density' \
+  '-dvispath:dvips program:_command_names -e' \
+  '-editor:text editor:_cmdstring' \
+  '-expertmode:display bitmask:((1\:statusline 2\:scrollbars 4\:pagelist 8\:toolbar 16\:menubar))' \
+  -{fg,foreground}':color:_x_color' \
+  '-findstring:string' \
+  '-font:font:_x_font' \
+  '-fullscreen' \
   '-gamma:anti-aliasing factor [1.0]' \
-  -grid{1,2,3}':grid color:_x_color' \
+  '-gsalpha' \
   '-gspalette:Ghostscript palette:(Color Greyscale Monochrome)' \
   '-hl:page highlight color:_x_color' \
   '-icongeometry:icon geometry:_x_geometry' \
@@ -21,6 +28,9 @@ _xt_arguments \
   '-offsets:offset size' \
   '-p:font size (pixel per inch)' \
   '-paper:paper size (<width>x<height> or ...):(us usr legal foolscap a1 a2 a3 a4 a5 a6 a7 b1 b2 b3 b4 b5 b6 b7 c1 c2 c3 c4 c5 c6 c7 a1r a2r a3r a4r a5r a6r a7r)' \
+  '-ps2pdfpath:ps2pdf program:_command_names -e' \
+  '-rulecolor:color' \
+  '-rv' \
   '-shrink:shrink factor' \
   '-S:font shrink density' \
   '-sidemargin:side margin' \
diff --git a/Completion/Zsh/Command/_cd b/Completion/Zsh/Command/_cd
index 46237e73d..9ca846c8f 100644
--- a/Completion/Zsh/Command/_cd
+++ b/Completion/Zsh/Command/_cd
@@ -70,8 +70,15 @@ else
 
     tmpcdpath=(${${(@)cdpath:#.}:#$PWD})
 
-    (( $#tmpcdpath )) &&
-      alt=( 'path-directories:directory in cdpath:_path_files -W tmpcdpath -/' )
+    if zstyle -t ":completion:${curcontext}:path-directories" separate-sections; then
+      local elem
+      for ((elem=1; elem <= $#tmpcdpath; elem++)); do
+        alt+=( "path-directories-${elem}:directory in ${tmpcdpath[$elem]}:_path_files -W 'tmpcdpath[$elem]' -/" )
+      done
+    else
+      (( $#tmpcdpath )) &&
+        alt=( 'path-directories:directory in cdpath:_path_files -W tmpcdpath -/' )
+    fi
 
     # With cdablevars, we can complete foo as if ~foo/
     if [[ -o cdablevars && -n "$PREFIX" && "$PREFIX" != <-> ]]; then
diff --git a/Completion/Zsh/Command/_fc b/Completion/Zsh/Command/_fc
index 80e570c5d..626d35956 100644
--- a/Completion/Zsh/Command/_fc
+++ b/Completion/Zsh/Command/_fc
@@ -40,7 +40,7 @@ fc_hist=(
   '(-A -R -W -e -d -E -i -t -a -p -P)-f[mm/dd/yyyy format time-stamps]'
   '(-A -R -W -e -d -f -i -t -a -p -P)-E[dd.mm.yyyy format time-stamps]'
   '(-A -R -W -e -d -f -E -t -a -p -P)-i[yyyy-mm-dd format time-stamps]'
-  '(-A -R -W -e -d -f -E -i -a -p -P)-t[print time-stamps in specified format]:date format'
+  '(-A -R -W -e -d -f -E -i -a -p -P)-t[print time-stamps in specified format]: : _date_formats zsh'
   '(-A -R -W -e -a -p -P)-D[print elapsed times]'
 
   '(-A -R -W -I -e -d -f -i -l -m -n -r -D -E -t -P)-a[with -p, automatically pop history on function return]'
diff --git a/Completion/Zsh/Command/_kill b/Completion/Zsh/Command/_kill
index b9dfde3f0..3b5c02151 100644
--- a/Completion/Zsh/Command/_kill
+++ b/Completion/Zsh/Command/_kill
@@ -4,9 +4,11 @@ local curcontext="$curcontext" line state ret=1
 typeset -A opt_args
 
 _arguments -C \
-  '(-s -l 1)-n[specify signal number]:signal number' \
-  '(-n -l 1)-s[specify signal name]:signal:_signals -s' \
-  '(-n -s)-l[list signal names or numbers of specified signals]:*:signal:_signals' \
+  '(-s -l -L 1)-n[specify signal number]:signal number' \
+  '(-l -L)-q[send the specified integer with the signal using sigqueue]:value' \
+  '(-n -l -L 1)-s[specify signal name]:signal:_signals -s' \
+  '-l[list signal names or numbers of specified signals]:*:signal:_signals' \
+  '(- *)-L[list each signal and corresponding number]' \
   '(-n -s -l)1::signal:_signals -p -s' \
   '*:processes:->processes' && ret=0
   
diff --git a/Completion/Zsh/Command/_vared b/Completion/Zsh/Command/_vared
index aba64880a..e7072ca6d 100644
--- a/Completion/Zsh/Command/_vared
+++ b/Completion/Zsh/Command/_vared
@@ -10,5 +10,7 @@ _arguments -s -A "-*" \
   '-f+[specify finish widget]:widget:_widgets' \
   '-h[allow access to history]' \
   '-e[exit on EOF (^D)]' \
+  '-M+[specify keymap to link to main]:keymap:compadd -a keymaps' \
+  '-m+[specify keymap to link to vicmd]:keymap:compadd -a keymaps' \
   '1:parameter spec:_vars'
 
diff --git a/Completion/Zsh/Command/_zle b/Completion/Zsh/Command/_zle
index 0b8ef7a15..97ec8c875 100644
--- a/Completion/Zsh/Command/_zle
+++ b/Completion/Zsh/Command/_zle
@@ -23,6 +23,7 @@ _arguments -s -S \
     \(${(j. .)opts:#-[La]}')-l+[list user-defined widgets]:*:-:->listing' \
     \(${(j. .)opts:#-l}')-a[with -l, list all widgets]' \
     "(: * ${(j. .)opts:#-[Lw]})-F[install file descriptor handler]:file descriptor:_file_descriptors::handler:_functions" \
+    "($opts)-I[invalidate the current zle display]" \
     "!($opts)-K:keymap:compadd -a keymaps" \
     "($opts)-M[display message]:message: " \
     "($opts)-N[define new widget]:widget name:->widget-or-function ::widget shell function:->function" \
diff --git a/Completion/Zsh/Context/_dynamic_directory_name b/Completion/Zsh/Context/_dynamic_directory_name
index f449c3b12..5e0d73a8d 100644
--- a/Completion/Zsh/Context/_dynamic_directory_name
+++ b/Completion/Zsh/Context/_dynamic_directory_name
@@ -1,15 +1,29 @@
 #autoload
+local -a dirfuncs=(
+    ${(k)functions[zsh_directory_name]}
+    $zsh_directory_name_functions
+)
+local descr='dynamically named directory'
 
-local func
-integer ret=1
+if (( $#dirfuncs )); then
+  local -a expl
+  local -i ret
+  local func suf tag=dynamically-named-directories
 
-if [[ -n $functions[zsh_directory_name] || \
-  ${+zsh_directory_name_functions} -ne 0 ]] ; then
-  [[ -n $functions[zsh_directory_name] ]] && zsh_directory_name c && ret=0
-  for func in $zsh_directory_name_functions; do
-    $func c && ret=0
+  [[ $ISUFFIX != \]* ]] &&
+      suf=-S]
+
+  _tags "$tag"
+  while _tags; do
+    while _next_label "$tag" expl "$descr" $suf; do
+      for func in $dirfuncs; do
+        $func c && ret=0
+      done
+    done
+    (( ret )) || break
   done
   return ret
+
 else
-  _message 'dynamic directory name: implemented as zsh_directory_name c'
+  _message "${descr}: implement as zsh_directory_name c"
 fi
diff --git a/Completion/Zsh/Context/_parameter b/Completion/Zsh/Context/_parameter
index 7e7788535..b08d665f5 100644
--- a/Completion/Zsh/Context/_parameter
+++ b/Completion/Zsh/Context/_parameter
@@ -1,3 +1,8 @@
 #compdef -parameter-
 
+if compset -P '*:'; then
+  _history_modifiers p
+  return
+fi
+
 _parameters -e
diff --git a/Completion/Zsh/Context/_redirect b/Completion/Zsh/Context/_redirect
index e6da5d115..520a7666e 100644
--- a/Completion/Zsh/Context/_redirect
+++ b/Completion/Zsh/Context/_redirect
@@ -15,4 +15,5 @@ if [[ "$CURRENT" != "1" ]]; then
   fi
 fi
 
-_dispatch -redirect-,{${compstate[redirect]},-default-},${^strs}
+_dispatch -redirect-,${compstate[redirect]},$_comp_command \
+	  -redirect-,{${compstate[redirect]},-default-},${^strs}
diff --git a/Completion/Zsh/Type/_command_names b/Completion/Zsh/Type/_command_names
index 12cbd69c1..d445be06e 100644
--- a/Completion/Zsh/Type/_command_names
+++ b/Completion/Zsh/Type/_command_names
@@ -4,7 +4,7 @@
 # complete only external commands and executable files. This and a
 # `-' as the first argument is then removed from the arguments.
 
-local args defs expl ffilt
+local args defs expl ffilt verbose
 
 zstyle -t ":completion:${curcontext}:commands" rehash && rehash
 
@@ -33,13 +33,19 @@ else
   defs=( "$defs[@]"
     'builtins:builtin command:compadd -Qk builtins'
     "functions:shell function:compadd -k 'functions$ffilt'"
-    'aliases:alias:compadd -Qk aliases'
     'suffix-aliases:suffix alias:_suffix_alias_files'
     'reserved-words:reserved word:compadd -Qk reswords'
     'jobs:: _jobs -t'
     'parameters:: _parameters -g "^*(readonly|association)*" -qS= -r "\n\t\- =[+"'
     'parameters:: _parameters -g "*association*~*readonly*" -qS\[ -r "\n\t\- =[+"'
   )
+
+  if zstyle -T ":completion:${curcontext}:aliases" verbose; then
+    printf -v verbose %s:%s\  ${(@q+)${(kv)aliases}[@]//\:/\\:}
+    defs+=( "aliases:alias:(( $verbose ))" )
+  else
+    defs+=( 'aliases:alias:compadd -Qk aliases' )
+  fi
 fi
 
 args=( "$@" )
diff --git a/Completion/Zsh/Type/_globquals b/Completion/Zsh/Type/_globquals
index bc3165eba..beb47ed30 100644
--- a/Completion/Zsh/Type/_globquals
+++ b/Completion/Zsh/Type/_globquals
@@ -268,6 +268,7 @@ case $state in
     "P:prepend word"
     "Y:+ at most ARG matches"
     "[:+ range of files"
+    ",:logical OR"
     "):end of qualifiers"
     "\::modifier"
     )
diff --git a/Completion/Zsh/Type/_parameters b/Completion/Zsh/Type/_parameters
index b5da45c58..7b7692a3c 100644
--- a/Completion/Zsh/Type/_parameters
+++ b/Completion/Zsh/Type/_parameters
@@ -6,11 +6,6 @@
 # If you specify a -g option with a pattern, the pattern will be used to
 # restrict the type of parameters matched.
 
-if compset -P '*:'; then
-  _history_modifiers p
-  return
-fi
-
 local i pfilt
 local -i nm=$compstate[nmatches]
 local -a expl pattern=( -g \* ) normal described verbose faked fakes tmp
@@ -21,7 +16,7 @@ zstyle -t ":completion:${curcontext}:parameters" prefix-needed &&
 _description parameters expl parameter
 zparseopts -D -K -E g:=pattern
 
-if zstyle -t ":completion:${curcontext}:parameters" extra-verbose; then
+if zstyle -t ":completion:${curcontext}:parameters" verbose; then
   described=(
       "${(@M)${(@k)parameters[(R)$~pattern[2]~*(hideval|local|special)*]}:#$~pfilt*}"
   )
diff --git a/Completion/Zsh/Type/_ps1234 b/Completion/Zsh/Type/_ps1234
index 0ea2cdda9..e4391dc00 100644
--- a/Completion/Zsh/Type/_ps1234
+++ b/Completion/Zsh/Type/_ps1234
@@ -1,17 +1,18 @@
-#compdef -value-,PROMPT,-default- -value-,PROMPT2,-default- -value-,PROMPT3,-default- -value-,PROMPT4,-default- -value-,RPROMPT,-default- -value-,RPROMPT2,-default- -value-,PS1,-default- -value-,PS2,-default- -value-,PS3,-default- -value-,PS4,-default- -value-,RPS1,-default- -value-,RPS2,-default- -value-,SPROMPT,-default-
+#compdef -value-,PROMPT,-default- -value-,PROMPT2,-default- -value-,PROMPT3,-default- -value-,PROMPT4,-default- -value-,RPROMPT,-default- -value-,RPROMPT2,-default- -value-,PS1,-default- -value-,PS2,-default- -value-,PS3,-default- -value-,PS4,-default- -value-,RPS1,-default- -value-,RPS2,-default- -value-,SPROMPT,-default- -value-,PROMPT_EOL_MARK,-default-
 
-local -a specs ccol
-local expl grp cols bs suf pre changed=1 ret=1
+local -a specs ccol suf
+local expl grp cols bs pre changed=1 ret=1
 local -A ansi
 
 [[ -z $compstate[quote] ]] && bs='\'
+suf=( -S '' )
 
 # first strip off any complete prompt specifications leaving only the
 # current, incomplete, one
 while (( changed )); do
   changed=0
-  compset -P '%[DFK](\\|){[^}]#}' && changed=1 # formats with arg: %x{...}
-  compset -P '%[0-9-\\]#[^DFK(0-9-<>\\\[]' && changed=1 # normal formats
+  compset -P '%[DFHK](\\|){[^}]#}' && changed=1 # formats with arg: %x{...}
+  compset -P '%[0-9-\\]#[^DFHK(0-9-<>\\\[]' && changed=1 # normal formats
   compset -P '%[0-9-\\]#(<[^<]#<|>[^>]#>|\[[^\]]#\])' && changed=1 # truncations
   compset -P '%[0-9-\\]#(\\|)\([0-9-]#[^0-9]?|[^%]' && changed=1 # start of ternary
   compset -P '[^%]##' && changed=1 # sundry other characters
@@ -41,15 +42,15 @@ if compset -P '%[FK]'; then
   grp="$expl[expl[(i)-J]+1]"
   print -v ccol -f "($grp)=%s=%s" ${(kv)ansi}
   _comp_colors+=( $ccol )
-  compadd "$expl[@]" $suf $pre -k ansi && ret=0
-  if (( $#suf )) && compset -P "(<->|%v)"; then
+  compadd "$expl[@]" "$suf[@]" $pre -k ansi && ret=0
+  if [[ $ISUFFIX != (\\|)}* ]] && compset -P "(<->|%v)"; then
     _wanted ansi-colors expl 'closing brace' compadd -S '' \} && ret=0
   elif (( $+terminfo[colors] )); then
     (( cols = $terminfo[colors] - 1 ))
     (( cols = cols > 255 ? 255 : cols ))
     _description -V terminal-colors expl 'terminal color'
     grp="$expl[expl[(i)-J]+1]"
-    compadd "$expl[@]" $suf $pre {0..$cols}
+    compadd "$expl[@]" "$suf[@]" $pre {0..$cols}
     for c in {0..$cols}; do
       _comp_colors+=( "($grp)=${c}=${${${(%):-%F{$c\}}#?\[}%m}" )
     done
@@ -93,11 +94,14 @@ elif compset -P '%[0-9-\\]#(\\|)\([0-9-]#'; then
     'w:day of week (Sunday = 0)'
   )
   [[ $IPREFIX != *- ]] && _describe -t ternary-prompt-expressions \
-      'ternary prompt format test character' specs $suf && ret=0
+      'ternary prompt format test character' specs "$suf[@]" && ret=0
   _message -e numbers number
 elif compset -P '%D(\\|){'; then
   compset -S '(\\|)}*'
   _date_formats zsh && ret=0
+elif compset -P '%H(\\|){'; then
+  compset -S '(\\|)}*' || suf=( -S "$bs}" )
+  _wanted highlight-groups expl 'highlight group' compadd "$suf[@]" -k .zle.hlgroups && ret=0
 elif [[ -prefix '%' ]] ||
       ! zstyle -t ":completion:${curcontext}:prompt-format-specifiers" prefix-needed
 then
@@ -152,6 +156,7 @@ then
       'B:start bold'
       'b:stop bold'
       'E:clear to end of line'
+      'H{:use highlight group'
       'U:start underline'
       'u:stop underline'
       'S:start standout'
diff --git a/Completion/compdump b/Completion/compdump
index 6daf92f9f..5af5174f1 100644
--- a/Completion/compdump
+++ b/Completion/compdump
@@ -113,7 +113,7 @@ integer _i=5
 print -n autoload -Uz >& $_d_fd
 while (( $#_d_als )); do
   if (( ! $+_compautos[$_d_als[1]] )); then
-    print -n " $_d_als[1]"
+    print -rn " ${(q-)_d_als[1]}"
     if (( ! --_i && $#_d_als > 1 )); then
       _i=5
       print -n ' \\\n           '
@@ -126,13 +126,13 @@ print >& $_d_fd
 
 local _c
 for _c in "${(ok@)_compautos}"; do
-  print "autoload -Uz $_compautos[$_c] $_c" >& $_d_fd
+  print -r "autoload -Uz ${(q-)_compautos[$_c]} $_c" >& $_d_fd
 done
 
 print >& $_d_fd
 
 print "typeset -gUa _comp_assocs" >& $_d_fd
-print "_comp_assocs=( ${(qq)_comp_assocs} )" >& $_d_fd
+print -r "_comp_assocs=( ${(qq)_comp_assocs} )" >& $_d_fd
 exec {_d_fd}>&-
 
 mv -f $_d_file ${_d_file%.$HOST.$$}
diff --git a/Completion/compinit b/Completion/compinit
index 5cb527fac..51e9d88b8 100644
--- a/Completion/compinit
+++ b/Completion/compinit
@@ -301,7 +301,7 @@ compdef() {
     if [[ -z "$eval" ]] && [[ "$1" = *\=* ]]; then
       while (( $# )); do
         if [[ "$1" = *\=* ]]; then
-	  cmd="${1%%\=*}"
+	  cmd="${(q)${1%%\=*}}"
 	  svc="${1#*\=}"
           func="$_comps[${_services[(r)$svc]:-$svc}]"
           [[ -n ${_services[$svc]} ]] &&
@@ -412,7 +412,7 @@ compdef() {
 	      svc=
             fi
             if [[ -z "$new" || -z "${_comps[$1]}" ]]; then
-              _comps[$cmd]="$func"
+              _comps[$cmd]="${(q)func}"
 	      [[ -n "$svc" ]] && _services[$cmd]="${1#*\=}"
 	    fi
             ;;
diff --git a/Config/defs.mk.in b/Config/defs.mk.in
index 2bc17482a..116875fb9 100644
--- a/Config/defs.mk.in
+++ b/Config/defs.mk.in
@@ -75,7 +75,6 @@ IMPOPT          = @IMPOPT@
 
 # utilities
 AWK             = @AWK@
-ANSI2KNR        = @ANSI2KNR@
 YODL            = @YODL@ @YODL_OPTIONS@
 YODL2TXT        = @YODL@2txt
 YODL2HTML       = @YODL@2html
@@ -100,7 +99,7 @@ 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)' \
+AWK='$(AWK)' \
 YODL='$(YODL)' YODL2TXT='$(YODL2TXT)' YODL2HTML='$(YODL2HTML)' \
 FUNCTIONS_INSTALL='$(FUNCTIONS_INSTALL)' tzsh='$(tzsh)'
 
diff --git a/Doc/Makefile.in b/Doc/Makefile.in
index 23e5fc7e2..d9be182e9 100644
--- a/Doc/Makefile.in
+++ b/Doc/Makefile.in
@@ -43,6 +43,7 @@ TEXI2DVI = @TEXI2DVI@
 DVIPS = dvips
 TEXI2PDF  = @TEXI2PDF@
 TEXI2HTML = @TEXI2HTML@
+SET_TEXI2ANY_VAR = @SET_TEXI2ANY_VAR@
 PAPERSIZE = @PAPERSIZE@
 
 .SUFFIXES: .yo .1
@@ -62,8 +63,9 @@ Zsh/mod_attr.yo Zsh/mod_cap.yo Zsh/mod_clone.yo \
 Zsh/mod_compctl.yo Zsh/mod_complete.yo Zsh/mod_complist.yo \
 Zsh/mod_computil.yo Zsh/mod_curses.yo \
 Zsh/mod_datetime.yo Zsh/mod_db_gdbm.yo Zsh/mod_deltochar.yo \
-Zsh/mod_example.yo Zsh/mod_files.yo Zsh/mod_langinfo.yo \
-Zsh/mod_mapfile.yo Zsh/mod_mathfunc.yo \
+Zsh/mod_example.yo Zsh/mod_files.yo \
+Zsh/mod_hlgroup.yo Zsh/mod_langinfo.yo \
+Zsh/mod_ksh93.yo Zsh/mod_mapfile.yo Zsh/mod_mathfunc.yo \
 Zsh/mod_nearcolor.yo Zsh/mod_newuser.yo \
 Zsh/mod_parameter.yo Zsh/mod_pcre.yo Zsh/mod_private.yo \
 Zsh/mod_regex.yo Zsh/mod_sched.yo Zsh/mod_socket.yo \
@@ -266,7 +268,7 @@ texi2html.conf: $(sdir_top)/Config/version.mk
 	d=`echo $(VERSION_DATE)`; \
 	v="<font size=\"-1\">Zsh version $(VERSION), released on $$d.</font>"; \
 	case '$(TEXI2HTML)' in \
-	  *texi2any*) echo "set_from_init_file('PRE_BODY_CLOSE','$$v');" ;; \
+	  *texi2any*) echo "$(SET_TEXI2ANY_VAR)('PRE_BODY_CLOSE','$$v');" ;; \
 	  *) echo "\$$PRE_BODY_CLOSE = '$$v';" ;; \
 	esac > $@
 
diff --git a/Doc/Zsh/arith.yo b/Doc/Zsh/arith.yo
index bc3e35ad5..9f5298821 100644
--- a/Doc/Zsh/arith.yo
+++ b/Doc/Zsh/arith.yo
@@ -206,6 +206,11 @@ example,
 example(((val2 = val1 * 2)))
 
 assigns twice the value of tt($val1) to the parameter named tt(val2).
+If the expansion of tt($val1) is text rather than a number, then when
+tt(val1) is referenced that text is itself evaluated as a math expression
+as if surrounded by parentheses `tt(LPAR()$val1)tt(RPAR())'.  Expansion
+continues until there are no more parameter references, a number has
+resulted, or an expression error occurs.
 
 An internal integer representation of a named parameter
 can be specified with the tt(integer) builtin.
diff --git a/Doc/Zsh/builtins.yo b/Doc/Zsh/builtins.yo
index 641e46cf9..7a9684ac8 100644
--- a/Doc/Zsh/builtins.yo
+++ b/Doc/Zsh/builtins.yo
@@ -683,6 +683,7 @@ the same as if the commands had been executed directly by the shell;
 if there are no var(args) or they contain no commands (i.e. are
 an empty string or whitespace) the return status is zero.
 )
+findex(exec)
 item(tt(exec) [ tt(-cl) ] [ tt(-a) var(argv0) ] [ var(command) [ var(arg) ... ] ])(
 Replace the current shell with var(command) rather than forking.
 If var(command) is a shell builtin command or a shell function,
@@ -1052,9 +1053,11 @@ The choice of hash table to work on is determined by the tt(-d) option;
 without the option the command hash table is used, and with the option the
 named directory hash table is used.
 
-A command var(name) starting with a tt(/) is never hashed, whether by
-explicit use of the tt(hash) command or otherwise.  Such a command
-is always found by direct look up in the file system.
+A command var(name) starting with a tt(/) or with a relative path
+starting with tt(./) or tt(../) is never executed by lookup in
+the command hash table, and these can only be added to the table by
+explicit use of the tt(hash) command.  Such a command is always
+found by direct look up in the file system.
 
 Given no arguments, and neither the tt(-r) or tt(-f) options,
 the selected hash table will be listed in full.
@@ -1063,9 +1066,11 @@ The tt(-r) option causes the selected hash table to be emptied.
 It will be subsequently rebuilt in the normal fashion.
 The tt(-f) option causes the selected hash table to be fully
 rebuilt immediately.  For the command hash table this hashes
-all the absolute directories in the tt(PATH),
-and for the named directory hash table this adds all users' home directories.
+all (and em(only)) the absolute directories in the tt(PATH),
+and for the named directory hash table this adds all users' home
+directories.
 These two options cannot be used with any arguments.
+Both options remove any explicitly-added elements.
 
 The tt(-m) option causes the arguments to be taken as patterns
 (which should be quoted) and the elements of the hash table
@@ -1138,8 +1143,9 @@ findex(kill)
 cindex(killing jobs)
 cindex(jobs, killing)
 xitem(tt(kill) [ tt(-s) var(signal_name) | tt(-n) var(signal_number) | \
-tt(-)var(sig) ] var(job) ...)
-item(tt(kill) tt(-l) [ var(sig) ... ])(
+tt(-)var(sig) ] [ tt(-q) var(value) ] var(job) ...)
+xitem(tt(kill) tt(-l) [ var(sig) ... ])
+item(tt(kill) tt(-L))(
 Sends either tt(SIGTERM) or the specified signal to the given
 jobs or processes.
 Signals are given by number or by names, with or without the `tt(SIG)'
@@ -1153,7 +1159,8 @@ specified the signal names are listed.  Otherwise, for each
 var(sig) that is a name, the corresponding signal number is
 listed.  For each var(sig) that is a signal number or a number
 representing the exit status of a process which was terminated or
-stopped by a signal the name of the signal is printed.
+stopped by a signal the name of the signal is printed.  The final
+form with tt(-L) lists each signal name with its corresponding number.
 
 On some systems, alternative signal names are allowed for a few signals.
 Typical examples are tt(SIGCHLD) and tt(SIGCLD) or tt(SIGPOLL) and
@@ -1165,6 +1172,9 @@ tt(kill -IO) and tt(kill -POLL) have the same effect.
 
 Many systems will allow process IDs to be negative to kill a process
 group or zero to kill the current process group.
+
+The tt(-q) option allows an integer value to be sent with the signal
+on systems that support tt(sigqueue+LPAR()RPAR()).
 )
 findex(let)
 item(tt(let) var(arg) ...)(
@@ -1585,7 +1595,8 @@ Input is read from the coprocess.
 )
 item(tt(-d) var(delim))(
 Input is terminated by the first character of var(delim) instead of
-by newline.
+by newline.  For compatibility with other shells, if var(delim) is an
+empty string, input is terminated at the first NUL.
 )
 item(tt(-t) [ var(num) ])(
 Test if input is available before attempting to read.  If var(num)
@@ -1628,6 +1639,7 @@ cancels both tt(-p) and tt(-u).
 
 The tt(-c) or tt(-l) flags cancel any and all of tt(-kpquz).
 )
+findex(readonly)
 cindex(parameters, marking readonly)
 item(tt(readonly))(
 Same as tt(typeset -r).  With the tt(POSIX_BUILTINS) option set, same
@@ -1639,7 +1651,9 @@ cindex(functions, returning from)
 item(tt(return) [ var(n) ])(
 Causes a shell function or `tt(.)' script to return to
 the invoking script with the return status specified by
-an arithmetic expression var(n).  
+an arithmetic expression var(n).  Also causes a non-interctive
+shell to exit, allowing files containing shell code to be used
+both as scripts and as autoloadable shell functions.
 For example, the following prints `tt(42)':
 
 example(() { integer foo=40; return "foo + 2" }
@@ -1919,6 +1933,8 @@ redef(SPACES)(0)(tt(ifztexi(NOTRANS(@ @ @ @ @ @ @ @ ))ifnztexi(        )))
 xitem(tt(typeset )[ {tt(PLUS())|tt(-)}tt(AHUaghlmrtux) ] \
 [ {tt(PLUS())|tt(-)}tt(EFLRZip) [ var(n) ] ])
 xitem(SPACES()[ tt(+) ] [ var(name)[tt(=)var(value)] ... ])
+xitem(tt(typeset ){tt(PLUS())|tt(-)}tt(n) [ tt(-g) ] \
+[ {tt(PLUS())|tt(-)}tt(r) ] [ var(name)[tt(=)var(value)] ... ])
 xitem(tt(typeset )tt(-T) [ {tt(PLUS())|tt(-)}tt(Uglrux) ] [ {tt(PLUS())|tt(-)}tt(LRZp) [ var(n) ] ])
 xitem(SPACES()[ tt(+) | var(SCALAR)[tt(=)var(value)] var(array)[tt(=LPAR())var(value) ...tt(RPAR())] [ var(sep) ] ])
 item(tt(typeset) tt(-f) [ {tt(PLUS())|tt(-)}tt(TUkmtuz) ] [ tt(+) ] [ var(name) ... ])(
@@ -2032,6 +2048,36 @@ To initialize a parameter var(param) to a command output and mark it readonly,
 use tt(typeset -r )var(param) or tt(readonly )var(param) after the parameter
 assignment statement.
 
+cindex(named reference)
+cindex(reference, named)
+The flag tt(-n) creates a em(named reference) to another parameter.
+The second parameter need not exist at the time the reference is
+created.  Only tt(-g), tt(-u), and tt(-r) may be used in conjunction with
+tt(-n).  The var(name) so created may not be an array element nor use
+a subscript, but the var(value) assigned may be any valid parameter
+name syntax, even a subscripted array element (including an associative
+array element) or an array slice, which is evaluated when the named
+reference is expanded.  It is an error for a named reference to refer
+to itself, even indirectly through a chain of references.  When tt(-u)
+is applied to a named reference, the parameter identified by var(value)
+is always found in the calling function scope rather than the current
+local scope.  In this case, if there is no such parameter in the calling
+scope, assignments to the named reference may fail, setting tt($?) to 1.
+See ifzman(zmanref(zshexpn))ifnzman(noderef(Parameter Expansion)) and
+ifzman(zmanref(zshparam))ifnzman(noderef(Parameters)) for details of the
+behavior of named references.
+
+Local function scoping rules for `tt(typeset)' do apply with `tt(-n)',
+so a declaration within a function persists only until the end of the
+function unless `tt(-g -n)' is specified, and any local parameter (of
+any type) with the same var(name) supplants a named reference from a
+surrounding scope.
+
+A scalar parameter, including an existing named reference, may be
+converted to a new named reference by `tt(typeset -n )var(name)', so
+the `tt(-p)' option must be included to display the value of a
+specific named reference var(name).
+
 If no attribute flags are given, and either no var(name) arguments are
 present or the flag tt(+m) is used, then each parameter name printed is
 preceded by a list of the attributes of that parameter (tt(array),
@@ -2047,8 +2093,9 @@ startitem()
 item(tt(PLUS()))(
 If `tt(PLUS())' appears by itself in a separate word as the last option,
 then the names of all parameters (functions with tt(-f)) are printed, but
-the values (function bodies) are not.  No var(name) arguments may appear,
-and it is an error for any other options to follow `tt(PLUS())'.  The
+the values (function bodies) are not.  If var(name) arguments appear,
+both those names and their values are printed in the form of assignments.
+It is an error for any other options to follow `tt(PLUS())', but the
 effect of `tt(PLUS())' is as if all attribute flags which precede it were
 given with a `tt(PLUS())' prefix.  For example, `tt(typeset -U PLUS())' is
 equivalent to `tt(typeset +U)' and displays the names of all arrays having
@@ -2075,13 +2122,15 @@ is not used in this case).
 
 If the tt(+g) flag is combined with tt(-m), a new local parameter is
 created for every matching parameter that is not already local.  Otherwise
-tt(-m) applies all other flags or assignments to the existing parameters.
+tt(-m) applies all other flags or assignments to the existing parameters,
+except that the tt(-n) option cannot create named references in this way.
 
 Except when assignments are made with var(name)tt(=)var(value), using
 tt(+m) forces the matching parameters and their attributes to be printed,
 even inside a function.  Note that tt(-m) is ignored if no patterns are
 given, so `tt(typeset -m)' displays attributes but `tt(typeset -a +m)'
-does not.
+does not.  Ordinary scalar string parameters have no attributes, so for
+those tt(+m) prints only the names.
 )
 item(tt(-p) [ var(n) ])(
 If the tt(-p) option is given, parameters and values are printed in the
@@ -2093,6 +2142,14 @@ tt(-p) may be followed by an optional integer argument.  Currently
 only the value tt(1) is supported.  In this case arrays and associative
 arrays are printed with newlines between indented elements for
 readability.
+
+The names and values of readonly special parameters
+(most of the parameters marked `<S>' in
+ifzman(zmanref(zshparam))ifnzman(noderef(Parameters Set By The Shell)),
+except those documented as settable)
+are not printed with `tt(-)tt(p)' because to execute those typeset commands
+would cause errors.  However, these parameters are printed when they
+have been made local to the scope where `tt(typeset -p)' is run.
 )
 item(tt(-T) [ var(scalar)[tt(=)var(value)] var(array)[tt(=LPAR())var(value) ...tt(RPAR())] [ var(sep) ] ])(
 This flag has a different meaning when used with tt(-f); see below.
@@ -2235,9 +2292,9 @@ automatically given the tt(-h) attribute to avoid name clashes.
 item(tt(-H))(
 Hide value: specifies that tt(typeset) will not display the value of the
 parameter when listing parameters; the display for such parameters is
-always as if the `tt(PLUS())' flag had been given.  Use of the parameter is
-in other respects normal, and the option does not apply if the parameter is
-specified by name, or by pattern with the tt(-m) option.  This is on by
+always as if the `tt(PLUS())' flag were given, but use of the parameter is
+in other respects normal.  This effect does not apply when the parameter is
+specified by name or by pattern with the tt(-m) option.  This is on by
 default for the parameters in the tt(zsh/parameter) and tt(zsh/mapfile)
 modules.  Note, however, that unlike the tt(-h) flag this is also useful
 for non-special parameters.
@@ -2284,8 +2341,10 @@ readonly). Special variables that have been made readonly retain their value
 and readonly attribute when made local.
 )
 item(tt(-t))(
-Tags the named parameters.  Tags have no special meaning to the shell.
-This flag has a different meaning when used with tt(-f); see above.
+Tags the named parameters.  Tags only exist to flag the parameter for
+the user's own purposes --- the list of tagged parameters can be queried
+using `tt(typeset -t)'.  Tags have no other use.  Note that the tt(-t)
+flag has a different meaning when used with tt(-f); see above.
 )
 item(tt(-u))(
 Convert the result to upper case whenever the parameter is expanded.
@@ -2375,6 +2434,7 @@ the mask is printed as an octal number.  Note that in
 the symbolic form the permissions you specify are those which are to be
 allowed (not denied) to the users specified.
 )
+findex(unalias)
 cindex(aliases, removing)
 item(tt(unalias) [ tt(-ams) ] var(name) ...)(
 Removes aliases.  This command works the same as tt(unhash -a), except that
@@ -2416,7 +2476,7 @@ with the command `tt(zmodload -F zsh/rlimits b:unlimit)'.
 )
 findex(unset)
 cindex(parameters, unsetting)
-item(tt(unset) [ tt(-fmv) ] var(name) ...)(
+item(tt(unset) [ tt(-fmv) ] [ tt(-n) ] var(name) ...)(
 Each named parameter is unset.
 Local parameters remain local even if unset; they appear unset within scope,
 but the previous value will still reappear when the scope ends.
@@ -2430,10 +2490,13 @@ be quoted) and all parameters with matching names are unset.  Note that this
 cannot be used when unsetting associative array elements, as the subscript
 will be treated as part of the pattern.
 
-The tt(-v) flag specifies that var(name) refers to parameters. This is the
-default behaviour.
+The tt(-v) flag specifies that var(name) refers to parameters. This is
+the default behaviour.  If the tt(-n) option is supplied, and
+var(name) is a a named reference, var(name) will be unset rather than
+the variable it references.
 
-tt(unset -f) is equivalent to tt(unfunction).
+tt(unset -f) is equivalent to tt(unfunction).  The tt(-n) option has
+no effect with tt(-f).
 )
 findex(unsetopt)
 cindex(options, unsetting)
@@ -2521,11 +2584,14 @@ item(tt(-a))(
 Do a search for all occurrences of var(name)
 throughout the command path.
 Normally only the first occurrence is printed.
+When combined with tt(-m), only names appearing in the command hash
+table are searched, but all occurrences of those names are printed.
 )
 item(tt(-m))(
 The arguments are taken as patterns (pattern characters should be
-quoted), and the information is displayed for each command matching one
-of these patterns.
+quoted), and the information is displayed for each entry in the command
+hash table matching one of these patterns.  The hash table is first
+refilled, in case of changes to tt(PATH).
 )
 item(tt(-s))(
 If a pathname contains symlinks, print the symlink-free pathname as well.
diff --git a/Doc/Zsh/compsys.yo b/Doc/Zsh/compsys.yo
index 584ede441..f75298a1b 100644
--- a/Doc/Zsh/compsys.yo
+++ b/Doc/Zsh/compsys.yo
@@ -2023,8 +2023,8 @@ position shown as a percentage of the total length otherwise.  In each
 case the form with the uppercase letter will be replaced by a string of fixed
 width, padded to the  right with spaces, while the lowercase form will
 be replaced by a variable width string.  As in other prompt strings, the
-escape sequences `tt(%S)', `tt(%s)', `tt(%B)', `tt(%b)', `tt(%U)',
-`tt(%u)' for entering and leaving the display modes
+escape sequence `tt(%H)` along with `tt(%S)', `tt(%s)', `tt(%B)', `tt(%b)',
+`tt(%U)', `tt(%u)' for entering and leaving the display modes
 standout, bold and underline, and `tt(%F)', `tt(%f)', `tt(%K)', `tt(%k)' for
 changing the foreground background colour, are also available, as is the form
 `tt(%{)...tt(%})' for enclosing escape sequences which display with zero
@@ -5227,6 +5227,57 @@ the group name.
 This function is called automatically from tt(_description)
 and hence is not normally called explicitly.
 )
+findex(_shadow)
+findex(_unshadow)
+xitem(tt(_shadow) [ tt(-s) var(suffix) ] [ -- ] var(command_name) ...)
+item(tt(_unshadow))(
+The tt(_shadow) function creates a copy of each of the shell functions
+in the var(command_name) arguments.  The original functions can then
+be replaced by new implementations.  A later call to tt(_unshadow)
+removes the new implementations, if any, and restores the originals.
+
+Recommended usage is to pair tt(_shadow) and tt(_unshadow) calls by
+use of an `tt(always)' block:
+example({
+  _shadow fname
+  function fname {
+    # Do your new thing
+  }
+  # Invoke callers of fname
+} always {
+  _unshadow
+})
+
+The var(suffix), if supplied, is prepended by an `tt(@)' character and
+then appended to each var(command_name) to create the copy.  Thus
+example(_shadow -s XX foo)
+creates a function named `tt(foo@XX)'.  This provides a well-known
+name for the original implementation if the new implementation needs
+to call it as a wrapper.  If a nested call to  tt(_shadow) uses the
+same var(suffix), em(no new copy is made).  The presumption thus is
+that suffixes and new implementations correspond one to one.
+
+If var(command_name) is a builtin or external command, and there has been
+no preceding tt(_shadow) replacement made, the function so created calls
+the shadowed name prefixed by the tt(builtin) or tt(command) keywords as
+appropriate.
+example({
+  _shadow -s wrap compadd
+  compadd LPAR()RPAR() {
+    # compadd@wrap runs builtin compadd
+    compadd@wrap -O tmparr "$@" }
+} always {
+  _unshadow
+})
+
+When no var(suffix) argument is present, tt(_shadow) creates a unique
+suffix to avoid name collisions.
+
+Arguments of tt(_unshadow) are ignored.  Every listed var(command_name)
+for the most recent call to tt(_shadow) is removed.  This differs from
+an early implementation that required tt(_unshadow) to receive the
+same var(suffix) and var(command_name) list as tt(_shadow).
+)
 findex(_store_cache)
 item(tt(_store_cache) var(cache_identifier) var(param) ...)(
 This function, together with tt(_retrieve_cache) and
diff --git a/Doc/Zsh/compwid.yo b/Doc/Zsh/compwid.yo
index d32a0702f..b0c9b0a5f 100644
--- a/Doc/Zsh/compwid.yo
+++ b/Doc/Zsh/compwid.yo
@@ -112,7 +112,7 @@ vindex(QIPREFIX)
 item(tt(QIPREFIX))(
 This parameter is read-only and contains the quoted string up to the
 word being completed. E.g. when completing `tt("foo)', this parameter
-contains the double quote. If the tt(-q) option of tt(compset) is used 
+contains the double quote. If the tt(-q) option of tt(compset) is used
 (see below), and the original string was `tt("foo bar)' with the
 cursor on the `tt(bar)', this parameter contains `tt("foo )'.
 )
@@ -597,7 +597,8 @@ ifnzman((see noderef(Prompt Expansion)))\
 ifzman(as described in the section EXPANSION OF PROMPT SEQUENCES in
 zmanref(zshmisc)):
 `tt(%B)', `tt(%S)', `tt(%U)', `tt(%F)', `tt(%K)' and their lower case
-counterparts, as well as `tt(%{)...tt(%})'.  `tt(%F)', `tt(%K)' and
+counterparts, as well as `tt(%H)' and `tt(%{)...tt(%})'.  `tt(%F)',
+`tt(%K)', `tt(%H)' and
 `tt(%{)...tt(%})' take arguments in the same form as prompt
 expansion.  (Note that the sequence `tt(%G)' is not available; an
 argument to `tt(%{)' should be used instead.)  The sequence `tt(%%)'
@@ -1082,8 +1083,8 @@ enditem()
 )
 xitem(tt(l:)tt(|)var(word-pat)tt(=)var(match-pat))
 xitem(tt(L:)tt(|)var(word-pat)tt(=)var(match-pat))
-xitem(tt(R:)var(word-pat)tt(|)tt(=)var(match-pat))
-item(tt(r:)var(word-pat)tt(|)tt(=)var(match-pat))(
+xitem(tt(r:)var(word-pat)tt(|)tt(=)var(match-pat))
+item(tt(R:)var(word-pat)tt(|)tt(=)var(match-pat))(
 
 If there is a substring at the tt(l:)eft or tt(r:)ight edge of the current word
 that matches var(word-pat), then broaden the corresponding part of the match
diff --git a/Doc/Zsh/contrib.yo b/Doc/Zsh/contrib.yo
index 0ef59dbc9..c1bea6022 100644
--- a/Doc/Zsh/contrib.yo
+++ b/Doc/Zsh/contrib.yo
@@ -2448,6 +2448,33 @@ history is restricted, so cursor motions, etc., may not pass outside of
 the pasted content.  Text assigned to tt(BUFFER) by the active widgets
 is copied back into tt(PASTED) before tt(paste-finish).
 )
+tindex(bracketed-paste-url-magic)
+item(tt(bracketed-paste-url-magic))(
+This widget is a simpler version of using tt(bracketed-paste-magic)
+to enable tt(quote-url-magic). Rather than re-interpreting everything as
+keystrokes, it simply handles quoting of pasted urls itself, and all other
+text is handled like the default bracketed-paste widget.
+
+It limits the quoting to pastes that consist of a single url, but you
+can also enable or disable quoting explicitly for a paste by setting
+NUMERIC to 1 or 2 respectively (ie, by pressing alt-1 or alt-2 before
+pasting).
+
+It is also possible to customize the list of schemas used to
+decide if something is a url by setting the tt(schema) style in the
+tt(:bracketed-paste-url-magic) context, for example:
+ifzman()
+example(zstyle :bracketed-paste-url-magic schema http:// myspecialschema:)
+
+The default list of schemas is tt(http:// https:// ftp:// ftps:// file:// \
+                                  ssh:// sftp:// magnet:).
+
+The widget itself is installed in a similar way as
+tt(bracketed-paste-magic) above, by
+ifzman()
+example(autoload -Uz bracketed-paste-url-magic
+zle -N bracketed-paste bracketed-paste-url-magic)
+)
 tindex(copy-earlier-word)
 item(tt(copy-earlier-word))(
 This widget works like a combination of tt(insert-last-word) and
@@ -2593,12 +2620,33 @@ zle -N history-pattern-search-forward history-pattern-search)
 tindex(incarg)
 vindex(incarg, use of)
 item(tt(incarg))(
-Typing the keystrokes for this widget with the cursor placed on or to the
-left of an integer causes that integer to be incremented by one.  With a
-numeric argument, the number is incremented by the amount of the
-argument (decremented if the numeric argument is negative).  The shell
-parameter tt(incarg) may be set to change the default increment to
-something other than one.
+This widget allows you to increment integers on the current line. In addition
+to decimals, it can handle hexadecimals prefixed with tt(0x), binaries with
+tt(0b), and octals with tt(0o).
+
+By default, the target integer will be incremented by one. With a numeric
+argument, the integer is incremented by the amount of the argument. The shell
+parameter tt(incarg) may be set to change the default increment to something
+other than one.
+
+The behavior of this widget changes depending on the widget name.
+
+When the widget is named tt(incarg), the widget will increment an integer
+placed under the cursor placed or just to the left of it. tt(decarg), on the
+other hand, decrements the integer. When the name is prefixed with tt(vi),
+the cursor will jump to the nearest integer after the cursor before incrementing
+it. The tt(vi) prefix can also be combined with a tt(backward-) prefix to make
+the widget search backwards for numbers.
+
+There's also a tt(sync-) prefix that can be added to the widget name. This
+variant is used for creating a sequence of numbers on split terminals with
+synchronized key input. The first pane won't increment the integer at all, but
+each pane after that will have the integer incremented once more than the
+previous pane. It currently supports tmux and iTerm2.
+
+The prefixes tt(vi), tt(backward-), and tt(sync-) can be combined, for example,
+into tt(vim-sync-) or tt(vim-backward-sync-). The tt(vi) prefix needs to be
+at the very beginning.
 
 example(bindkey '^X+' incarg)
 )
@@ -3972,8 +4020,11 @@ calculation is stored.  For example, the result of the calculation on the
 line preceded by `tt(4> )' is available as tt($4).  The last value
 calculated is available as tt(ans).  Full command line editing, including
 the history of previous calculations, is available; the history is saved in
-the file tt(~/.zcalc_history).  To exit, enter a blank line or type `tt(:q)'
-on its own (`tt(q)' is allowed for historical compatibility).
+the file tt($ZCALC_HISTFILE).  If tt($ZCALC_HISTFILE) is unset,
+tt($ZDOTDIR/.zcalc_history) is used instead, which in turn falls backs to
+tt($HOME/.zcalc_history) if tt($ZDOTDIR) is unset.  To exit, enter a blank
+line or type `tt(:q)' on its own (`tt(q)' is allowed for historical
+compatibility).
 
 A line ending with a single backslash is treated in the same fashion
 as it is in command line editing:  the backslash is removed, the
@@ -4262,13 +4313,17 @@ tt(colors) more than once.
 The eight base colors are: tt(black), tt(red), tt(green), tt(yellow),
 tt(blue), tt(magenta), tt(cyan), and tt(white).  Each of these has codes for
 foreground and background.  In addition there are seven intensity attributes:
-tt(bold), tt(faint), tt(standout), tt(underline), tt(blink), tt(reverse),
+tt(bold), tt(faint), tt(italic), tt(underline), tt(blink), tt(reverse),
 and tt(conceal).  Finally, there are seven codes used to negate attributes:
 tt(none) (reset all attributes to the defaults), tt(normal)
-(neither bold nor faint), tt(no-standout), tt(no-underline), tt(no-blink),
+(neither bold nor faint), tt(no-italic), tt(no-underline), tt(no-blink),
 tt(no-reverse), and tt(no-conceal).
 
 Some terminals do not support all combinations of colors and intensities.
+Prior to zsh tt(5.8.1) the intensity tt(standout) was provided.  It has
+been replaced by the more specific tt(italic) and tt(reverse) to match
+the specification, but some terminals may swap these or make one of them
+produce blinking text even if the tt(blink) code is not usable.
 
 The associative arrays are:
 
@@ -4333,6 +4388,27 @@ example(is-at-least 3.1.6-15 && setopt NO_GLOBAL_RCS
 is-at-least 3.1.0 && setopt HIST_REDUCE_BLANKS
 is-at-least 2.6-17 || print "You can't use is-at-least here.")
 )
+findex(mkshadow)
+findex(rmshadow)
+xitem(tt(mkshadow) [ tt(-s) var(suffix) ] [ -- ] var(command_name) ...)
+item(tt(rmshadow))(
+These functions are an interface to the tt(_shadow) and tt(_unshadow)
+completion utilities to make them more easily accessible in other
+contexts.  Usage is exactly as for the completion utility:
+example({
+  mkshadow fname
+  function fname {
+    # Do your new thing
+  }
+  # Invoke callers of fname
+} always {
+  rmshadow
+})
+
+Upon return, the value of tt($REPLY) is the suffix used to create a
+copy of the original var(command_name), so var(command_name)tt(@$REPLY)
+invokes that original.
+)
 findex(nslookup)
 item(tt(nslookup) [ var(arg) ... ])(
 This wrapper function for the tt(nslookup) command requires the
@@ -4617,10 +4693,10 @@ renames `tt(foo.lis)' to `tt(foo.txt)', `tt(my.old.stuff.lis)' to
 
 The pattern is always treated as an tt(EXTENDED_GLOB) pattern.  Any file
 whose name is not changed by the substitution is simply ignored.  Any
-error (a substitution resulted in an empty string, two substitutions gave
-the same result, the destination was an existing regular file and tt(-f)
-was not given) causes the entire function to abort without doing
-anything.
+error (no files matched the var(srcpat), substitution resulted in an empty
+string, two substitutions gave the same result, the destination was an
+existing regular file and tt(-f) was not given) causes the entire function
+to abort without doing anything.
 
 In addition to pattern replacement, the variable tt($f) can be referred
 to in the second (replacement) argument.  This makes it possible to
diff --git a/Doc/Zsh/expn.yo b/Doc/Zsh/expn.yo
index eb8cdbae5..7eade4a11 100644
--- a/Doc/Zsh/expn.yo
+++ b/Doc/Zsh/expn.yo
@@ -312,7 +312,8 @@ zero) that are neither `tt(.)' nor `tt(/)' and that continue to the end
 of the string.  For example, the extension of
 `tt(foo.orig.c)' is `tt(.c)', and `tt(dir.c/foo)' has no extension.
 )
-item(tt(s/)var(l)tt(/)var(r)[tt(/)])(
+xitem(tt(s/)var(l)tt(/)var(r)[tt(/)])
+item(tt(S/)var(l)tt(/)var(r)[tt(/)])(
 Substitute var(r) for var(l) as described below.
 The substitution is done only for the
 first string that matches var(l).  For arrays and for filename
@@ -324,13 +325,17 @@ perform global substitution, i.e. substitute every occurrence of var(r)
 for var(l).  Note that the tt(g) or tt(:G) must appear in exactly the
 position shown.
 
+The use of tt(S) instead of tt(s) is identical except that
+the source is treated as a pattern, just as if the option
+tt(HIST_SUBST_PATTERN) were set.
+
 See further notes on this form of substitution below.
 )
 item(tt(&))(
-Repeat the previous tt(s) substitution.  Like tt(s), may be preceded
-immediately by a tt(g).  In parameter expansion the tt(&) must appear
-inside braces, and in filename generation it must be quoted with a
-backslash.
+Repeat the previous tt(s) or tt(S) substitution, whichever was most
+recent.  Like tt(s) and tt(S), may be preceded immediately by a tt(g).
+In parameter expansion the tt(&) must appear inside braces, and in
+filename generation it must be quoted with a backslash.
 )
 item(tt(t) [ var(digits) ])(
 Remove all leading pathname components, leaving the final component (tail).
@@ -377,7 +382,8 @@ substitutions or expansions are performed once at the time the qualifier
 is parsed, even before the `tt(:s)' expression itself is divided into
 var(l) and var(r) sides.
 
-If the option tt(HIST_SUBST_PATTERN) is set, var(l) is treated as
+If the option tt(HIST_SUBST_PATTERN) is set or the original substitution
+was started with a capital tt(S), var(l) is treated as
 a pattern of the usual form described in
 ifzman(the section FILENAME GENERATION below)\
 ifnzman(noderef(Filename Generation)).  This can be used in
@@ -604,6 +610,16 @@ and other operators, such as `tt(${PREFIX:-"/usr/local"})'.  Parameter
 expansions can also be nested.  These topics will be introduced below.
 The full rules are complicated and are noted at the end.
 
+cindex(namespace)
+Parameter expansions may optionally include a em(namespace) prefix in
+the format `tt(.)var(identifier)tt(.)' This currently has no special
+meaning to the shell, but provides a convenient means of grouping
+related parameters.  Expansions using a namespace em(must) include
+braces (tt({) and tt(})) as shown in the descriptions below, and
+only one namespace prefix is allowed.  Note that, for support of
+possible future features, the first `tt(.)' is optional, but omitting
+it is discouraged.
+
 In the expansions discussed below that require a pattern, the form of
 the pattern is the same as that used for filename generation;
 see noderef(Filename Generation).  Note that these patterns, along with
@@ -616,6 +632,8 @@ substitution on the expansion of parameter tt($i).
 
 In the following descriptions, `var(word)' refers to a single word
 substituted on the command line, not necessarily a space delimited word.
+The reference to `var(name)' in each description presumes any optional
+namespace prefix.
 
 startitem()
 item(tt(${)var(name)tt(}))(
@@ -665,7 +683,9 @@ item(tt(${)var(name)tt(:?)var(word)tt(}))(
 In the first form, if var(name) is set, or in the second form if var(name)
 is both set and non-null, then substitute its value; otherwise, print
 var(word) and exit from the shell.  Interactive shells instead return to
-the prompt.  If var(word) is omitted, then a standard message is printed.
+the prompt.  If var(word) is omitted, then a standard message is
+printed.  Note that var(word) is expanded even though its value
+is not substituted onto the command line.
 )
 enditem()
 
@@ -967,6 +987,11 @@ means the same thing as the more readable `(tt(%%qqq))'.  The
 following flags are supported:
 
 startitem()
+item(tt(!))(
+When the parameter being expanded is a named reference, the reference
+itself is examined and thus is em(not) resolved to its referent.  In
+ksh emulation, the parens around this flag are optional.
+)
 item(tt(#))(
 Evaluate the resulting words as numeric expressions and interpret
 these as character codes.  Output the corresponding characters.  Note
@@ -1093,7 +1118,7 @@ tt(KSH_ARRAYS) option a subscript `tt([*])' or `tt([@])' is needed
 to operate on the whole array, as usual.
 )
 item(tt(L))(
-Convert all letters in the result to lower case.
+Convert all letters in the result to lower case, like `tt(typeset -l)'.
 )
 item(tt(n))(
 Sort decimal integers numerically; if the first differing
@@ -1177,34 +1202,35 @@ of the parameter would usually appear. This string consists of keywords
 separated by hyphens (`tt(-)'). The first keyword in the string describes
 the main type, it can be one of `tt(scalar)', `tt(array)', `tt(integer)',
 `tt(float)' or `tt(association)'. The other keywords describe the type in
-more detail:
+more detail, in most cases corresponding to options of the `tt(typeset)'
+command:
 
 startitem()
 item(tt(local))(
 for local parameters
 )
 item(tt(left))(
-for left justified parameters
+for left justified parameters (tt(-L))
 )
 item(tt(right_blanks))(
-for right justified parameters with leading blanks
+for right justified parameters with leading blanks (tt(-R))
 )
 item(tt(right_zeros))(
-for right justified parameters with leading zeros
+for right justified parameters with leading zeros (tt(-Z))
 )
 item(tt(lower))(
 for parameters whose value is converted to all lower case when it is
-expanded
+expanded (tt(-l))
 )
 item(tt(upper))(
 for parameters whose value is converted to all upper case when it is
-expanded
+expanded (tt(-u))
 )
 item(tt(readonly))(
-for readonly parameters
+for readonly parameters (tt(-r))
 )
 item(tt(tag))(
-for tagged parameters
+for tagged parameters (tt(-t))
 )
 item(tt(tied))(
 for parameters tied to another parameter in the manner of tt(PATH)
@@ -1212,16 +1238,20 @@ for parameters tied to another parameter in the manner of tt(PATH)
 special parameters or user-defined with `tt(typeset -T)'
 )
 item(tt(export))(
-for exported parameters
+for exported parameters (tt(-x) or `tt(export)')
 )
 item(tt(unique))(
-for arrays which keep only the first occurrence of duplicated values
+for arrays which keep only the first occurrence of duplicated values (tt(-U))
 )
 item(tt(hide))(
-for parameters with the `hide' flag
+for parameters with the `hide' flag (tt(-h))
 )
 item(tt(hideval))(
-for parameters with the `hideval' flag
+for parameters with the `hideval' flag (tt(-H))
+)
+item(tt(nameref))(
+for named references (tt(typeset -n)) either having an empty value or
+when combined with `tt(!)' as in `tt(${LPAR()!t)tt(RPAR()var(rname)})'
 )
 item(tt(special))(
 for special parameters defined by the shell
@@ -1229,10 +1259,10 @@ for special parameters defined by the shell
 enditem()
 )
 item(tt(u))(
-Expand only the first occurrence of each unique word.
+Expand only the first occurrence of each unique word, like `tt(typeset -U)'.
 )
 item(tt(U))(
-Convert all letters in the result to upper case.
+Convert all letters in the result to upper case, like `tt(typeset -u)'.
 )
 item(tt(v))(
 Used with tt(k), substitute (as two consecutive words) both the key
@@ -1520,6 +1550,103 @@ Include the unmatched portion in the result (the em(R)est).
 )
 enditem()
 
+subsect(Named References)
+cindex(named references)
+cindex(namerefs)
+cindex(reference variables)
+cindex(parameters, nameref)
+The command
+ifzman()
+indent(tt(typeset -n )var(pname)tt(=)var(rname))
+
+initializes a parameter var(pname) as a reference to a second
+parameter var(rname).  With the few exceptions described here, when
+var(pname) is used in any of the expansion forms described above, the
+parameter var(rname) is expanded instead.  This is similar to the
+action of the `tt((P))' expansion flag, but when var(rname) has itself
+been declared a named reference, that third parameter referenced by
+var(pname) is also expanded, and so on.  With `tt((P))' this must be
+done explicitly, so for example
+tt(${LPAR()P)tt(RPAR()${LPAR()P)tt(RPAR())var(name)tt(}}).
+
+Unlike `tt((P))', named references in substitutions that perform
+assignment, such as tt(${)var(pname)tt(::=)var(word)tt(}), do not
+create new arrays when var(rname) is in the form of an array element
+or slice and no such array (or associative array) is presently set.
+This includes arrays declared, but not initialized, when the option
+tt(TYPESET_TO_UNSET) is in effect.  The var(word) is substituted but
+no assignment occurs.
+
+Also unlike `tt((P))' named references always expand parameters at
+the scope in which var(rname) existed when `tt(typeset -n)' was
+called.  This can be used to expand or assign parameters from an
+earlier scope even if a local of the same name has been declared at
+a later scope.  Example:
+ifzman()
+example(tt(caller=OUTER)
+tt(func LPAR()RPAR() {)
+tt(  print before local: $caller)
+tt(  typeset -n outer=$1)
+tt(  local caller=INNER)
+tt(  print by reference: $outer)
+tt(  outer=RESULT)
+tt(})
+tt(func caller)
+tt(print after func: $caller))
+
+displays the output
+ifzman()
+example(tt(before local: OUTER)
+tt(by reference: OUTER)
+tt(after func: RESULT))
+
+To force a named reference to refer to the outer scope, even if a local
+has already been declared, add the tt(-u) option when declaring the
+named reference.  In this case var(rname) should already exist in the
+outer scope, otherwise the behavior of assignment through var(pname)
+is not defined and may change the scope of the reference or fail with
+a status of 1.  Example of correct usage:
+ifzman()
+example(tt(caller=OUTER)
+tt(func LPAR()RPAR() {)
+tt(  print before local: $caller)
+tt(  local caller=INNER)
+tt(  print after local: $caller)
+tt(  typeset -n -u outer=$1)
+tt(  print by reference: $outer)
+tt(  outer=RESULT)
+tt(})
+tt(func caller)
+tt(print after func: $caller))
+
+Note, however, that named references to em(special) parameters acquire
+the behavior of the special parameter, regardless of the scope where
+the reference is declared.
+
+When var(rname) includes an array subscript, the subscript expression
+is interpreted at the time tt(${)var(pname)tt(}) is expanded.  Any
+form of subscript is allowed, including those that select individual
+elements, substrings of scalar strings, or multiple elements as with
+array slices or the `tt((i))', `tt((I))', `tt((r))', `tt((R))' and
+`tt((w))' subscript flags.  However, the subscript is evaluated with
+the tt(NO_EXEC) option in effect, so command substitution and other
+similar constructs produce no output, although are not syntactically
+excluded.
+
+When var(rname) is an array (but not an array element or slice), the
+named reference may also be used in substitutions requiring an
+var(arrayname), so these are equivalent:
+ifzman()
+example(tt(${)var(name)tt(:|)var(rname)tt(})
+tt(${)var(name)tt(:|)var(pname)tt(}))
+
+Expansions of the form `tt(${LPAR()t)tt(RPAR())var(pname)tt(})' expand
+the type information of var(rname), unless var(rname) is empty, in which
+case the expansion is `tt(nameref)', or when no variable var(rname)
+exists, in which case the expansion is empty.
+
+See also ifzman(zmanref(zshparam))ifnzman(noderef(Parameters)).
+
 subsect(Rules)
 cindex(parameter expansion rules)
 cindex(rules, parameter expansion)
@@ -1542,12 +1669,16 @@ substitutions; the nested substitution will return either a scalar or an
 array as determined by the flags, possibly adjusted for quoting.  All the
 following steps take place where applicable at all levels of substitution.
 
-Note that, unless the `tt((P))' flag is present, the flags and any
+Note that, unless the `tt((P))' flag or a named reference is present,
+the flags and any
 subscripts apply directly to the value of the nested substitution; for
 example, the expansion tt(${${foo}}) behaves exactly the same as
-tt(${foo}).  When the `tt((P))' flag is present in a nested substitution,
+tt(${foo}).  When a named reference or the `tt((P))' flag is used in a
+nested substitution,
 the other substitution rules are applied to the value em(before) it is
 interpreted as a name, so tt(${${(P)foo}}) may differ from tt(${(P)foo}).
+When both a named reference and the `tt((P))' flag appear, the named
+reference is resolved before `tt((P))' is applied.
 
 At each nested level of substitution, the substituted words undergo all
 forms of single-word substitution (i.e. not filename generation), including
@@ -1773,23 +1904,65 @@ sect(Command Substitution)
 cindex(command substitution)
 cindex(substitution, command)
 A command enclosed in parentheses preceded by a dollar sign, like
-`tt($LPAR())...tt(RPAR())', or quoted with grave
-accents, like `tt(`)...tt(`)', is replaced with its standard output, with
-any trailing newlines deleted.
-If the substitution is not enclosed in double quotes, the
-output is broken into words using the tt(IFS) parameter.
+`tt($LPAR())...tt(RPAR())', or quoted with grave accents, like
+`tt(`)...tt(`)', is executed in a subshell and replaced by its
+standard output, with any trailing newlines deleted.  If the
+substitution is not enclosed in double quotes, the output is broken
+into words using the tt(IFS) parameter.
 vindex(IFS, use of)
 
 The substitution `tt($LPAR()cat) var(foo)tt(RPAR())' may be replaced
 by the faster `tt($LPAR()<)var(foo)tt(RPAR())'.  In this case var(foo)
 undergoes single word shell expansions (em(parameter expansion),
 em(command substitution) and em(arithmetic expansion)), but not
-filename generation.
+filename generation.  No subshell is created.
 
 If the option tt(GLOB_SUBST) is set, the result of any unquoted command
 substitution, including the special form just mentioned, is eligible for
 filename generation.
 
+A command with a leading pipe character, enclosed in braces prefixed by
+a dollar sign, as in `tt(${|)...tt(})', is executed in the current shell
+context, rather than in a subshell, and is replaced by the value of the
+parameter tt(REPLY) at the end of the command.  There em(must not) be
+any whitespace between the opening brace and the pipe character.  Any
+prior value of tt($REPLY) is saved and restored around this substitution,
+in the manner of a function local parameter.  Other parameters declared
+within the substitution also behave as locals, as if in a function,
+unless `tt(typeset -g)' is used.  Trailing newlines are em(not) deleted
+from the final replacement in this case, and it is subject to filename
+generation in the same way as `tt($LPAR())...tt(RPAR())' but is em(not)
+split on tt(IFS) unless the tt(SH_WORD_SPLIT) option is set.
+
+cindex(substitution, command, current shell)
+cindex(substitution, command, non forking)
+cindex(substitution, nofork)
+Substitutions of the form `tt(${{)var(param)tt(}) ...tt(})' are similar,
+except that the substitution is replaced by the value of the parameter
+named by var(param).  No implicit save or restore applies to var(param)
+and var(param) should em(not) be declared within the command.  No space
+is allowed within `tt(${{)' and space or newline is required after
+`tt({)var(param)tt(})'.  The var(param) may include a subscript, and if,
+after evaluating the expression, var(param) names an array, then array
+expansion rules apply to the final substitution.
+
+A command enclosed in braces preceded by a dollar sign, and set off from
+the braces by whitespace, like `tt(${ )...tt( })', is replaced by its
+standard output.  Like `tt(${|)...tt(})' and unlike
+`tt($LPAR())...tt(RPAR())', the command executes in the current shell
+context with function local behaviors and does not create a subshell.
+Word splitting does not apply unless tt(SH_WORD_SPLIT) is set, but a
+single trailing newline is stripped unless the substitution is enclosed
+in double quotes.
+
+Note that because `tt(${|)...tt(})' and the two related substitutions
+must be parsed at once as both string tokens and commands, all other
+braces (`tt({)' or `tt(})') within the command either must be quoted,
+or must appear in syntactically valid pairs, such as around complex
+commands, function bodies, or parameter references.  Furthermore,
+comments are always recognized, even when tt(NO_INTERACTIVE_COMMENTS)
+is in effect.
+
 texinode(Arithmetic Expansion)(Brace Expansion)(Command Substitution)(Expansion)
 sect(Arithmetic Expansion)
 cindex(arithmetic expansion)
@@ -1970,34 +2143,24 @@ tt(/home/pws/perforce).  In this simple case a static name for the
 directory would be just as effective.
 
 example(zsh_directory_name+LPAR()RPAR() {
-  emulate -L zsh
-  setopt extendedglob
+  emulate -L zsh -o extendedglob
   local -a match mbegin mend
-  if [[ $1 = d ]]; then
-    # turn the directory into a name
-    if [[ $2 = (#b)(/home/pws/perforce/)([^/]##)* ]]; then
-      typeset -ga reply
-      reply=(p:$match[2] $(( ${#match[1]} + ${#match[2]} )) )
-    else
-      return 1
-    fi
-  elif [[ $1 = n ]]; then
-    # turn the name into a directory
-    [[ $2 != (#b)p:(?*) ]] && return 1
-    typeset -ga reply
-    reply=(/home/pws/perforce/$match[1])
-  elif [[ $1 = c ]]; then
-    # complete names
-    local expl
-    local -a dirs
-    dirs=(/home/pws/perforce/*(/:t))
-    dirs=(p:${^dirs})
-    _wanted dynamic-dirs expl 'dynamic directory' compadd -S\] -a dirs
-    return
-  else
-    return 1
-  fi
-  return 0
+  local base=/home/pws/perforce
+  case $1 in
+  ( d )  # Turn the directory into a name.
+    [[ $2 == (#b)($base/)([^/]##)* ]] &&
+        reply=( p:$match[2] $(( $#match[1] + $#match[2] )) )
+  ;;
+  ( n )  # Turn the name into a directory.
+    [[ $2 == (#b)p:(?*) ]] &&
+        reply=( $base/$match[1] )
+  ;;
+  ( c )  # Complete names.
+    local -a dirs=( $base/*(/:t) )
+    # Completion system populates $expl with flags for compadd.
+    compadd "$expl[@]" p:$^dirs
+  ;;
+  esac
 })
 
 texinode(Static named directories)(`=' expansion)(Dynamic named directories)(Filename Expansion)
@@ -2987,9 +3150,10 @@ so both can be used on the same glob expression; for example by writing
 )
 enditem()
 
-More than one of these lists can be combined, separated by commas. The
-whole list matches if at least one of the sublists matches (they are
-`or'ed, the qualifiers in the sublists are `and'ed).  Some qualifiers,
+Multiple consecutive qualifiers are joined into a list by implicit logical AND.
+More than one of these lists can be combined using comma `tt(,)' as logical OR.
+The whole list matches if at least one of the sublists matches.
+Some qualifiers,
 however, affect all matches generated, independent of the sublist in
 which they are given.  These are the qualifiers `tt(M)', `tt(T)',
 `tt(N)', `tt(D)', `tt(n)', `tt(o)', `tt(O)' and the subscripts given
diff --git a/Doc/Zsh/files.yo b/Doc/Zsh/files.yo
index 65debe044..c6c7da307 100644
--- a/Doc/Zsh/files.yo
+++ b/Doc/Zsh/files.yo
@@ -14,7 +14,7 @@ cindex(zshenv)
 Commands are first read from tt(zshenv()); this cannot be overridden.
 Subsequent behaviour is modified by the tt(RCS) and
 tt(GLOBAL_RCS) options; the former affects all startup files, while the
-second only affects global startup files (those shown here with an
+second only affects global startup files (those shown here with a
 path starting with a tt(/)).  If one of the options
 is unset at any point, any subsequent startup file+LPAR()s+RPAR()
 of the corresponding
diff --git a/Doc/Zsh/func.yo b/Doc/Zsh/func.yo
index 12db3f56a..7b71e34e9 100644
--- a/Doc/Zsh/func.yo
+++ b/Doc/Zsh/func.yo
@@ -13,6 +13,43 @@ Functions are executed like commands with the arguments
 passed as positional parameters.
 (See noderef(Command Execution).)
 
+Parameters declared by any of the `tt(typeset)' family of commands
+during the execution of a function become em(local) to the function
+unless the `tt(-g)' option is used.  This is the em(scope) of the
+parameter, which extends dynamically to any other functions called by
+the declaring function.  In most cases, local parameters take the
+place of any other parameter having the same name that was assigned or
+declared in an earlier function scope.
+(See noderef(Local Parameters).)
+
+A named parameter declared with the `tt(-n)' option to any of the
+`tt(typeset)' commands becomes a reference to a parameter in scope at
+the time of assignment to the named reference, which may be at a
+different call level than the declaring function.  For this reason,
+it is good practice to declare a named reference as soon as the
+referent parameter is in scope, and as early as possible in the
+function if the reference is to a parameter in a calling scope.
+
+A typical use of named references is to pass the name
+of the referent as a positional parameter.  In this case it is
+good practice to use the tt(-u) option to reference the calling
+scope.  For example,
+ifzman()
+example(pop+LPAR()RPAR() {
+  local -nu ref=$1
+  local last=$ref[$#ref]
+  ref[$#ref]=LPAR()RPAR()
+  print -r -- $last
+}
+array=LPAR() a list of five values RPAR()
+pop array)
+
+prints the word `tt(values)' and shortens `tt($array)' to
+`tt(LPAR() a list of five RPAR())'.  With tt(-nu), `tt(ref)' becomes a
+reference to `tt(array)' in the caller.  There are no local parameters in
+tt(pop) at the time `tt(ref=$1)' is assigned, so in this example tt(-u)
+could have been omitted, but it makes the intention clear.
+
 Functions execute in the same process as the caller and
 share all files
 and present working directory with the
diff --git a/Doc/Zsh/grammar.yo b/Doc/Zsh/grammar.yo
index f8f4ada86..b80f9750c 100644
--- a/Doc/Zsh/grammar.yo
+++ b/Doc/Zsh/grammar.yo
@@ -100,14 +100,15 @@ More generally, a list can be seen as a set of any shell commands
 whatsoever, including the complex commands below; this is implied wherever
 the word `list' appears in later descriptions.  For example, the commands
 in a shell function form a special sort of list.
+
 texinode(Precommand Modifiers)(Complex Commands)(Simple Commands & Pipelines)(Shell Grammar)
 sect(Precommand Modifiers)
 cindex(precommand modifiers)
 cindex(modifiers, precommand)
-A simple command may be preceded by a em(precommand modifier),
-which will alter how the command is interpreted.  These modifiers are
-shell builtin commands with the exception of tt(nocorrect) which is
-a reserved word.
+With the exception of tt(nocorrect), which is a reserved word that
+affects further parsing when it is found in command position, each
+of the following builtin commands is a em(precommand modifier) which
+may precede a simple command to alter how that command is interpreted.
 
 startitem()
 findex(-)
@@ -158,8 +159,7 @@ before any parsing is done.  It has no effect in non-interactive shells.
 )
 findex(noglob)
 item(tt(noglob))(
-Filename generation (globbing) is not performed on any of
-the words.
+Filename generation (globbing) is not performed on any of the words.
 )
 enditem()
 texinode(Complex Commands)(Alternate Forms For Complex Commands)(Precommand Modifiers)(Shell Grammar)
@@ -187,6 +187,12 @@ Expand the list of var(word)s, and set the parameter
 var(name) to each of them in turn, executing var(list)
 each time.  If the `tt(in) var(word)' is omitted,
 use the positional parameters instead of the var(word)s.
+If any var(name) has been declared as a named reference,
+the corresponding var(word) is treated as the name of a
+parameter and var(name) is made a reference to that.
+Note that for the positional parameters, this treats the
+value of each positional as parameter name rather than
+creating a reference to the position.
 
 The var(term) consists of one or more newline or tt(;)
 which terminate the var(word)s, and are optional when the
@@ -536,7 +542,7 @@ itemiz(Errors creating command or process substitutions)
 itemiz(Syntax errors in glob qualifiers)
 itemiz(File generation errors where not caught by the option tt(BAD_PATTERN))
 itemiz(All bad patterns used for matching within case statements)
-itemiz(File generation failures where not caused by tt(NO_MATCH) or
+itemiz(File generation failures where not caused by tt(NOMATCH) or
 similar options)
 itemiz(All file generation errors where the pattern was used to create a
 multio)
diff --git a/Doc/Zsh/mod_hlgroup.yo b/Doc/Zsh/mod_hlgroup.yo
new file mode 100644
index 000000000..efe8934a1
--- /dev/null
+++ b/Doc/Zsh/mod_hlgroup.yo
@@ -0,0 +1,25 @@
+COMMENT(!MOD!zsh/hlgroup
+Alternative views of highlighting groups
+!MOD!)
+The tt(zsh/hlgroup) module defines special parameters that represent
+highlighting groups in different forms to ease the use of the groups when
+configuring other tools.
+
+In each case, these are readonly associative arrays where accessing elements
+uses values from the underlying tt(.zle.hlgroups) variable.
+
+startitem()
+vindex(.zle.esc)
+item(tt(.zle.esc))(
+This associative array contains the literal escape sequences used to apply the
+highlighting for each group. An example use would be when setting the
+tt(LESS_TERMCAP_xx) environment variables for the tt(less) pager.
+)
+vindex(.zle.sgr)
+item(tt(.zle.sgr))(
+Where highlighting makes use of CSI escape sequences, this parameter contains
+the "Select Graphic Rendition" number sequence. This is useful with, for
+example the tt(GREP_COLORS) and  tt(LSCOLORS) environment variables and the
+tt(list-colors) style.
+)
+enditem()
diff --git a/Doc/Zsh/mod_ksh93.yo b/Doc/Zsh/mod_ksh93.yo
new file mode 100644
index 000000000..7508758aa
--- /dev/null
+++ b/Doc/Zsh/mod_ksh93.yo
@@ -0,0 +1,243 @@
+COMMENT(!MOD!zsh/ksh93
+Extended ksh93 compatibility for "emulate ksh"
+!MOD!)
+cindex(ksh93)
+The tt(zsh/ksh93) module provides one builtin and several parameters to
+improve compatibility with ksh93.  As of this writing, several ksh93
+features are still missing.
+
+subsect(Ksh Builtins)
+The single builtin provided by this module is:
+
+startitem()
+findex(nameref)
+cindex(named references, creating)
+item(tt(nameref) [ tt(-gur) ] var(pname)[tt(=)var(rname)])(
+Equivalent to tt(typeset -n )var(pname)tt(=)var(rname)
+
+However, tt(nameref) is a builtin command rather than a reserved word,
+so when var(rname) uses subscript syntax it must be quoted against
+globbing.  Subscripts in referenced parameters are not supported in
+ksh93, so this is not a significant compatibility issue.
+)
+enditem()
+
+subsect(Ksh Parameters)
+cindex(parameters, ksh)
+Parameters supplied by this module that are marked with `<K>' below
+are available only when ksh emulation is active before entry to the
+shell function, that is, `tt(emulate ksh)' locally to a function does
+not populate these parameters for that function.
+
+startitem()
+vindex(.sh.command)
+item(tt(.sh.command))(
+A named reference to `tt(ZSH_DEBUG_CMD)'
+)
+vindex(.sh.edchar)
+item(tt(.sh.edchar) <K>)(
+In a ZLE widget, equivalent to the `tt(KEYS)' special parameter.  In a
+future release, assignments to this parameter will affect the input
+stream seen by ZLE.
+)
+vindex(.sh.edcol)
+item(tt(.sh.edcol))(
+A named reference to the ZLE special parameter `tt(CURSOR)'.
+)
+vindex(.sh.edmode)
+item(tt(.sh.edmode) <K>)(
+In a ZLE widget, this parameter has the value tt(ESC) (tt($'\e')) if the
+tt(VI) option is set and the `tt(main)' keymap is selected.  This is
+intended for use with vi-mode key bindings (`tt(bindkey -v)').  In a
+future revision, assigning `tt(.sh.edchar=${.sh.edmode})' is expected
+to initiate `tt(vicmd)' mode when `tt(viins)' is active, and do
+nothing when `tt(vicmd)' is already active.
+)
+vindex(.sh.edtext)
+item(tt(.sh.edtext))(
+A named reference to the `tt(BUFFER)' special ZLE parameter.
+)
+vindex(.sh.file)
+item(tt(.sh.file))(
+A named reference to the `tt(ZSH_SCRIPT)' parameter.
+)
+vindex(.sh.fun)
+item(tt(.sh.fun) <K>)(
+In a shell function, the function's name.  Usually the same as `tt($0)',
+but not affected by tt(POSIX_ARGZERO) or tt(FUNCTION_ARGZERO) options.
+)
+vindex(.sh.level)
+item(tt(.sh.level) <K>)(
+In a shell function, initially set to the depth of the call stack. This
+may be assigned to change the apparent depth.  However, such assignment
+does not affect the scope of local parameters.
+)
+vindex(.sh.lineno)
+item(tt(.sh.lineno))(
+A named reference to the `tt(LINENO)' special parameter.
+)
+vindex(.sh.match)
+item(tt(.sh.match))(
+An array equivalent to the `tt(match)' parameter as assigned by the
+`tt(LPAR()#b)tt(RPAR())' extended globbing flag.  When the
+tt(KSH_ARRAYS) option is set, `tt(${.sh.match[0]})' gives the value of
+the `tt(MATCH)' parameter as set by the `tt(LPAR()#m)tt(RPAR())' extended
+globbing flag.  Currently, the tt(EXTENDED_GLOB) option must be enabled
+and those flags must be explicitly used in a pattern in order for these
+values of `tt(.sh.match)' to be set.
+)
+vindex(.sh.name)
+item(tt(.sh.name) <K>)(
+When the `tt(vared)' command is used, this parameter may be used in
+user-defined ZLE widgets to get the name of the variable being edited.
+A future release is expected to use this parameter in the implementation
+of "discipline functions".
+)
+vindex(.sh.subscript)
+item(tt(.sh.subscript) <K>)(
+When `tt(vared)' has been used on an array element, this parameter holds
+the array index (either a number, or an associative array key).
+)
+vindex(.sh.subshell)
+item(tt(.sh.subshell))(
+A named reference to the `tt(ZSH_SUBSHELL)' parameter.
+)
+vindex(.sh.value)
+item(tt(.sh.value) <K>)(
+In `tt(vared)' this is a named reference to the ZLE special `tt(BUFFER)'.
+A future release is expected to use this parameter in the implementation
+of "discipline functions".
+)
+vindex(.sh.version)
+item(tt(.sh.version))(
+A named reference to `tt(ZSH_PATCHLEVEL)'.
+)
+enditem()
+
+subsect(Future Compatibility)
+
+The following features of ksh93 are not currently supported but may be
+available in a future release.
+
+startitem()
+item(tt(namespace )var(ident)tt( { )var(list)tt( }))(
+This reserved word executes the current shell compound command
+tt({ )var(list)tt( }), with the special behavior that all functions
+and parameters `var(name)' declared within var(list) are implicitly
+prefixed to become `tt(.)var(ident)tt(.)var(name)', and similarly any
+reference to a function or parameter `var(name)' is searched for as
+`tt(.)var(ident)tt(.)var(name)' before falling back to `var(name)'.
+
+em(THIS FEATURE IS NOT YET IMPLEMENTED.)
+)
+item(tt(.sh.math) <K>)(
+This parameter is more accurately considered a namespace.  A function
+defintion of the form
+ifzman()
+indent(tt(function .sh.math.)var(name)tt( )var(ident)tt( ... { )var(list)tt( }))
+
+is equivalent to the native zsh definition
+ifzman()
+example(tt(function )var(name)tt( {)
+tt(  local )var(ident)tt(=$1 ...)
+tt(  )var(list)
+tt(})
+tt(functions -M )var(name)tt( 1 3))
+ifzman()
+Up to 3 var(ident) arguments, interpreted as floating point numbers,
+may be provided for a function defined with tt(.sh.math) in this way.
+The names (but not definitions) of all such functions are available
+via tt(${.sh.math[@]}).
+
+em(THIS FEATURE IS NOT YET IMPLEMENTED.)
+)
+item(tt(var(name)tt(.get)))(
+A shell function having this name, if defined, is invoked whenever the
+parameter tt(${)var(name)tt(}) is referenced, including by commands
+such as `tt(typeset -p)'.  If the special variable `tt(.sh.value)' is
+assigned by the function, that value is substituted instead of the
+true value of var(name).  This does not change the value of var(name),
+but there is no way to access the actual value without first removing
+the function.
+
+Additionally, an explicit reference to tt(${)var(name)tt(.get})
+calls the function var(name)tt(.get) even if there is no parameter
+`var(name)' and substitutes the standard output of the function.
+
+em(THIS FEATURE IS NOT YET IMPLEMENTED.)
+)
+xitem(tt(var(name)tt(.set)))
+item(tt(var(name)tt(.append)))(
+Shell functions having these names are invoked when the parameter
+var(name) is assigned or (for array types) has a new field appended.
+The function may change the result of the operation by assigning to
+the `tt(.sh.value)' special parameter, or block the change by
+unsetting `tt(.sh.value)'.
+
+Explicit reference to tt(${)var(name)tt(.set}) or tt(${)var(name)tt(.append})
+substitutes the standard output of the function.
+
+em(THIS FEATURE IS NOT YET IMPLEMENTED.)
+)
+item(tt(var(name)tt(.unset)))(
+When a function of this name is defined, it is called whenever the
+parameter var(name) would be unset.  The function must explicitly
+`tt(unset )var(name)', otherwise the variable remains set.
+
+em(THIS FEATURE IS NOT YET IMPLEMENTED.)
+)
+item(tt(typeset -C )var(name)[tt(=)var(values)tt( ...)])(
+Creates a em(compound variable).
+
+em(THIS FEATURE IS NOT YET IMPLEMENTED, and the syntax of var(values)
+is unlikely to be fully ksh compatible.)
+)
+enditem()
+
+subsect(Other Differences)
+
+The following features of ksh93 are not currently supported and there are
+no plans to implement them.
+
+startitem()
+item(var(pathdir)tt(/.paths))(
+Each directory var(pathdir) in the tt(PATH) parameter may contain a
+text file `tt(.paths)' which may define additional directories to
+be searched for function definitions (tt(FPATH)), external executables
+(tt(PATH)), and plugin files (similar to tt(MODULE_PATH)).
+
+em(THIS FEATURE IS UNLIKELY EVER TO BE IMPLEMENTED.)
+)
+item(tt(builtin -f )var(file))(
+Installs a new shell builtin command dynamically linked from var(file),
+where var(file) is found by a path search and the base name of the file
+is the name of the builtin to be added.
+
+Similar to `tt(zmodload -F zsh/)var(file)tt( +b:)var(file)'.
+
+em(THIS FEATURE IS UNLIKELY EVER TO BE IMPLEMENTED.)
+)
+item(tt(typeset -H )var(name)[tt(=)var(value)])(
+Used for em(host-name file mapping) on some operating systems.
+
+em(THIS FEATURE IS UNLIKELY EVER TO BE IMPLEMENTED.)
+)
+item(tt(typeset ){tt(PLUS()|-)}tt(M )var(mapname)tt( )var(name)[tt(=)var(value)])(
+Declares a character translation var(mapname) for values assigned to var(name).
+)
+xitem(tt(typeset -S))
+xitem(tt(typeset -T ) [tt(-f)] [ var(tname)tt(=LPAR())var(values)tt(RPAR()) ])
+item(tt(typeset -h )var(str))(
+Used to define em(typed variables) and properties of their em(sub-variables).
+The tt(-T) and tt(-h) options conflict with existing zsh usage.
+)
+item(tt(typeset -X )var(name)[tt(=)var(value)])(
+Declares a floating-point variable displayed in hexadecimal format.
+)
+item(tt(typeset -b )var(name)[tt(=)var(value)])(
+Declares a parameter stored in em(base64) format.
+)
+item(tt(typeset -m )var(newname)tt(=)var(oldname))(
+em(Moves) var(oldname) to var(newname).  Conflicts with native zsh usage.
+)
+enditem()
diff --git a/Doc/Zsh/mod_parameter.yo b/Doc/Zsh/mod_parameter.yo
index f3bcd7957..3defef2b7 100644
--- a/Doc/Zsh/mod_parameter.yo
+++ b/Doc/Zsh/mod_parameter.yo
@@ -125,7 +125,16 @@ zmanref(zshexpn)
 ifnzman(\
 noderef(Parameter Expansion)
 )\
-.
+. The value may also be `tt(undefined)' indicating a parameter that
+may be autoloaded from a module but has not yet been referenced.
+When the key is the name of a named reference, the value is
+`tt(nameref-)' prepended to the type of the referenced parameter,
+for example
+ifzman()
+example(tt(% typeset -n parms=parameters)
+tt(% print -r ${parameters[parms]})
+tt(nameref-association-readonly-hide-hideval-special))
+
 Setting or unsetting keys in this array is not possible.
 )
 vindex(modules)
diff --git a/Doc/Zsh/mod_pcre.yo b/Doc/Zsh/mod_pcre.yo
index c2817f519..41fab4475 100644
--- a/Doc/Zsh/mod_pcre.yo
+++ b/Doc/Zsh/mod_pcre.yo
@@ -20,12 +20,12 @@ including those that indicate newline.
 )
 findex(pcre_study)
 item(tt(pcre_study))(
-Studies the previously-compiled PCRE which may result in faster
-matching.
+Requests JIT compilation for the previously-compiled PCRE which
+may result in faster matching.
 )
 findex(pcre_match)
 item(tt(pcre_match) [ tt(-v) var(var) ] [ tt(-a) var(arr) ] \
-[ tt(-n) var(offset) ] [ tt(-b) ] var(string))(
+[ tt(-A) var(assoc) ] [ tt(-n) var(offset) ] [ tt(-bd) ] var(string))(
 Returns successfully if tt(string) matches the previously-compiled
 PCRE.
 
@@ -36,7 +36,9 @@ substrings, unless the tt(-a) option is given, in which
 case it will set the array var(arr).  Similarly, the variable
 tt(MATCH) will be set to the entire matched portion of the
 string, unless the tt(-v) option is given, in which case the variable
-var(var) will be set.
+var(var) will be set. Furthermore, any named captures will
+be stored in the associative array tt(.pcre.match) unless an
+alternative is given with tt(-A).
 No variables are altered if there is no successful match.
 A tt(-n) option starts searching for a match from the
 byte var(offset) position in var(string).  If the tt(-b) option is given,
@@ -67,6 +69,15 @@ print -l $accum)
 )
 enditem()
 
+If the regular expression contains callouts, these are executed as shell code.
+During the execution of the callout, the string the regular expression is
+matching against is available in the parameter tt(.pcre.subject). If there is a
+non-zero return status from the shell code, the callout does not match.
+
+The option tt(-d) uses the alternative breadth-first DFA search algorithm of
+pcre. This sets tt(match), or the array given with tt(-a), to all the matches
+found from the same start point in the subject.
+
 The tt(zsh/pcre) module makes available the following test condition:
 
 startitem()
diff --git a/Doc/Zsh/mod_private.yo b/Doc/Zsh/mod_private.yo
index 184fa2be8..24c099f38 100644
--- a/Doc/Zsh/mod_private.yo
+++ b/Doc/Zsh/mod_private.yo
@@ -16,9 +16,10 @@ The tt(private) builtin accepts all the same options and arguments as tt(local)
 (ifzman(zmanref(zshbuiltins))ifnzman(noderef(Shell Builtin Commands))) except
 for the `tt(-)tt(T)' option.  Tied parameters may not be made private.
 
-The `tt(-)tt(p)' option is presently a no-op because the state of
-private parameters cannot reliably be reloaded.  This also applies
-to printing private parameters with `tt(typeset -p)'.
+The `tt(-)tt(p)' option is presently disabled because the state of
+private parameters cannot reliably be reloaded.  When `tt(typeset -)tt(p)'
+outputs a private parameter, it is treated as a local with the
+`tt(-)tt(h)' (hide) option enabled.
 
 If used at the top level (outside a function scope), tt(private) creates a
 normal parameter in the same manner as tt(declare) or tt(typeset).  A
@@ -84,6 +85,14 @@ created outside the local scope when it was not previously declared.)
 itemiz(An exported private remains in the environment of inner scopes but
 appears unset for the current shell in those scopes.  Generally, exporting
 private parameters should be avoided.)
+itemiz(Current shell command substitutions such as `tt(${|)...tt(})',
+`tt(${|)var(var)tt(|)...tt(})' and `tt(${ )...tt( })' may read and assign
+private parameters from the enclosing function.)
+itemiz(Declaring a private parameter in a current shell command substitution
+limits that parameter to the scope of the command substitution, just as if
+the parameter were declared in a function.  This also prevents access by
+any enclosed current shell command substitutions, but other substitutions
+may use the private parameter because those have the same calling scope.)
 enditemize()
 
 Note that this differs from the static scope defined by compiled languages
diff --git a/Doc/Zsh/mod_zselect.yo b/Doc/Zsh/mod_zselect.yo
index faf59c165..42287f116 100644
--- a/Doc/Zsh/mod_zselect.yo
+++ b/Doc/Zsh/mod_zselect.yo
@@ -13,7 +13,7 @@ blocks until a file descriptor is ready for reading or writing, or has an
 error condition, with an optional timeout.  If this is not available on
 your system, the command prints an error message and returns status 2
 (normal errors return status 1).  For more information, see your system's
-documentation for manref(select)(3).  Note there is no connection with the
+documentation for manref(select)(2).  Note there is no connection with the
 shell builtin of the same name.
 
 Arguments and options may be intermingled in any order.  Non-option
diff --git a/Doc/Zsh/mod_zutil.yo b/Doc/Zsh/mod_zutil.yo
index 3cf9e5028..9946618d6 100644
--- a/Doc/Zsh/mod_zutil.yo
+++ b/Doc/Zsh/mod_zutil.yo
@@ -11,6 +11,7 @@ xitem(tt(zstyle) [ tt(-L) [ var(metapattern) [ var(style) ] ] ])
 xitem(tt(zstyle) [ tt(-e) | tt(-) | tt(-)tt(-) ] var(pattern) var(style) var(string) ...)
 xitem(tt(zstyle -d) [ var(pattern) [ var(style) ... ] ])
 xitem(tt(zstyle -g) var(name) [ var(pattern) [ var(style) ] ])
+xitem(tt(zstyle -q) var(context) var(style))
 xitem(tt(zstyle -){tt(a)|tt(b)|tt(s)} var(context) var(style) var(name) [ var(sep) ])
 xitem(tt(zstyle -){tt(T)|tt(t)} var(context) var(style) [ var(string) ... ])
 item(tt(zstyle -m) var(context) var(style) var(pattern))(
@@ -105,6 +106,12 @@ enditem()
 The other forms can be used to look up or test styles for a given context.
 
 startitem()
+item(tt(zstyle -q) var(context) var(style))(
+Return tt(0) if var(style) is defined in var(context).  This does not
+evaluate expressions defined by tt(zstyle -e) and does not examine any
+values set by var(style).  The expected use is to test whether a style
+has been defined for var(context) before asserting a new style.
+)
 item(tt(zstyle -s) var(context) var(style) var(name) [ var(sep) ])(
 The parameter var(name) is set to the value of the style interpreted as a
 string.  If the value contains several strings they are concatenated with
diff --git a/Doc/Zsh/options.yo b/Doc/Zsh/options.yo
index bf73664c9..c3af8dd33 100644
--- a/Doc/Zsh/options.yo
+++ b/Doc/Zsh/options.yo
@@ -1214,6 +1214,9 @@ Note that, when the tt(HASH_LIST_ALL) option is not set or when some
 directories in the path are not readable, this may falsely report spelling
 errors the first time some commands are used.
 
+Refer to the shell variable tt(SPROMPT) for an explanation of the
+`tt([nyae])' (no/yes/abort/edit) prompt that is offered.
+
 The shell variable tt(CORRECT_IGNORE) may be set to a pattern to
 match words that will never be offered as corrections.
 )
@@ -1222,7 +1225,10 @@ pindex(NO_CORRECT_ALL)
 pindex(CORRECTALL)
 pindex(NOCORRECTALL)
 item(tt(CORRECT_ALL) (tt(-O)))(
-Try to correct the spelling of all arguments in a line.
+Try to correct the spelling of all arguments in a line, in order from
+left to right, treating each as a file name.  Answering `tt(a)' or
+`tt(e)' at any prompt stops all corrections, otherwise every correction
+is prompted for.
 
 The shell variable tt(CORRECT_IGNORE_FILE) may be set to a pattern to
 match file names that will never be offered as corrections.
@@ -1723,27 +1729,38 @@ pindex(NOERREXIT)
 cindex(exit status, trapping)
 item(tt(ERR_EXIT) (tt(-e), ksh: tt(-e)))(
 If a command has a non-zero exit status, execute the tt(ZERR)
-trap, if set, and exit.  This is disabled while running initialization
-scripts.
-
-The behaviour is also disabled inside tt(DEBUG) traps.  In this
-case the option is handled specially: it is unset on entry to
-the trap.  If the option tt(DEBUG_BEFORE_CMD) is set,
-as it is by default, and the option tt(ERR_EXIT) is found to have been set
-on exit, then the command for which the tt(DEBUG) trap is being executed is
-skipped.  The option is restored after the trap exits.
-
-Non-zero status in a command list containing tt(&&) or tt(||) is ignored
-for commands not at the end of the list.  Hence
-
-example(false && true)
-
-does not trigger exit.
+trap, if set, and exit.
+
+The option is ignored when executing the commands following tt(while),
+tt(until), tt(if), or tt(elif), a pipeline beginning with tt(!), or
+any command other than the last in command list containing tt(&&) or
+tt(||).  Hence neither `tt(if foo; then true; fi)', nor `tt(foo &&
+true)' trigger exit when tt(foo) returns with a non-zero exit status.
+Note that if tt(foo) is a function, the option is also ignored during
+its whole execution.
+
+The option is also ignored when executing a complex command (tt(if),
+tt(for), tt(while), tt(until), tt(repeat), tt(case), tt(select),
+tt(always), or a list in braces) if its exit status comes from a
+command executed while the option is ignored. Hence, the tt(if)
+command in `tt(if true; then false && true; fi)' does not trigger
+exit.
+
+Finally, the option is also ignored while running initialization
+scripts and inside tt(DEBUG) traps.  In the latter case, the option is
+handled specially: it is unset on entry to the trap.  If the option
+tt(DEBUG_BEFORE_CMD) is set, as it is by default, and the option
+tt(ERR_EXIT) is found to have been set on exit, then the command for
+which the tt(DEBUG) trap is being executed is skipped.  The option is
+restored after the trap exits.
 
 Exiting due to tt(ERR_EXIT) has certain interactions with asynchronous
 jobs noted in
 ifzman(the section JOBS in zmanref(zshmisc))\
 ifnzman(noderef(Jobs & Signals)).
+
+Note this behaviour is not disabled in interactive shells ---
+a non-zero status on the command line causes the shell to exit.
 )
 pindex(ERR_RETURN)
 pindex(NO_ERR_RETURN)
@@ -1752,26 +1769,29 @@ pindex(NOERRRETURN)
 cindex(function return, on error)
 cindex(return from function, on error)
 item(tt(ERR_RETURN))(
-If a command has a non-zero exit status, return immediately from the
-enclosing function.  The logic is similar to that for tt(ERR_EXIT),
-except that an implicit tt(return) statement is executed instead of an
-tt(exit).  This will trigger an exit at the outermost level of a
-non-interactive script.
-
-Normally this option inherits the behaviour of tt(ERR_EXIT) that
-code followed by `tt(&&)' `tt(||)' does not trigger a return.  Hence
-in the following:
-
-example(summit || true)
 
-no return is forced as the combined effect always has a zero return
-status.
-
-Note. however, that if tt(summit) in the above example is itself a
-function, code inside it is considered separately: it may force a return
-from tt(summit) (assuming the option remains set within tt(summit)), but
-not from the enclosing context.  This behaviour is different from
-tt(ERR_EXIT) which is unaffected by function scope.
+If a command has a non-zero exit status, return immediately from the
+enclosing function. Except as explained below, an implicit tt(return)
+statement is executed following the same logic described for
+tt(ERR_EXIT). This will trigger an exit at the outermost level of a
+non-interactive script.  At the top level of an interactive shell, it
+will trigger a return to the command prompt; in other words, the
+sequence of commands typed by the user may be thought of as a function
+for this purpose.
+
+Unlike for tt(ERR_EXIT), when a function is called while the option is
+being ignored, the option is NOT ignored during the execution of the
+function.  Hence, if tt(foo) in `tt(foo && true)' is a function, code
+inside it is considered separately: it may force a return from tt(foo)
+(assuming the option remains set within tt(foo)).
+
+Like for tt(ERR_EXIT), the option is ignored inside tt(DEBUG) traps
+but it's not unset on entry to the trap and setting or unsetting it
+inside the trap has no special effect.
+
+If tt(ERR_RETURN) and tt(ERR_EXIT) are both set, it may happen that
+both exit and return should be triggered. In that case only exit is
+triggered.
 )
 pindex(EVAL_LINENO)
 pindex(NO_EVAL_LINENO)
@@ -2550,10 +2570,12 @@ pindex(NO_EMACS)
 pindex(NOEMACS)
 item(tt(EMACS))(
 If ZLE is loaded, turning on this option has the equivalent effect
-of `tt(bindkey -e)'.  In addition, the VI option is unset.
+of `tt(bindkey -e)'.  In addition, the tt(VI) option is unset.
 Turning it off has no effect.  The option setting is
-not guaranteed to reflect the current keymap.  This option is
-provided for compatibility; tt(bindkey) is the recommended interface.
+not guaranteed to reflect the current keymap, and the tt(LOCALOPTIONS)
+option does not work correctly. This option is provided only for
+compatibility, and its use is highly discouraged.  tt(bindkey) is the
+recommended interface.
 )
 pindex(OVERSTRIKE)
 pindex(NO_OVERSTRIKE)
@@ -2582,10 +2604,12 @@ pindex(NO_VI)
 pindex(NOVI)
 item(tt(VI))(
 If ZLE is loaded, turning on this option has the equivalent effect
-of `tt(bindkey -v)'.  In addition, the EMACS option is unset.
+of `tt(bindkey -v)'.  In addition, the tt(EMACS) option is unset.
 Turning it off has no effect.  The option setting is
-not guaranteed to reflect the current keymap.  This option is
-provided for compatibility; tt(bindkey) is the recommended interface.
+not guaranteed to reflect the current keymap, and the tt(LOCALOPTIONS)
+option does not work correctly. This option is provided only for
+compatibility, and its use is highly discouraged.  tt(bindkey) is the
+recommended interface.
 )
 pindex(ZLE)
 pindex(NO_ZLE)
diff --git a/Doc/Zsh/params.yo b/Doc/Zsh/params.yo
index b543d1c38..02ce796a9 100644
--- a/Doc/Zsh/params.yo
+++ b/Doc/Zsh/params.yo
@@ -52,6 +52,20 @@ cindex(assignment)
 ifzman()
 indent(var(name)tt(=)var(value))
 
+cindex(namespace)
+The var(name) in an assignment may optionally include a em(namespace)
+prefix:
+ifzman()
+indent(tt(.)var(namespace)tt(.)var(parameter)tt(=)var(value))
+
+Namespaces have no special meaning to the shell except that parameters
+with a `tt(.)' prefix are not listed by the `tt(set)' builtin, nor
+shown by the `tt(typeset)' builtin unless explicitly named or the
+`tt(-m)' option is used.  They provide a convenient way to group
+related variables.  Note that, for support of possible future features,
+the first `tt(.)' is optional, but omitting it is discouraged.  Unlike
+ksh, a namespace need not be declared before it is referenced.
+
 In scalar assignment, var(value) is expanded as a single string, in
 which the elements of arrays are joined together; filename expansion is
 not performed unless the option tt(GLOB_ASSIGN) is set.
@@ -70,7 +84,8 @@ change its type to integer or float, and with tt(GLOB_ASSIGN) assigning a
 pattern to a variable may change its type to an array.
 
 To reference the value of a parameter, write `tt($)var(name)' or
-`tt(${)var(name)tt(})'.  See
+`tt(${)var(name)tt(})'.  The latter form is required when var(name)
+includes a namespace prefix.  See
 ifzman(em(Parameter Expansion) in zmanref(zshexpn))\
 ifnzman(noderef(Parameter Expansion))
 for complete details.  That section also explains the effect
@@ -80,10 +95,13 @@ startmenu()
 menu(Array Parameters)
 menu(Positional Parameters)
 menu(Local Parameters)
+menu(Named References)
 menu(Parameters Set By The Shell)
 menu(Parameters Used By The Shell)
 endmenu()
 texinode(Array Parameters)(Positional Parameters)()(Parameters)
+cindex(array parameters)
+cindex(parameters, array)
 sect(Array Parameters)
 To assign an array value, write one of:
 findex(set, use of)
@@ -566,6 +584,8 @@ entire second parameter concatenated with the filename generation pattern
 `tt([3,5])'.
 
 texinode(Positional Parameters)(Local Parameters)(Array Parameters)(Parameters)
+cindex(positional parameters)
+cindex(parameters, positional)
 sect(Positional Parameters)
 The positional parameters provide access to the command-line arguments
 of a shell function, shell script, or the shell itself; see
@@ -592,7 +612,9 @@ array assignment of the form `var(n)tt(=LPAR())var(value) ...tt(RPAR())' is
 allowed, and has the effect of shifting all the values at positions greater
 than var(n) by as many positions as necessary to accommodate the new values.
 
-texinode(Local Parameters)(Parameters Set By The Shell)(Positional Parameters)(Parameters)
+texinode(Local Parameters)(Named References)(Positional Parameters)(Parameters)
+cindex(local parameters)
+cindex(parameters, local)
 sect(Local Parameters)
 Shell function executions delimit scopes for shell parameters.
 (Parameters are dynamically scoped.)  The tt(typeset) builtin, and its
@@ -626,7 +648,53 @@ find the programs in tt(/new/directory) inside a function.
 Note that the restriction in older versions of zsh that local parameters
 were never exported has been removed.
 
-texinode(Parameters Set By The Shell)(Parameters Used By The Shell)(Local Parameters)(Parameters)
+texinode(Named References)(Parameters Set By The Shell)(Local Parameters)(Parameters)
+cindex(named references)
+cindex(references, named)
+sect(Named References)
+Zsh supports two different mechanisms for indirect parameter referencing:
+ifzman()
+example(tt(typeset )var(name)tt(=)var(rname)
+tt(print -r -- ${LPAR()P)tt(RPAR())var(name)tt(}))
+ifzman()
+example(tt(typeset -n )var(pname)tt(=)var(rname)
+tt(print -r -- ${)var(pname)tt(}))
+
+The `tt((P))' flag method is older and should be used when a script
+needs to be backwards-compatible.  This is described fully in
+the Parameter Expansion Flags section of
+ifzman(zmanref(zshexpn))ifnzman(noderef(Parameter Expansion)).  Zsh
+versions em(greater than) tt(5.9.0) are required for `tt(typeset -n)'.
+This manual was generated with Zsh tt(version()).
+
+When a em(named reference) is created with `tt(typeset -n)', all uses
+of var(pname) in assignments and expansions instead assign to or
+expand var(rname).  This also applies to `tt(unset )var(pname)' and to
+most subsequent uses of `tt(typeset)' with the exceptions of declaring
+a local in a called function, or updating a current-scope parameter with
+`tt(typeset -n)' or `tt(typeset +n)'. Thus to remove a named reference,
+use either `tt(unset -n )var(pname)' (preferred) or one of:
+ifzman()
+example(tt(typeset -n )var(pname=)
+tt(typeset +n )var(pname))
+
+followed by
+ifzman()
+indent(tt(unset )var(pname))
+
+An empty reference such as one of
+ifzman()
+example(tt(typeset -n )var(pname)
+tt(typeset -n )var(pname)tt(=)
+tt(typeset -n )var(pname)tt(=""))
+
+acts as a placeholder.  The first non-empty assignment to var(pname)
+initializes the reference, and subsequently any expansions of, or
+assignments to, var(pname) act on the referenced parameter.  This
+is explained in the Named References section of
+ifzman(zmanref(zshexpn))ifnzman(noderef(Parameter Expansion)).
+
+texinode(Parameters Set By The Shell)(Parameters Used By The Shell)(Named References)(Parameters)
 sect(Parameters Set By The Shell)
 In the parameter lists that follow, the mark `<S>' indicates that the
 parameter is special.  `<Z>' indicates that the parameter does not exist
@@ -681,9 +749,13 @@ vindex(argv)
 item(tt(argv) <S> <Z>)(
 Same as tt(*).  Assigning to tt(argv) changes the local positional
 parameters, but tt(argv) is em(not) itself a local parameter.
-Deleting tt(argv) with tt(unset) in any function deletes it everywhere,
-although only the innermost positional parameter array is deleted (so
-tt(*) and tt(@) in other scopes are not affected).
+Deleting tt(argv) with tt(unset) in any function deletes it everywhere.
+This can be avoided by declaring `tt(local +h argv)' before unsetting.
+Even when not so declared, only the innermost positional parameter
+array is deleted (so tt(*) and tt(@) in other scopes are not affected).
+
+A named reference to tt(argv) em(does not) permit a called function to
+access the positional parameters of its caller.
 )
 vindex(@)
 item(tt(@) <S>)(
@@ -712,7 +784,10 @@ last pipeline.
 )
 vindex(_)
 item(tt(_) <S>)(
-The last argument of the previous command.
+Initially, if tt(_) exists in the environment, then this parameter is set to
+its value. This value may be the full pathname of the current zsh
+executable or the script command file.
+Later, this parameter is set to the last argument of the previous command.
 Also, this parameter is set in the environment of every command
 executed to the full pathname of the command.
 )
@@ -879,7 +954,10 @@ has index 1, the signals are offset by 1 from the signal number
 used by the operating system.  For example, on typical Unix-like systems
 tt(HUP) is signal number 1, but is referred to as tt($signals[2]).  This
 is because of tt(EXIT) at position 1 in the array, which is used
-internally by zsh but is not known to the operating system.
+internally by zsh but is not known to the operating system. On many systems
+there is a block of reserved or unused signal numbers before the POSIX
+real-time signals so the array index can't be used as an accurate indicator
+of their signal number. Use, for example, tt(kill -l SIGRTMIN) instead.
 )
 vindex(TRY_BLOCK_ERROR)
 item(tt(TRY_BLOCK_ERROR) <S>)(
@@ -953,11 +1031,12 @@ Code specified by the tt(-c) option to the command line that invoked
 the shell.
 )
 item(tt(cmdsubst))(
-Command substitution using the tt(`)var(...)tt(`) or
-tt($+LPAR())var(...)tt(RPAR()) construct.
+Command substitution using of the tt(`)var(...)tt(`),
+tt($+LPAR())var(...)tt(RPAR()),tt(${{)var(name)tt(}) var(...)tt(}),
+tt(${|)var(...)tt(}), or tt(${ )var(...)tt( }) constructs.
 )
 item(tt(equalsubst))(
-File substitution using the tt(=+LPAR())var(...)tt(RPAR()) construct.
+The tt(=+LPAR())var(...)tt(RPAR()) form of process substitution.
 )
 item(tt(eval))(
 Code executed by the tt(eval) builtin.
@@ -985,13 +1064,13 @@ item(tt(globsort))(
 Code executed to order files by the tt(o) glob qualifier.
 )
 item(tt(insubst))(
-File substitution using the tt(<LPAR())var(...)tt(RPAR()) construct.
+The tt(<LPAR())var(...)tt(RPAR()) form of process substitution.
 )
 item(tt(loadautofunc))(
 Code read directly from a file to define an autoloaded function.
 )
 item(tt(outsubst))(
-File substitution using the tt(>LPAR())var(...)tt(RPAR()) construct.
+The tt(>LPAR())var(...)tt(RPAR()) form of process substitution.
 )
 item(tt(sched))(
 Code executed by the tt(sched) builtin.
@@ -1042,6 +1121,10 @@ item(tt(ZSH_EXECUTION_STRING))(
 If the shell was started with the option tt(-c), this contains
 the argument passed to the option.  Otherwise it is not set.
 )
+vindex(ZSH_EXEPATH)
+item(tt(ZSH_EXEPATH))(
+Full pathname of the executable file of the current zsh process.
+)
 vindex(ZSH_NAME)
 item(tt(ZSH_NAME))(
 Expands to the basename of the command used to invoke this instance
@@ -1251,15 +1334,18 @@ Internal field separators (by default space, tab, newline and NUL), that
 are used to separate words which result from
 command or parameter expansion and words read by
 the tt(read) builtin.  Any characters from the set space, tab and
-newline that appear in the IFS are called em(IFS white space).
+newline that appear in the tt(IFS) are called em(IFS white space).
 One or more IFS white space characters or one non-IFS white space
 character together with any adjacent IFS white space character delimit
 a field.  If an IFS white space character appears twice consecutively
-in the IFS, this character is treated as if it were not an IFS white
+in the tt(IFS), this character is treated as if it were not an IFS white
 space character.
 
 If the parameter is unset, the default is used.  Note this has
 a different effect from setting the parameter to an empty string.
+
+If tt(MULTIBYTE) option is on and tt(IFS) contains invalid characters in
+the current locale, it is reset to the default.
 )
 vindex(KEYBOARD_HACK)
 item(tt(KEYBOARD_HACK))(
@@ -1414,6 +1500,7 @@ An array (colon-separated list)
 of directories to search for commands.
 When this parameter is set, each directory is scanned
 and all files found are put in a hash table.
+Directories named by relative path are not scanned for hashing.
 )
 vindex(POSTEDIT)
 item(tt(POSTEDIT) <S>)(
@@ -1553,9 +1640,13 @@ All other prompt escapes are also allowed.
 
 The actions available at the prompt are tt([nyae]):
 startsitem()
-sitem(tt(n) +LPAR()`no'+RPAR() +LPAR()default+RPAR())(Discard the correction and run the command.)
-sitem(tt(y) +LPAR()`yes'+RPAR())(Make the correction and run the command.)
-sitem(tt(a) +LPAR()`abort'+RPAR())(Discard the entire command line without running it.)
+sitem(tt(n) +LPAR()`no'+RPAR() +LPAR()default+RPAR())(Discard the correction.
+If there are no more corrections, accept the command line, else (with
+tt(CORRECT_ALL)) prompt for the next.)
+sitem(tt(y) +LPAR()`yes'+RPAR())(Make the correction. If there are no more
+corrections, accept the command line.)
+sitem(tt(a) +LPAR()`abort'+RPAR())(Place the entire command line in the
+history for later edit, but without accepting it.)
 sitem(tt(e) +LPAR()`edit'+RPAR())(Resume editing the command line.)
 endsitem()
 )
@@ -1667,7 +1758,7 @@ well as any directory names.  The default is `tt(/tmp/zsh)'.
 vindex(TMPSUFFIX)
 item(tt(TMPSUFFIX))(
 A filename suffix which the shell will use for temporary files created
-by process substitutions (e.g., `tt(=LPAR()var(list)RPAR())').
+by process substitutions (e.g., `tt(=LPAR())var(list)tt(RPAR())').
 Note that the value should include a leading dot `tt(.)' if intended
 to be interpreted as a file extension.  The default is not to append
 any suffix, thus this parameter should be assigned only when needed
diff --git a/Doc/Zsh/prompt.yo b/Doc/Zsh/prompt.yo
index 909012c8e..de988ab7c 100644
--- a/Doc/Zsh/prompt.yo
+++ b/Doc/Zsh/prompt.yo
@@ -246,6 +246,14 @@ item(tt(%K) LPAR()tt(%k)RPAR())(
 Start (stop) using a different bacKground colour.  The syntax is
 identical to that for tt(%F) and tt(%f).
 )
+item(tt(%H))(
+Change all character visual attributes using a highlighting specification from
+the tt(.zle.hlgroups) associative array. The key is specified in following
+braces so, for example tt(%H{error}) will use the highlighting specification
+for the `error' group.  If the key is not found in the associative array then
+it has no effect.  Highlighting specifications are in the same format as for
+the tt(zle_highlight) parameter.
+)
 item(tt(%{)...tt(%}))(
 Include a string as a literal escape sequence.
 The string within the braces should not change the cursor
diff --git a/Doc/Zsh/restricted.yo b/Doc/Zsh/restricted.yo
index 33dfc96c6..a84fd28ea 100644
--- a/Doc/Zsh/restricted.yo
+++ b/Doc/Zsh/restricted.yo
@@ -65,10 +65,10 @@ variables.  Except for the few listed above, zsh does not restrict
 the setting of environment variables.
 
 If a `tt(perl)', `tt(python)', `tt(bash)', or other general purpose
-interpreted script it treated as a restricted
+interpreted script is treated as a restricted
 command, the user can work around the restriction by
 setting specially crafted `tt(PERL5LIB)', `tt(PYTHONPATH)',
-`tt(BASHENV)' (etc.) environment variables. On GNU systems, any
+`tt(BASH_ENV)' (etc.) environment variables. On GNU systems, any
 command can be made to run arbitrary code when performing character set
 conversion (including zsh itself) by setting a `tt(GCONV_PATH)'
 environment variable.  Those are only a few examples.
diff --git a/Doc/Zsh/zle.yo b/Doc/Zsh/zle.yo
index 2d033a0a1..31eb3f3ba 100644
--- a/Doc/Zsh/zle.yo
+++ b/Doc/Zsh/zle.yo
@@ -376,7 +376,7 @@ If the tt(-p) flag is given, the following string will be taken as
 the prompt to display at the left.  If the tt(-r) flag is given,
 the following string gives the prompt to display at the right.  If the
 tt(-h) flag is specified, the history can be accessed from ZLE. If the
-tt(-e) flag is given, typing tt(^D) (Control-D) on an empty line
+tt(-e) flag is given, typing tt(^D) (Control-D) in an empty buffer
 causes tt(vared) to exit immediately with a non-zero return value.
 
 The tt(-M) option gives a keymap to link to the tt(main) keymap during
@@ -2470,10 +2470,11 @@ command.  tt(run-help) is normally aliased to tt(man).
 tindex(vi-set-buffer)
 item(tt(vi-set-buffer) (unbound) (tt(")) (unbound))(
 Specify a buffer to be used in the following command.
-There are 37 buffers that can be specified:
+There are 39 buffers that can be specified:
 the 26 `named' buffers tt("a) to tt("z), the `yank' buffer tt("0),
-the nine `queued' buffers tt("1) to tt("9) and the `black hole' buffer
-tt("_).  The named buffers can also be specified as tt("A) to tt("Z).
+the nine `queued' buffers tt("1) to tt("9), the `black hole' buffer
+tt("_) and the system selection tt("*) and clipboard tt("+).
+The named buffers can also be specified as tt("A) to tt("Z).
 
 When a buffer is specified for a cut, change or yank command, the text
 concerned replaces the previous contents of the specified buffer. If
@@ -2482,6 +2483,10 @@ appended to the buffer instead of overwriting it. When using the tt("_)
 buffer, nothing happens. This can be useful for deleting text without
 affecting any buffers.
 
+Updating the system clipboard relies on specific support from the terminal.
+Reading it is not possible so a paste command with tt("*) or tt("+) will do
+nothing.
+
 If no buffer is specified for a cut or change command, tt("1) is used, and
 the contents of tt("1) to tt("8) are each shifted along one buffer;
 the contents of tt("9) is lost. If no buffer is specified for a yank
@@ -2686,6 +2691,9 @@ for different completions.
 item(tt(paste))(
 Following a command to paste text, the characters that were inserted.
 )
+item(tt(ellipsis))(
+Markers used to indicate where the text doesn't fit within the terminal.
+)
 enditem()
 
 When tt(region_highlight) is set, the contexts that describe a region DASH()-
@@ -2775,9 +2783,13 @@ This works similarly to the foreground colour, except the background is
 not usually affected by the bold attribute.
 )
 item(tt(bold))(
-The characters in the given context are shown in a bold font.
+The characters in the given context are shown with a bold font weight.
 Not all terminals distinguish bold fonts.
 )
+item(tt(faint))(
+The characters in the given context are shown with a faint font weight.
+Not all terminals distinguish faint fonts.
+)
 item(tt(standout))(
 The characters in the given context are shown in the terminal's standout
 mode.  The actual effect is specific to the terminal; on many terminals it
@@ -2791,6 +2803,21 @@ The characters in the given context are shown underlined.  Some
 terminals show the foreground in a different colour instead; in this
 case whitespace will not be highlighted.
 )
+item(tt(italic))(
+The characters in the given context are shown in a italic font.
+Not all terminals support italic fonts.
+)
+item(tt(hl=)var(group))(
+Use the specified highlighting group.  The var(group) is used as a key into
+the associative array tt(.zle.hlgroups) to determine the actual highlighting.
+)
+item(tt(layer=)var(layer))(
+The layer is used to determine precedence when multiple highlighting regions
+overlap. The var(layer) is a decimal integer, with higher numbers taking
+precedence over lower numbers. The default layer is 10 with 30 used as the
+default for tt(special), 20 for tt(region) and tt(isearch) and 15 for
+tt(paste).
+)
 enditem()
 
 The characters described above as `special' are as follows.  The
diff --git a/Etc/BUGS b/Etc/BUGS
index 72c313e88..dee115ee0 100644
--- a/Etc/BUGS
+++ b/Etc/BUGS
@@ -46,7 +46,18 @@ related, probably obsolete, vared special case for $TERM set to "emacs".
 ------------------------------------------------------------------------
 47561: [PATCH v4] vcs_info: choose backend by basedir
 ------------------------------------------------------------------------
-48091: Bug in compdescribe with matcher 'b:-=+'
+48091, 49276: Bug in compdescribe with matcher 'b:-=+'
 ------------------------------------------------------------------------
 users/26071: Strange behavior about option completion of "git push --f"
 ------------------------------------------------------------------------
+50930: If a conditional expression appears in a current-shell construct
+(such as { sleep 20 && print $? }) which is then suspended with ^Z, the
+return value of the left side of the expression is always 148 (SIGTSTP)
+and thus the expression is likely to be incorrectly interpreted.
+------------------------------------------------------------------------
+52521: Empty files and unreadable files cannot be removed using the
+mapfile module "unset 'mapfile[filename]'", and are not distinguished
+from files that do not exist.
+------------------------------------------------------------------------
+52747,52755: HIST_IGNORE_DUPS et. al. ignore syntactically significant
+quoted whitespace and can incorrectly exclude commands as duplicates.
diff --git a/Etc/FAQ.yo b/Etc/FAQ.yo
index 8c795685a..4e11637ea 100644
--- a/Etc/FAQ.yo
+++ b/Etc/FAQ.yo
@@ -101,6 +101,10 @@ Chapter 2:  How does zsh differ from...?
 2.6. Shouldn't zsh be more/less like ksh/(t)csh?
 2.7. What is zsh's support for Unicode/UTF-8?
 2.8. Why does my bash script report an error when I run it under zsh?
+2.9. What is a `namespace' anyway?
+2.10. What about named references?
+2.11. What is zsh's support for non-forking command substitution?
+2.12. Comparisons of forking and non-forking command substitution
 
 Chapter 3:  How to get various things to work
 3.1. Why does `$var' where `var="foo bar"' not do what I expect?
@@ -445,7 +449,14 @@ label(21)
      invoked with the appropriate name.  Including the command
      `emulate sh; setopt localoptions' in a shell function will
      turn on sh emulation for that function only.  In version 4 (and in
-     3.0.6 through 8), this can be abbreviated as `emulate -L sh'.
+     3.0.6 through 8), this can be abbreviated as `emulate -L sh';
+  myeit() in versions after 5.9, the myem(namespace) syntax and
+     myem(named references) (ksh mytt(nameref)) are available, but
+     differ in some details from the ksh93+ semantics;
+  myeit() also after 5.9, myem(non-forking command substitutions) are
+     available.  These are described by ksh as myem(a brace group preceded
+     by a dollar sign) (mytt(${ list;})), but zsh has both some added
+     features adopted from mksh, and some limitations, see link(2.11)(211)
    )
 
   The classic difference is word splitting, discussed in question \
@@ -496,9 +507,9 @@ tt(RM_STAR_SILENT),
 	those are a completely different type of object.)
     it()  Coprocesses are established by mytt(coproc); mytt(|&) behaves like
         csh.  Handling of coprocess file descriptors is also different.
-    it()  In mytt(cmd1 && cmd2 &), only mytt(cmd2) instead of the whole
-        expression is run in the background in zsh.  The manual implies
-        this is a bug.  Use mytt({ cmd1 && cmd2 } &) as a workaround.
+    it()  In mytt(cmd1 && cmd2 &), instead of backgrounding the whole
+        expression, only mytt(cmd2) is run in the background in zsh.
+        Use mytt(( cmd1 && cmd2 ) &) as a workaround.
   )
   it() Command line substitutions, globbing etc.:
   itemization(
@@ -960,6 +971,164 @@ label(28)
   languages and adjusting it accordingly, just like you would
   when translating a book from American English to British English.
 
+sect(What is a mytt(namespace) anyway?)
+label(29)
+
+  As of this writing, namespaces in zsh are little more than syntactic
+  sugar for grouping related parameters.  For example, as of the update
+  to PCRE2, the parameters ${.pcre.match} and ${.pcre.subject} are used
+  for regular expression substring capture.  The mytt(.pcre.) part is
+  the namespace, and when you refer to a parameter that has one, you
+  mybf(must) use the mytt(${...}) braces around the name.  Assignments
+  are not special, they have the form mytt(.nspace.var=value) as usual.
+
+  Parameters using a namespace have the additional property that, like
+  file names beginning with a dot for globbing, they're hidden from
+  mytt(typeset) output unless explicitly asked for.
+
+  Namespaces appear in releases after but not including zsh 5.9.
+
+sect(What about named references?)
+label(210)
+
+  Named references are a bit like aliases, but for parameters.  A named
+  reference would typically be usable in the same cases as ${(P)name}
+  (see link(3.22)(322)).  The value of a named reference is the name
+  of another parameter, and when you expand or assign to the named
+  reference, that other parameter is expanded or assigned instead.
+  Thus a trivial example is
+  verb(
+    % target=RING
+    % typeset -n ref=target
+    % print $ref
+    RING
+    % ref=BULLSEYE
+    % print $target
+    BULLSEYE
+  )
+
+  One exception to this behavior is when a named reference is used as
+  the loop variable in a mytt(for) loop.  In that case the reference is
+  unset and reset on each iteration of the loop.
+  verb(
+    % target=RING bullseye=SPOT other=MISS
+    % typeset -n ref=other
+    % for ref in target bullseye; do
+    > print $ref
+    > ref=HIT:$ref
+    > done
+    RING
+    SPOT
+    % print $other
+    MISS
+    % print $ref
+    HIT:SPOT
+  )
+
+  Dynamic scoping applies to named references, so for example a named
+  reference declared in global scope may be used in function scopes.
+  In ksh, local parameters have static scope, so named references in
+  zsh may have side-effects that do not occur in ksh.  To limit those
+  effects, mytt(zmodload zsh/param/private) and declare all named
+  references mytt(private).
+
+  Named references may be used in zsh versions later than 5.9.
+
+sect(What is zsh's support for non-forking command substitution?)
+label(211)
+
+  This is for cases where you'd write mytt($(command)) but you don't want
+  the overhead or other issues associated with forking a subshell.
+  There are 3 variations:
+  itemization(
+  eit() Borrowed from mksh
+   verb(
+     ${| code }
+   )
+   Runs code in the current shell context and then substitutes mytt(${REPLY}).
+   The result is not split into words unless the tt(SH_WORD_SPLIT) option
+   is set, for example by mytt(${=${| code }}).  mytt($REPLY) is a local
+   parameter within the substitution so its value in the surrounding scope
+   is not changed.
+
+  eit() An extension to #1
+   verb(
+     ${{var} code }
+   )
+   Runs code in the current shell and then substitutes mytt(${var}).  If
+   mytt(${var}) names an array, the result is an array of those elements,
+   but no further splitting is done without tt(SH_WORD_SPLIT). mytt(${var})
+   is myem(not) local to the substitution.
+
+  eit() The traditional ksh form, except that the closing mytt(;)
+   may usually be omitted:
+   verb(
+     ${ code }
+   )
+   Runs code in the current shell and substitutes its standard output.
+   (this is done with a temporary file ala mytt($(<=( code ))) but
+   without the fork implied by mytt(=(...))).  The result is not split
+   into words without tt(SH_WORD_SPLIT).
+  )
+
+  In all three forms mytt(code) behaves myem(similarly) to an anonymous
+  function invoked like:
+  verb(
+    () { code } "$@"
+  )
+  Thus, all parameters declared inside the substitution are local by
+  default, and positional parameters mytt($1), mytt($2), etc. are those
+  of the calling context.
+
+  The most significant limitation is that braces (mytt({) and mytt(}))
+  within the substitutions must either be in balanced pairs, or must be
+  quoted, that is, included in a quoted string or prefixed by backslash.
+  These substitutions first become usable after zsh 5.9.
+
+sect(Comparisons of forking and non-forking command substitution)
+
+  mytt(${ command }) and variants may change the caller's options by using
+  mytt(setopt) and may modify the caller's local parameters, including the
+  positional parameters mytt($1), mytt($2), etc., via both assignments and
+  mytt(set -- pos1 pos2 etc).  Nothing that happens within mytt($(command))
+  affects the caller.
+
+  When not enclosed in double quotes, the expansion of mytt($(command)) is
+  split on tt(IFS) into an array of words.  In contrast, and unlike both
+  bash and ksh, unquoted non-forking substitutions behave like parameter
+  expansions with respect to the tt(SH_WORD_SPLIT) option.
+
+  Both mytt(${|...}) and mytt(${{var} ...}) retain any trailing newlines,
+  except as handled by the tt(SH_WORD_SPLIT) option, consistent with
+  mytt(${|...}) from mksh. mytt(${ command }) removes a single final
+  newline, but mytt("${ command }") retains it.  This differs from
+  bash and ksh, so in emulation modes, newlines are stripped even from
+  quoted command output.  In all cases, mytt($(command)) removes all
+  trailing newlines from the output of mytt(command).
+
+  When mytt(command) is myem(not) a builtin, mytt(${ command }) does
+  fork, and typically forks the same number of times as
+  mytt($(command)), because in the latter case zsh usually optimizes
+  the final fork into an exec.
+
+  Redirecting input from files has subtle differences:
+  itemization(
+    it() mytt($(<file)) is optimized to read from mytt(file) without forking,
+    	 but per above it removes trailing newlines.
+    it() mytt(${<file}) is a substitution error.
+    it() mytt(${ <file }) copies mytt(file) using the mytt(NULLCMD) programs,
+    	 then reads and substitutes the contents of the copy.  Also, this
+	 fails if the tt(CSH_NULLCMD) or tt(SH_NULLCMD) options are in effect,
+	 so it does not work in emulation modes.
+    it() mytt(${|<file}) copies mytt(file) to the standard output using
+    	 tt(NULLCMD) but substitutes nothing because there is no assignment
+	 to tt(REPLY).  It also fails in emulation modes.
+    )
+  mytt(${|IFS= read -rd '' <file}) is therefore the best solution for files
+  that do not contain nul bytes, because it copies the file directly into
+  the local mytt(REPLY) and then substitutes that.  For very large files,
+  refer to mytt(Functions/Misc/zslurp).
+
 chapter(How to get various things to work)
 
 sect(Why does mytt($var) where mytt(var="foo bar") not do what I expect?)
@@ -1641,6 +1810,7 @@ label(321)
   manual.
 
 sect(How do I get a variable's value to be evaluated as another variable?)
+label(322)
 
   The problem is that you have a variable tt($E) containing the string
   mytt(EDITOR), and a variable tt($EDITOR) containing the string mytt(emacs),
@@ -1833,7 +2003,7 @@ sect(Why is my output duplicated with `tt(foo 2>&1 >foo.out | bar)'?)
   to both files when the redirector appears twice.  What's going on in the
   first example is exactly the same, however the second redirector is
   disguised as a pipe.  So if you want to turn this effect off, you need
-  to unset the option mytt(MULTIOS), or alternatively write the following:
+  to unset the option tt(MULTIOS), or alternatively write the following:
   verb(
     % { print output; print error >&2 } 2>&1 >&- >foo.out | sed 's/error/erratic/'
     erratic
@@ -2509,14 +2679,11 @@ sect(What's on the wish-list?)
      characters.  Initial support for this appeared in version 4.3;
      it is reasonably complete in the line editor but patchy elsewhere
      (note this may require the configuration option --enable-multibyte).
-  it() The parameter code could do with tidying up, maybe with more of the
-     features made available in ksh93.
+  it() The parameter code could do with tidying up.
   it() Configuration files to enable zsh startup files to be created
      with the Dotfile Generator.
   it() Further improvements in integrating the line editor with shell
      functions.
-  it() POSIX compatibility could be improved.
-  it() Option for glob qualifiers to follow perl syntax (a traditional item).
   )
 
 sect(Did zsh have problems in the year 2000?)
@@ -2618,11 +2785,12 @@ https://github.com/chrisbra/vim_faq/blob/de424bd8e08bcf0e6b1e0563ee49514dfed926a
 
 nsect(Acknowledgments:)
 
-Thanks to zsh-list, in particular Bart Schaefer, for suggestions
+Thanks to zsh-workers, in particular Bart Schaefer, for suggestions
 regarding this document.  Zsh has been in the hands of archivists Jim
 Mattson, Bas de Bakker, Richard Coleman, Zoltan Hidvegi and Andrew
-Main, and the mailing list has been run by Peter Gray, Rick Ohnemus,
-Richard Coleman, Karsten Thygesen and Geoff Wing, all of whom deserve
+Main, and the mailing lists have been managed or hosted by Peter Gray,
+Rick Ohnemus, Richard Coleman, Karsten Thygesen, Geoff Wing, Phil
+Pennock, Daniel Shahaf, and Oliver Kiddle, all of whom deserve
 thanks.  The world is eternally in the debt of Paul Falstad for inventing
 zsh in the first place (though the wizzo extended completion is by Sven
 Wischnowsky).
@@ -2630,15 +2798,15 @@ Wischnowsky).
 nsect(Copyright Information:)
 
 This document is copyright (C) P.W. Stephenson, 1995, 1996, 1997,
-1998, 1999, 2000, 2012, 2020. This text originates in the U.K. and the author
-asserts his moral rights under the Copyrights, Designs and Patents Act,
-1988.
+1998, 1999, 2000, 2012, 2020, 2023. This text originates in the U.K.
+and the author asserts his moral rights under the Copyrights, Designs
+and Patents Act, 1988.
 
 Permission is hereby granted, without written agreement and without
 license or royalty fees, to use, copy, modify, and distribute this
 documentation for any purpose, provided that the above copyright
 notice appears in all copies of this documentation.  Remember,
-however, that this document changes monthly and it may be more useful
+however, this document changes occasionally and it may be more useful
 to provide a pointer to it rather than the entire text.  A suitable
 pointer is "information on the Z-shell can be obtained on the World
 Wide Web at URL https://zsh.sourceforge.io/".
diff --git a/Etc/zsh-development-guide b/Etc/zsh-development-guide
index e8c292cfd..bdabe17d8 100644
--- a/Etc/zsh-development-guide
+++ b/Etc/zsh-development-guide
@@ -223,9 +223,6 @@ C coding style
 * Do not use space between the function name and the opening parenthesis.
   Use space after if/for/while.  Use space after type casts.
 
-* Do not use (unsigned char) casts since some compilers do not handle
-  them properly.  Use the provided STOUC(X) macro instead.
-
 * If you use emacs 19.30 or newer you can put the following line to your
   ~/.emacs file to make these formatting rules the default:
 
@@ -243,7 +240,7 @@ C coding style
   There must be an empty line, a line with "/**/", a line with the
   type of the function, and finally the name of the function with typed
   arguments.  These lines must not be indented.  The script generating
-  function prototypes and the ansi2knr program depend on this format.
+  function prototypes depends on this format.
 
 * Variable declarations must similarly be preceded by a
   line containing only "/**/", for the prototype generation script.
@@ -374,8 +371,8 @@ particular they can be called before or after `boot_'.
 The function named `boot_' should register function wrappers, hooks and
 anything that will be visible to the user that is not handled by features_
 and enables_ (so features should not be turned on here).  It will be called
-after the `setup_'-function, and also after the initial set of features
-have been set by calls to `features_' and `enables_'.
+after the initial set of features have been set by calls to `features_'
+and `enables_'.
 
 The function named `cleanup_', is called when the user tries to unload
 a module and should de-register all features and hooks.  A call
@@ -615,7 +612,7 @@ For defining parameters, a module can call `createparam()' directly or
 use a table to describe them, e.g.:
 
   static struct paramdef patab[] = {
-    PARAMDEF("foo", PM_INTEGER, NULL, get_foo, set_foo, unset_foo),
+    PARAMDEF("foo", PM_INTEGER, NULL, foo_gsu),
     INTPARAMDEF("exint", &intparam),
     STRPARAMDEF("exstr", &strparam),
     ARRPARAMDEF("exarr", &arrparam),
@@ -627,17 +624,23 @@ There are four macros used:
     - the name of the parameter
     - the parameter flags to set for it (from the PM_* flags defined
       in zsh.h)
-    - optionally a pointer to a variable holding the value of the
-      parameter
-    - three functions that will be used to get the value of the
-      parameter, store a value in the parameter, and unset the
-      parameter
+    - optionally a pointer to the value of the parameter
+    - a GSU pointer to the three functions that will be used to get
+      the value of the parameter, store a value in the parameter,
+      and unset the parameter
   - the other macros provide simple ways to define the most common
     types of parameters; they get the name of the parameter and a
     pointer to a variable holding the value as arguments; they are
-    used to define integer-, scalar-, and array-parameters, so the
-    variables whose addresses are given should be of type `long',
-    `char *', and `char **', respectively
+    used to define integer-, scalar-, and array-parameters, so for
+    those macros the pointer to the parameter value should be the
+    address of a variable of type `long', `char *',or `char **',
+    respectively, pointing in turn to the desired value.
+  - Parameters used in a module that don't have special behaviour
+    shouldn't be declared in this way, instead they should just be
+    created in `boot_'  with the standard parameter functions.
+
+GSU (get, set, unset) structures are defined in Src/zsh.h for each of
+the parameter types scalar, integer, float, array, and hash.
 
 For a description of how to write functions for getting or setting the 
 value of parameters, or how to write a function to unset a parameter,
diff --git a/Functions/MIME/zsh-mime-handler b/Functions/MIME/zsh-mime-handler
index 288a0796d..2feacf063 100644
--- a/Functions/MIME/zsh-mime-handler
+++ b/Functions/MIME/zsh-mime-handler
@@ -193,7 +193,7 @@ if ! zsh-mime-contexts -s $suffix flags flags; then
   # Same again for flags.
   s=$suffix
   while true; do
-    flags="${zsh_mime_flags[$suffix]}"
+    flags="${zsh_mime_flags[$s]}"
     if [[ -n $flags ]]; then
       break
     fi
diff --git a/Functions/Misc/add-zle-hook-widget b/Functions/Misc/add-zle-hook-widget
index 4d8049083..4293a07dd 100644
--- a/Functions/Misc/add-zle-hook-widget
+++ b/Functions/Misc/add-zle-hook-widget
@@ -39,7 +39,7 @@ zstyle zle-hook types ${hooktypes#zle-}
 
 # Relying on multifuncdef option here
 function azhw:${^hooktypes} {
-    local -a hook_widgets
+    local -a hook_widgets match mbegin mend
     local hook
     # Values of these styles look like number:name
     # and we run them in number order
@@ -58,7 +58,7 @@ function azhw:${^hooktypes} {
 # Redefine ourself with the setup left out
 
 function add-zle-hook-widget {
-    local -a hooktypes
+    local -a hooktypes match mbegin mend
     zstyle -a zle-hook types hooktypes
 
     # This part copied from add-zsh-hook
diff --git a/Functions/Misc/colors b/Functions/Misc/colors
index 5c9924adb..8a0cec383 100644
--- a/Functions/Misc/colors
+++ b/Functions/Misc/colors
@@ -44,7 +44,7 @@ color=(
   35 magenta                45 bg-magenta
   36 cyan                   46 bg-cyan
   37 white                  47 bg-white
-# 38 iso-8316-6           # 48 bg-iso-8316-6
+# 38 iso-8613-6           # 48 bg-iso-8613-6
   39 default                49 bg-default
 
 # Other codes:
diff --git a/Functions/Misc/is-at-least b/Functions/Misc/is-at-least
index d4ff3552a..5985684be 100644
--- a/Functions/Misc/is-at-least
+++ b/Functions/Misc/is-at-least
@@ -24,8 +24,14 @@ emulate -L zsh
 
 local IFS=".-" min_cnt=0 ver_cnt=0 part min_ver version order
 
+: ${2=$ZSH_VERSION}
+
+# sort out the easy corner cases first
+[[ $1 = $2 ]] && return 0 # same version
+[[ -n $2 ]] || return 1   # no version
+
 min_ver=(${=1})
-version=(${=2:-$ZSH_VERSION} 0)
+version=(${=2} 0)
 
 while (( $min_cnt <= ${#min_ver} )); do
   while [[ "$part" != <-> ]]; do
diff --git a/Functions/Misc/mkshadow b/Functions/Misc/mkshadow
new file mode 100644
index 000000000..2ae3a0f2c
--- /dev/null
+++ b/Functions/Misc/mkshadow
@@ -0,0 +1,11 @@
+#autoload
+# Front-end to the completion helper _shadow for use outside completion.
+# This just forces proper autoload of _shadow/_unshadow and calls them.
+
+autoload _shadow
+mkshadow() { unset REPLY; _shadow "$@" }
+rmshadow() { unset REPLY; _unshadow }
+
+# Bootstrap because of autoload special case
+unset REPLY
+_shadow "$@"
diff --git a/Functions/Misc/run-help b/Functions/Misc/run-help
index d52c1b032..462044b72 100644
--- a/Functions/Misc/run-help
+++ b/Functions/Misc/run-help
@@ -58,11 +58,11 @@ do
     case $what in
     (*( is an alias for (noglob|nocorrect))*)
 	[[ ${what[(w)7]:t} != ${what[(w)1]} ]] &&
-	  run_help_orig_cmd=${what[(w)1]} run-help ${what[(w)7]:t}
+	  run_help_orig_cmd=${what[(w)1]} run-help ${what[(w)7]:t} ${(z)${what[(w)8,-1]}}
 	;;
     (*( is an alias)*)
 	[[ ${what[(w)6]:t} != ${what[(w)1]} ]] &&
-	  run_help_orig_cmd=${what[(w)1]} run-help ${what[(w)6]:t}
+	  run_help_orig_cmd=${what[(w)1]} run-help ${what[(w)6]:t} ${(z)${what[(w)7,-1]}}
 	;;
     (*( is a * function))
 	case ${what[(w)1]} in
@@ -98,13 +98,13 @@ do
 	    if whence "run-help-$1:t" >/dev/null
 	    then
 		local cmd_args
-		builtin getln cmd_args
+		builtin getln cmd_args &&
 		builtin print -z "$cmd_args"
-		cmd_args=( ${(z)cmd_args} )
+		cmd_args=( ${(z)${cmd_args:-"$*"}} )
 
                 # Discard the command itself & everything before it.
-                shift $cmd_args[(i)${run_help_orig_cmd:-$1}] cmd_args ||
-                    return
+                shift $cmd_args[(i)(${run_help_orig_cmd}|$1)] cmd_args 2>/dev/null ||
+                    continue
 
                 # Discard options, parameter assignments & paths.
                 cmd_args=( ${cmd_args[@]:#([-+]*|*=*|*/*|\~*)} )
diff --git a/Functions/Misc/run-help-docker b/Functions/Misc/run-help-docker
new file mode 100644
index 000000000..09a8a221a
--- /dev/null
+++ b/Functions/Misc/run-help-docker
@@ -0,0 +1,9 @@
+if [[ $# == 0 ]]
+then
+    man docker
+elif [[ $# > 1 && $1 == (builder|checkpoint|config|container|context|image|manifest|network|node|plugin|secret|service|stack|swarm|system|trust|volume) ]]
+then
+    man docker-$1-$2
+else
+    man docker-$1
+fi
diff --git a/Functions/Misc/run-help-ip b/Functions/Misc/run-help-ip
index b811ce352..f635cce71 100644
--- a/Functions/Misc/run-help-ip
+++ b/Functions/Misc/run-help-ip
@@ -18,7 +18,7 @@ case $1 in
     (addrl*) man ip-addrlabel ;;
     (a*) man ip-address ;;
     (l2*) man ip-l2tp ;;
-    (li*) man ip-link ;;
+    (l*) man ip-link ;;
     (ma*) man ip-maddress ;;
     (mo*) man ip-monitor ;;
     (mr*) man ip-mroute ;;
diff --git a/Functions/Misc/run-help-openssl b/Functions/Misc/run-help-openssl
index c528418c8..e4e45070e 100644
--- a/Functions/Misc/run-help-openssl
+++ b/Functions/Misc/run-help-openssl
@@ -1,7 +1 @@
-
-if [ $# -eq 0 ]; then
-    man openssl
-else
-    man $1
-fi
-
+man openssl${1:+-$1} || man ${1:-openssl}
diff --git a/Functions/Misc/run-help-perf b/Functions/Misc/run-help-perf
new file mode 100644
index 000000000..2e0695af2
--- /dev/null
+++ b/Functions/Misc/run-help-perf
@@ -0,0 +1 @@
+man perf${1:+-$1}
diff --git a/Functions/Misc/run-help-podman b/Functions/Misc/run-help-podman
new file mode 100644
index 000000000..64d9cd83f
--- /dev/null
+++ b/Functions/Misc/run-help-podman
@@ -0,0 +1,9 @@
+if [[ $# == 0 ]]
+then
+    man podman
+elif [[ $# > 1 && $1 == (container|generate|healthcheck|image|kube|machine|manifest|network|pod|secret|system|volume) ]]
+then
+    man podman-$1-$2
+else
+    man podman-$1
+fi
diff --git a/Functions/Misc/run-help-ssh b/Functions/Misc/run-help-ssh
new file mode 100644
index 000000000..9c48596ff
--- /dev/null
+++ b/Functions/Misc/run-help-ssh
@@ -0,0 +1,6 @@
+if [[ $# < 2 ]]
+then
+    man ssh
+else
+    run-help $2
+fi
diff --git a/Functions/Misc/run-help-svk b/Functions/Misc/run-help-svk
deleted file mode 100644
index 782538246..000000000
--- a/Functions/Misc/run-help-svk
+++ /dev/null
@@ -1 +0,0 @@
-svk help $1 | ${=PAGER:-more}
diff --git a/Functions/Misc/run-help-svnadmin b/Functions/Misc/run-help-svnadmin
new file mode 100644
index 000000000..dbddd6396
--- /dev/null
+++ b/Functions/Misc/run-help-svnadmin
@@ -0,0 +1 @@
+svnadmin help $1 | ${=PAGER:-more}
diff --git a/Functions/Misc/zcalc b/Functions/Misc/zcalc
index 480373345..6cd2822c9 100644
--- a/Functions/Misc/zcalc
+++ b/Functions/Misc/zcalc
@@ -124,8 +124,10 @@ integer _rpn_mode _matched _show_stack _i _n
 integer _max_stack _push
 local -a _expressions stack
 
+
 # We use our own history file with an automatic pop on exit.
-history -ap "${ZDOTDIR:-$HOME}/.zcalc_history"
+history -ap "${ZCALC_HISTFILE:-${ZDOTDIR:-$HOME}/.zcalc_history}"
+
 
 _forms=( '%2$g' '%.*g' '%.*f' '%.*E' '')
 
diff --git a/Functions/Misc/zmv b/Functions/Misc/zmv
index 269fe5ba5..5c03e9ea1 100644
--- a/Functions/Misc/zmv
+++ b/Functions/Misc/zmv
@@ -236,12 +236,18 @@ if [[ $pat = (#b)(*)\((\*\*##/)\)(*) ]]; then
 else
   fpat=$pat
 fi
-files=(${~fpat})
 
 [[ -n $hasglobqual ]] && pat=$opat
 
 errs=()
 
+() {
+  # (#qN) breaks bareglobqual -Q option, so:
+  setopt localoptions nullglob
+  files=(${~fpat})
+}
+(( ${#files} )) || errs=( "no files matched \`$fpat'" )
+
 for f in $files; do
   if [[ $pat = (#b)(*)\(\*\*##/\)(*) ]]; then
     # This looks like a recursive glob.  This isn't good enough,
diff --git a/Functions/Misc/zslurp b/Functions/Misc/zslurp
new file mode 100644
index 000000000..84df0c948
--- /dev/null
+++ b/Functions/Misc/zslurp
@@ -0,0 +1,31 @@
+#!/bin/zsh -f
+
+# Read stdin verbatim and as efficiently as possible into $REPLY,
+# stopping without any change to $REPLY in the event of any error.
+# Benchmarked by Roman Perepelitsa in zsh-users/29472
+
+# Although this function faithfully records the input stream, later
+# references to $REPLY with the multibyte option back in effect will
+# (re-)interpret the content as multibyte characters.  This may not be
+# what is desired.
+
+emulate -L zsh -o no_multibyte
+
+### Alternate formulation, faster on bigger files
+# # /dev/fd/0 is treated specially by -f so also check /dev/fd
+# if [[ -d /dev/fd && -f /dev/fd/0 ]] && zmodload zsh/mapfile
+# then
+#     local +h -Ar mapfile
+#     typeset -g REPLY="${mapfile[/dev/fd/0]}" && return
+# fi
+# # else fall through to read from pipe/socket
+
+zmodload zsh/system || return
+local -a content
+local -i i=0
+while true; do
+    sysread 'content[++i]' && continue
+    (( $? == 5 )) || return
+    break
+done
+typeset -g REPLY=${(j::)content}
diff --git a/Functions/Prompts/prompt_sprint2_setup b/Functions/Prompts/prompt_sprint2_setup
new file mode 100644
index 000000000..0eaea4473
--- /dev/null
+++ b/Functions/Prompts/prompt_sprint2_setup
@@ -0,0 +1,128 @@
+# Created by Sebastian Gniazdowski 
+
+prompt_sprint2_help () {
+    cat <<EOF
+This prompt is color themable. You can invoke it in following way:
+
+prompt sprint2 <time/line color> <braces clr.> <text clr.> <at/colon clr.> <prompt clr.>
+
+You can provide only N first arguments, N=1..5.
+
+The default colors are: 39 green blue green yellow
+EOF
+}
+
+prompt_sprint2_setup () {
+    local col_time_line=${1:-'39'}
+    local col_parens=${2:-'green'}
+    local col_text=${3:-'blue'}
+    local col_at_colon=${4:-'green'}
+    local col_prompt=${5:-'yellow'}
+
+    autoload -Uz vcs_info
+
+    typeset -gA _psvar
+
+    local cl_time_line="%B%F{$col_time_line}"
+    local cl_text="%b%F{$col_text}"
+    local cl_parens="%B%F{$col_parens}"
+    local cl_at_colon="%b%F{$col_at_colon}"
+    local cl_prompt="%B%F{$col_prompt}"
+    local cl_rst="%b%f"
+
+    local _lpar="${cl_parens}["
+    local _rpar="${cl_parens}]"
+
+    local _time="$cl_time_line%D{%H:%M}"
+    _psvar[user]='%n'
+    local _user="$cl_text"'${_psvar[user]}'
+    _psvar[at]="@"
+    _psvar[host]='%m'
+    local _at="$cl_at_colon"'${_psvar[at]}'"$cl_text"'${_psvar[host]}'
+    _psvar[colon]=':'
+    local _path="$cl_at_colon"'${_psvar[colon]}'"$cl_text%28<*<%/%<<"
+    local _line="$cl_time_line%i"
+    local _prompt="$cl_prompt# "
+
+    # You can instantly shorten the prompt by setting PSSHORT=1
+    if [[ "$COLUMNS" -le 94 || "$PSSHORT" = "1" ]]; then
+        _psvar=()
+    else
+        _psvar[user]='%n'
+        _psvar[at]="@"
+        _psvar[host]='%m'
+        _psvar[colon]=':'
+    fi
+
+    PS1="$_time$_lpar$_user$_at$_path$_rpar$_line$_prompt$cl_rst"
+
+    PS2="$cl_parens> $cl_rst"
+
+    RPS1='${vcs_info_msg_0_}'
+    prompt_opts=(cr subst percent)
+
+    zstyle ':vcs_info:*' enable git svn darcs bzr hg
+    zstyle ':vcs_info:*' stagedstr "%F{green}●$cl_rst"
+    zstyle ':vcs_info:*' unstagedstr "%F{yellow}●$cl_rst"
+    zstyle ':vcs_info:*' check-for-changes true
+    zstyle ':vcs_info:*' formats '(%s)-[%b%u%c]-'
+
+    add-zsh-hook precmd prompt_sprint2_precmd
+}
+
+prompt_sprint2_precmd () {
+    setopt localoptions noxtrace noksharrays 
+
+    # You can instantly shorten the prompt by setting PSSHORT=1
+    if [[ "$COLUMNS" -le 94 || "$PSSHORT" = "1" ]]; then
+        _psvar=()
+    else
+        _psvar[user]='%n'
+        _psvar[at]="@"
+        _psvar[host]='%m'
+        _psvar[colon]=':'
+    fi
+
+    local -a changed_files
+    changed_files=( )
+    git diff --quiet 2>/dev/null || changed_files=( ${(f)"$( git diff --name-only 2>/dev/null )"} )
+    changed_files=( $^changed_files(N) )
+    if [[ "${#changed_files}" -gt 0 ]]; then
+        local basedir
+        basedir="$(git rev-parse --show-toplevel)/"
+        changed_files=( ${(f)"$( find "${basedir}${^changed_files[@]}" -mtime +2 )"} )
+    fi
+
+    if [[ "${#changed_files}" -eq 0 ]]; then
+        zstyle ':vcs_info:*' formats ' (%s)-[%b%u%c]'
+    else
+        zstyle ':vcs_info:*' formats ' (%s)-[%b%u%B%F{yellow}-OLD-%c%%b%f]'
+    fi
+
+    vcs_info
+}
+
+prompt_sprint2_preview () {
+    local -a colors_time_line colors_text
+    colors_time_line=(red yellow green blue magenta cyan)
+    colors_text=(red yellow green blue magenta cyan)
+
+    local ctime_line ctext i j
+
+    if (( ! $#* )); then
+        for (( i = 1; i <= ${#colors_time_line}; i++ )); do
+            ctime_line="${colors_time_line[$i]}"
+            for (( j = 1; j <= ${#colors_text}; j++ )); do
+                ctext="${colors_text[$j]}"
+                prompt_preview_theme sprint2 "$ctime_line" "red" "$ctext"
+                (( i != ${#colors_time_line} || j != ${#colors_text} )) && print
+            done
+        done
+    else
+        prompt_preview_theme sprint2 "$@"
+    fi
+}
+
+prompt_sprint2_setup "$@"
+
+# vim:ft=zsh
diff --git a/Functions/VCS_Info/Backends/VCS_INFO_get_data_git b/Functions/VCS_Info/Backends/VCS_INFO_get_data_git
index e45eebc8e..9a608adab 100644
--- a/Functions/VCS_Info/Backends/VCS_INFO_get_data_git
+++ b/Functions/VCS_Info/Backends/VCS_INFO_get_data_git
@@ -184,15 +184,8 @@ fi
 VCS_INFO_adjust
 VCS_INFO_git_getaction ${gitdir}
 
-local patchdir=${gitdir}/patches/${gitbranch}
-if [[ -d $patchdir ]] && [[ -f $patchdir/applied ]] \
-   && [[ -f $patchdir/unapplied ]]
-then
-    # stgit
-    git_patches_applied=(${(f)"$(< "${patchdir}/applied")"})
-    git_patches_unapplied=(${(f)"$(< "${patchdir}/unapplied")"})
-    VCS_INFO_git_handle_patches
-elif [[ -d "${gitdir}/rebase-merge" ]]; then
+local patchdir
+if [[ -d "${gitdir}/rebase-merge" ]]; then
     # 'git rebase -i'
     patchdir="${gitdir}/rebase-merge"
     local p
@@ -251,7 +244,9 @@ elif [[ -d "${gitdir}/rebase-merge" ]]; then
             (( $+REPLY )) && git_patches_applied+=( "$REPLY" )
         done
     fi
-    if [[ -f "${patchdir}/git-rebase-todo" ]] ; then
+    if zstyle -t ":vcs_info:${vcs}:${usercontext}:${rrn}" get-unapplied &&
+       [[ -f "${patchdir}/git-rebase-todo" ]]
+    then
         for p in ${(f)"$(< "${patchdir}/git-rebase-todo")"}; do
             VCS_INFO_git_map_rebase_line_to_hash_and_subject "$p"
             (( $+REPLY )) && git_patches_unapplied+=( "$REPLY" )
@@ -381,7 +376,9 @@ elif [[ -f "${gitdir}/CHERRY_PICK_HEAD" ]]; then
     # TODO: maybe read up to the first blank line
     IFS='' read -r subject < "${gitdir}/MERGE_MSG"
     git_patches_applied=( "$(<${gitdir}/CHERRY_PICK_HEAD) ${subject}" )
-    if [[ -f "${gitdir}/sequencer/todo" ]]; then
+    if zstyle -t ":vcs_info:${vcs}:${usercontext}:${rrn}" get-unapplied &&
+       [[ -f "${gitdir}/sequencer/todo" ]]
+    then
         # Get the next patches, and remove the one that's in CHERRY_PICK_HEAD.
         git_patches_unapplied=( ${${(M)${(f)"$(<"${gitdir}/sequencer/todo")"}:#pick *}#pick } )
         git_patches_unapplied[1]=()
@@ -389,6 +386,31 @@ elif [[ -f "${gitdir}/CHERRY_PICK_HEAD" ]]; then
         git_patches_unapplied=()
     fi
     VCS_INFO_git_handle_patches
+elif command -v stg >/dev/null &&
+        ${vcs_comm[cmd]} show-ref --quiet refs/stacks/${gitbranch} refs/heads/${gitbranch}.stgit 2>/dev/null &&
+        git_patches_applied=(${${(f)"$(stg series --noprefix --applied --description 2>/dev/null)"}/ #[#]})
+then
+    # Testing for StGit patches is done after testing for all git-proper
+    # patches/states. If a StGit user's repo is in one of those states, they
+    # will want to see that instead of the StGit patch info.
+
+    # Performance note: testing for the stg executable is done first because it
+    # is extremely cheap and there is nothing else to do if it isn't present.
+    # Using git to test whether a StGit stack is initialized is cheaper than
+    # running stg itself; especially for versions of StGit <= 2.0. Thus getting
+    # StGit patch info should only have a material runtime cost if StGit is
+    # installed and in-use for the current branch.
+
+    # In StGit >=1.2, the existence of refs/stacks/<branch> indicates StGit is
+    # initialized. In StGit >=0.15, it is refs/heads/<branch>.stgit.
+
+    # N.B. the "--noprefix" option is available in StGit 2.x as an alias for
+    # --no-prefix.  The former is compatible with StGit versions going back to
+    # 2008.
+    if zstyle -t ":vcs_info:${vcs}:${usercontext}:${rrn}" get-unapplied; then
+        git_patches_unapplied=(${${(f)"$(stg series --noprefix --unapplied --description 2>/dev/null)"}/ #[#]})
+    fi
+    VCS_INFO_git_handle_patches
 else
     gitmisc=''
 fi
diff --git a/Functions/Zle/edit-command-line b/Functions/Zle/edit-command-line
index 5f7ea321f..d4b405eaf 100644
--- a/Functions/Zle/edit-command-line
+++ b/Functions/Zle/edit-command-line
@@ -11,15 +11,30 @@ local left right prebuffer buffer=$BUFFER lbuffer=$LBUFFER
 local TMPSUFFIX=.zsh
 # set up parameters depending on which context we are called from,
 # see below comment for more details
-if (( REGION_ACTIVE )); then
+if (( REGION_ACTIVE == 1 )); then
   if (( CURSOR < MARK )); then
     left=$CURSOR right=$MARK
-    lbuffer=
   else
     left=$MARK right=$CURSOR
-    lbuffer[right-left,-1]=
   fi
-  (( left++ ))
+  lbuffer=$lbuffer[++left,-1]
+  buffer=$BUFFER[left,++right]
+elif (( REGION_ACTIVE == 2 )); then
+  local nl=$'\n'
+  if (( CURSOR < MARK )); then
+    left=${${BUFFER[1,CURSOR]}[(I)$nl]}
+    right=${${BUFFER[MARK+1,-1]}[(i)$nl]}
+    (( right += MARK ))
+  else
+    left=${${BUFFER[1,MARK]}[(I)$nl]}
+    right=${${BUFFER[CURSOR+1,-1]}[(i)$nl]}
+    (( right += CURSOR ))
+  fi
+  lbuffer=$lbuffer[++left,-1]
+  if [[ $BUFFER[right] = $nl ]]; then
+    # Keep the newline because "$(<$1)" below trims it
+    (( --right ))
+  fi
   buffer=$BUFFER[left,right]
 elif (( ! ZLE_RECURSIVE )); then
   prebuffer=$PREBUFFER
diff --git a/Functions/Zle/incarg b/Functions/Zle/incarg
index cff0cfe4c..0cfaf9ff5 100644
--- a/Functions/Zle/incarg
+++ b/Functions/Zle/incarg
@@ -1,43 +1,303 @@
-# Shell function to increment an integer either under the cursor or just
-# to the left of it.  Use
+emulate -L zsh
+
+# A ZLE widget to increment an integer.
+#
+# In addition to decimals, it can handle hexadecimals prefixed with "0x",
+# binaries with "0b", and octals with "0o".
+#
+# By default, the target integer will be incremented by one. With a numeric
+# argument, the integer is incremented by the amount of the argument. The shell
+# parameter "incarg" may be set to change the default increment to something
+# other than one.
+#
+# The behavior of this widget changes depending on how it is named.
+#
+# - incarg / decarg
+#
+#   incarg will increment an integer either under the cursor or just to the left
+#   of it. decarg, on the other hand, will decrement it.
+#
+#   For example,
+#
+#       echo 41
+#            ^^^ cursor anywhere here
+#
+#   with incarg gives
+#
+#       echo 42
+#              ^ cursor will move here
+#
+# - sync-incarg / sync-decarg
+#
+#   The sync- variant is used for creating a sequence of numbers on split
+#   terminals with synchronized key input. The first pane won't be incremented
+#   at all, but each pane after that will have the number incremented once more
+#   than the previous pane.
+#
+#   Currently supports tmux and iTerm2.
+#
+# - vim-incarg / vim-decarg
+#
+#   This behaves like Vim's CTRL-A / CTRL-X. It moves the cursor to the nearest
+#   number after the cursor and increments or decrements it.
+#
+# - vim-backward-incarg / vim-backward-decarg
+#
+#   This behaves like vim-incarg & vim-decarg, but it searches backwards for a
+#   number.
+#
+# - vim-sync-incarg / vim-sync-decarg
+#
+#   This combines the behavior of the vim- and sync- variants. It's inspired by
+#   Vim's g_CTRL-A / g_CTRL-X.
+#
+# - vim-backward-sync-incarg / vim-backward-sync-decarg
+#
+#   This combines the behavior of the vim-backward- and sync- variants.
+#
+# Example Usage:
+#
 #   autoload -Uz incarg
-#   zle -N incarg
-#   bindkey "..." incarg
-# to define it.  For example,
-#   echo 41
-#        ^^^ cursor anywhere here
-# with incarg gives
-#   echo 42
-# with the cursor in the same place.
-#
-# A numeric argument gives a number other than 1 to add (may be negative).
-# If you're going to do it a lot with one particular number, you can set
-# the parameter incarg to that number (a numeric argument still takes
-# precedence).
+#   for widget in vim-{,sync-}{inc,dec}arg; do
+#     zle -N "$widget" incarg
+#   done
+#   bindkey -a \
+#     '^A' vim-incarg \
+#     '^X' vim-decarg \
+#     'g^A' vim-sync-incarg \
+#     'g^X' vim-sync-decarg
 
-emulate -L zsh
-setopt extendedglob
+zle -f vichange
 
-local rrest lrest num
+setopt localoptions extended_glob
+local match mbegin mend MATCH MBEGIN MEND i
 
-rrest=${RBUFFER##[0-9]#}
-if [[ $RBUFFER = [0-9]* ]]; then
-  if [[ -z $rrest ]]; then
-    num=$RBUFFER
-  else
-    num=${RBUFFER[1,-$#rrest-1]}
+[[ -z "$BUFFER" ]] && return 1
+
+# find the number and determine the base
+integer pos=$(( CURSOR + 1 )) base=0
+
+# avoid miscalculating positions when cursor is at the end of the line
+while (( pos > 0 )) && [[ "$BUFFER[pos]" == '' ]]; do
+  (( pos-- ))
+done
+
+# check for a prefix (e.g., 0x) before the cursor
+for (( i = 0; i < 2; i++ )); do
+  case "$BUFFER[1,pos]" in
+    *0[xX][0-9a-fA-F]##) base=16 ;;
+    *0[oO][0-7]##) base=8 ;;
+    *0[bB][01]##) base=2 ;;
+    *[1-9]) base=10 ;;
+    *0) ;; # there may be a prefix right after the cursor
+    *)
+      # the non-Vim variant looks right before the cursor too, but not after it
+      if [[ "$WIDGET" != vi* ]]; then
+        if (( i == 0 )); then
+          (( pos-- ))
+          continue
+        else
+          return 1
+        fi
+      fi
+      ;;
+  esac
+
+  break
+done
+
+# check for a prefix on the cursor
+if (( base == 0 && pos < $#BUFFER )); then
+  case "$BUFFER[1,pos+1]" in
+    *0[xX][0-9a-fA-F]) base=16; (( pos++ )) ;;
+    *0[oO][0-7]) base=8; (( pos++ )) ;;
+    *0[bB][01]) base=2; (( pos++ )) ;;
+  esac
+fi
+
+if (( base == 0 )); then
+  if [[ "$WIDGET" == vi* ]]; then
+    if [[ "$WIDGET" == *backward-* ]]; then
+      # search backwards for a number
+      while true; do
+        case "$BUFFER[1,pos]" in
+          *0[xX][0-9a-fA-F]##) base=16 ;;
+          *0[oO][0-7]##) base=8 ;;
+          *0[bB][01]##) base=2 ;;
+          *[0-9]) base=10 ;;
+          *-)
+            case "$BUFFER[pos,-1]" in
+              -0[xX][0-9a-fA-F]*) ;;
+              -0[oO][0-7]*) ;;
+              -0[bB][01]*) ;;
+              -[0-9]*) base=10 ;;
+            esac
+            ;;
+        esac
+        (( base != 0 )) && break
+
+        (( pos-- ))
+        (( pos <= 0 )) && return 1
+      done
+    else
+      # jump to the nearest number after the cursor
+      while [[ "$BUFFER[pos]" == [^0-9] ]]; do
+        (( pos++ ))
+        (( pos > $#BUFFER )) && return 1
+      done
+    fi
+  fi
+
+  # check for a prefix right after the cursor and jump right after it, if any
+  if (( pos <= 1 )) || [[ "$BUFFER[pos-1]" == [^0-9] ]]; then
+    case "$BUFFER[pos,-1]" in
+      0[xX][0-9a-fA-F]*) base=16; (( pos += 2 )) ;;
+      0[oO][0-7]*) base=8; (( pos += 2 )) ;;
+      0[bB][01]*) base=2; (( pos += 2 )) ;;
+    esac
   fi
 fi
 
-lrest=${LBUFFER%%[0-9]#}
-if [[ $LBUFFER = *[0-9] ]]; then
-  if [[ -z $lrest ]]; then
-    num="$LBUFFER$num"
+if (( base == 0 )); then
+  base=10
+fi
+
+# find the start of the number
+integer first="$pos"
+case "$base" in
+  10)
+    while [[ "$BUFFER[first-1]" == [0-9] ]]; do
+      (( first-- ))
+    done
+    if [[ $BUFFER[first-1] = - ]]; then
+      (( first-- ))
+    fi
+    ;;
+  2)
+    while [[ "$BUFFER[first-1]" == [01] ]]; do
+      (( first-- ))
+    done
+    ;;
+  8)
+    while [[ "$BUFFER[first-1]" == [0-7] ]]; do
+      (( first-- ))
+    done
+    ;;
+  16)
+    while [[ "$BUFFER[first-1]" == [0-9a-fA-F] ]]; do
+      (( first-- ))
+    done
+    ;;
+esac
+
+# find the end of the number
+integer last="$pos"
+case "$base" in
+  10)
+    while [[ "$BUFFER[last+1]" == [0-9] ]]; do
+      (( last++ ))
+    done
+    ;;
+  2)
+    while [[ "$BUFFER[last+1]" == [01] ]]; do
+      (( last++ ))
+    done
+    ;;
+  8)
+    while [[ "$BUFFER[last+1]" == [0-7] ]]; do
+      (( last++ ))
+    done
+    ;;
+  16)
+    while [[ "$BUFFER[last+1]" == [0-9a-fA-F] ]]; do
+      (( last++ ))
+    done
+    ;;
+esac
+
+# calculate the number of digits
+integer ndigits=0
+case "$BUFFER[first,first+1]" in
+  0*|-0) ndigits=$(( last - first + 1 )) ;;
+esac
+
+# determine the amount to increment
+integer delta=${NUMERIC:-${incarg:-1}}
+if [[ "$WIDGET" = *decarg ]]; then
+  (( delta = -delta ))
+fi
+if [[ "$WIDGET" = *sync-* ]]; then
+  integer pane_index=0
+  if [[ -n "$TMUX_PANE" ]]; then
+    pane_index="$(tmux display-message -pt "$TMUX_PANE" '#{pane_index}')"
+  elif [[ "$ITERM_SESSION_ID" =~ '^w[0-9]+t[0-9]+p([0-9]+)' ]]; then
+    pane_index="$match[1]"
   else
-    num="${LBUFFER[$#lrest+1,-1]}$num"
+    zle -M "[$WIDGET] unsupported terminal"
+    return 1
   fi
+  (( delta *= pane_index ))
 fi
 
-[[ -n $num ]] && (( num += ${NUMERIC:-${incarg:-1}} ))
+local old="$BUFFER[first,last]"
+integer oldlen=$#BUFFER
+integer oldnum="$base#$old" 2> /dev/null
+
+# -00 should increment to 01 instead of 001
+if [[ "$BUFFER[first]" == '-' ]] && (( oldnum == 0 )); then
+  (( ndigits-- ))
+fi
+
+local fmt1 fmt2
+case "$base" in
+  10) fmt1=d; fmt2='#10' ;;
+  2) fmt1=s; fmt2='##2' ;;
+  8) fmt1=s; fmt2='##8' ;;
+  16) fmt1="$BUFFER[first-1]"; fmt2='#16' ;;
+esac
+
+local raw_result padded
+# $(( )) outputs an error message to stderr when integer truncation occurs
+printf -v raw_result "%0$ndigits$fmt1" $(( [$fmt2] "$base#$old" + delta )) 2> /dev/null
+padded="${raw_result// /0}"
+integer newnum="$base#$padded" 2> /dev/null
+
+# try to detect integer truncation
+if (( base != 10 && newnum < 0
+        || delta > 0 && newnum < oldnum
+        || delta < 0 && newnum > oldnum  )); then
+  zle -M "[$WIDGET] The resulting number is either too big or too small."
+  return 1
+fi
+
+# adjust the number of leading zeros if the sign of the integer changed
+local new
+if (( base == 10 && ndigits == $#padded )); then
+  if (( oldnum < 0 && newnum >= 0 )); then
+    new="${padded#0}"
+  elif (( oldnum >= 0 && newnum < 0 )); then
+    new="-0${padded#-}"
+  fi
+fi
+if [[ -z "$new" ]]; then
+  new="$padded"
+fi
+
+if zstyle -t ":zle:$WIDGET" debug; then
+  zle -M "[$WIDGET] base: $base delta: $delta old: '$old' new: '$new'"
+fi
+
+if (( 0 < first && first <= last && last <= $#BUFFER )); then
+  BUFFER[first,last]="$new"
+else
+  zle -M "[$WIDGET] The detected location of the integer was invalid. [location=BUFFER[$first,$last]]"
+  return 1
+fi
+
+integer offset=0
+if [[ "$WIDGET" == vi* ]]; then
+  offset=-1
+fi
+(( CURSOR = last + $#BUFFER - oldlen + offset ))
 
-BUFFER="$lrest$num$rrest"
+return 0
diff --git a/Misc/vcs_info-examples b/Misc/vcs_info-examples
index 94c47278d..ddd8dd9a8 100644
--- a/Misc/vcs_info-examples
+++ b/Misc/vcs_info-examples
@@ -343,7 +343,7 @@ function +vi-gen-applied-string() {
 
 
 # Allow substitutions and expansions in the prompt, necessary for
-# using a single-quoted $vcs_info_msg_0_ in PS1, RPOMPT (as used here) and
+# using a single-quoted $vcs_info_msg_0_ in PS1, RPROMPT (as used here) and
 # similar. Other ways of using the information are described above.
 setopt promptsubst
 # Load vcs_info to display information about version control repositories.
diff --git a/NEWS b/NEWS
index cdafd1ff5..d0a8584e2 100644
--- a/NEWS
+++ b/NEWS
@@ -4,6 +4,35 @@ CHANGES FROM PREVIOUS VERSIONS OF ZSH
 
 Note also the list of incompatibilities in the README file.
 
+Changes since 5.9
+-----------------
+
+In region_highlight and zle_highlight, italic and faint can be
+specified as font attributes for terminals that support them.
+
+Highlighting groups can be referenced in region_highlight and
+zle_highlight for common attribute combinations and a layer can be
+specified to indicate precedence where highlighted regions overlap.
+Highlighting groups are also supported in the prompt via a new %H
+prompt escape.
+
+Ellipsis markers shown by the line editor to indicate where the line
+doesn't fit in the terminal can be highlighted.
+
+The ERR_EXIT and ERR_RETURN options were refined to be more self-
+consistent and better aligned with the POSIX-2017 specification of
+`set -e`. For details on what exactly changed, see the list of
+incompatibilities in the README file.
+
+Support for named references and namespaces has been added, similar to
+those features in ksh but with some notable differences. The `nameref`
+builtin and some ksh-equivalent namespace names are available by loading
+the zsh/ksh93 module.  See the documentation of that module for more.
+
+Non-forking command substitutions with ${ ... } and ${| ... } are now
+available, and the latter extended with ${|param| ... } to return the
+result via assignment to the named param rather than always via $REPLY.
+
 Changes since 5.8.1
 -------------------
 
diff --git a/README b/README
index 21142e17c..8c11e6833 100644
--- a/README
+++ b/README
@@ -31,8 +31,105 @@ Zsh is a shell with lots of features.  For a list of some of these, see the
 file FEATURES, and for the latest changes see NEWS.  For more
 details, see the documentation.
 
-Incompatibilities since 5.8.1
------------------------------
+Incompatibilities since 5.9
+---------------------------
+
+The line editor's default keymap is now the "emacs" keymap regardless of the
+value of the environment variables $VISUAL and $EDITOR.  This only affects you
+if your $VISUAL or $EDITOR environment variable is set to a value that
+contains the string "vi".  To get the previous behaviour, add
+
+    bindkey -v
+
+or, if your $VISUAL and $EDITOR environment variables vary,
+
+    if [[ ${VISUAL} == *vi* || ${EDITOR} == *vi* ]]; then
+        bindkey -v
+    else
+        bindkey -e
+    fi
+
+to your .zshrc file.  These snippets are compatible with previous
+versions of the shell.
+
+The ERR_EXIT and ERR_RETURN options were refined to be more self-
+consistent and better aligned with the POSIX-2017 specification of
+`set -e`:
+
+  - Function calls or anonymous functions prefixed with `!` now never
+    trigger exit or return. Negated function calls or anonymous
+    functions used to trigger exit or return if ERR_EXIT or ERR_RETURN
+    was set and the function call or anonymous function returned a
+    zero exit status. Example:
+
+      setopt ERR_EXIT
+      f() { true }
+      ! f
+      echo "This is printed only since 5.10."
+
+  - The `always` command now ignores ERR_EXIT and ERR_RETURN, as other
+    complex commands do, if its exit status comes from a command
+    executed while the option is ignored. Example:
+
+      setopt ERR_EXIT
+      { false && true } always { echo "This was and still is printed." }
+      echo "This is printed only since 5.10."
+
+  - Function calls, anonymous functions, and the `eval`, `.`, and
+    `source` builtins now never ignore ERR_EXIT and ERR_RETURN on
+    their own. These commands used to ignore ERR_EXIT and ERR_RETURN
+    if their result came from a complex command (if, for, ...) whose
+    result came from a command executed while the option is
+    ignored. Example:
+
+      setopt ERR_EXIT
+      f() { if true; then false && true; fi }
+      f
+      echo "This is printed only prior to 5.10."
+
+  - The `&&` and `||` operators now always ignore ERR_RETURN in their
+    left operand. Until this version, the operators failed to ignored
+    ERR_RETURN in their left operand if they were executed as part of
+    a function call or an anonymous function that was itself executed
+    in a context where ERR_RETURN is ignored. Example:
+
+      setopt ERR_RETURN
+      f() { { false; echo "This is printed only since 5.10." } || true }
+      if f; then true; fi
+
+PCRE support is now PCRE2.
+
+Parameter names may begin with a "." and follow a relaxed implementation
+of ksh namespace syntax.  Expansion of such parameters must use braces,
+that is, in ${.param.name} form.  Parameters so named are excluded from
+`typeset` and `set` output unless explicitly listed in `typeset` arguments
+or matched by a pattern with `typeset -m`.
+
+Interpretation of exclusion-patterns following alternation-patterns has
+been rationalised.  This means for example that `[[ ab = (|a*)~^(*b) ]]`
+is true where previously it was false.
+
+Improvements to handling of terminal colors and attributes in prompts
+may change the behavior of some prompt sequences, most notably in
+cases where `esq=${(%)...}` is used to capture an escape sequence.
+
+The `which` and `functions` commands output function definitions in a
+format independent of the MULTI_FUNC_DEF option.
+
+Math context no longer interprets a leading underscore as part of a
+numeric constant.
+
+Nul and characters greater than \x77 are correctly handled by `read -d`.
+
+Return values of `sysopen` from the zsh/system module have been updated
+to be more similar to other commands in that module.
+
+Tied parameters created with the zsh/db/gdbm module may not be re-tied
+as locals in nested function scope.  This prevents database corruption
+when a function scope ends.
+
+Incompatibilities between 5.8.1 and 5.9
+---------------------------------------
 
 compinit: A "y" response to the "Ignore ... and continue?" prompt removes
 insecure elements from the set of completion functions, where previously
diff --git a/Src/Makemod.in.in b/Src/Makemod.in.in
index ea0cdc3a4..3343ae1d0 100644
--- a/Src/Makemod.in.in
+++ b/Src/Makemod.in.in
@@ -52,32 +52,17 @@ DLCOMPILE   = $(CC) -c -I. -I$(dir_top)/Src -I$(sdir_top)/Src -I$(sdir_top)/Src/
 LINK        = $(CC) $(LDFLAGS) $(EXELDFLAGS) $(EXTRA_LDFLAGS) -o $@
 DLLINK      = $(DLLD) $(LDFLAGS) $(LIBLDFLAGS) $(DLLDFLAGS) -o $@
 
-KNR_OBJ=.o
-KNROBJ=._foo_
+OBJ=.o
 
-ANSIOBJ=.o
-ANSI_OBJ=._foo_
+.SUFFIXES: .c .$(DL_EXT) ..o .o .syms .pro .epro
 
-.SUFFIXES: .c .$(DL_EXT) ..o .._foo_ .o ._foo_ .syms .pro .epro
-
-.c$(ANSI@U@OBJ):
+.c$(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):
+.c.$(OBJ):
 	$(DLCOMPILE) -o $@ $<
 
-.c.$(KNR@U@OBJ):
-	@ANSI2KNR@ $< > $@.c
-	$(DLCOMPILE) -o $@ $@.c
-	rm -f $@.c
-
 .c.syms:
 	$(AWK) -f $(sdir_src)/makepro.awk $< $(subdir) > $@
 
diff --git a/Src/Modules/curses.c b/Src/Modules/curses.c
index e46903916..8950cc153 100644
--- a/Src/Modules/curses.c
+++ b/Src/Modules/curses.c
@@ -1302,7 +1302,7 @@ zccmd_mouse(const char *nam, char **args)
 	    zlong delay;
 
 	    if (!*++args ||
-		((delay = zstrtol(*args, &eptr, 10)), eptr != NULL)) {
+		((delay = zstrtol(*args, &eptr, 10)), *eptr != '\0')) {
 		zwarnnam(nam, "mouse delay requires an integer argument");
 		return 1;
 	    }
@@ -1326,7 +1326,7 @@ zccmd_mouse(const char *nam, char **args)
 		if (old_mask != zcurses_mouse_mask)
 		    zcurses_flags |= ZCF_MOUSE_MASK_CHANGED;
 	    } else {
-		zwarnnam(nam, "unrecognised mouse command: %s", *arg);
+		zwarnnam(nam, "unrecognised mouse command: %s", arg);
 		return 1;
 	    }
 	}
@@ -1426,10 +1426,10 @@ zccmd_querychar(const char *nam, char **args)
     inc &= A_CHARTEXT;
     if (imeta(inc)) {
 	instr[0] = Meta;
-	instr[1] = STOUC(inc ^ 32);
+	instr[1] = (unsigned char) (inc ^ 32);
 	instr[2] = '\0';
     } else {
-	instr[0] = STOUC(inc);
+  	instr[0] = (unsigned char) inc;
 	instr[1] = '\0';
     }
     attrs = inc;
diff --git a/Src/Modules/files.c b/Src/Modules/files.c
index bf0e8f8a8..a3fec1daa 100644
--- a/Src/Modules/files.c
+++ b/Src/Modules/files.c
@@ -29,8 +29,8 @@
 
 #include "files.mdh"
 
-typedef int (*MoveFunc) _((char const *, char const *));
-typedef int (*RecurseFunc) _((char *, char *, struct stat const *, void *));
+typedef int (*MoveFunc) (char const *, char const *);
+typedef int (*RecurseFunc) (char *, char *, struct stat const *, void *);
 
 struct recursivecmd;
 
diff --git a/Src/Modules/hlgroup.c b/Src/Modules/hlgroup.c
new file mode 100644
index 000000000..082762623
--- /dev/null
+++ b/Src/Modules/hlgroup.c
@@ -0,0 +1,216 @@
+/*
+ * hlgroup.c - Supporting parameters for highlight groups
+ *
+ * This file is part of zsh, the Z shell.
+ *
+ * Copyright (c) 2024 Oliver Kiddle
+ * 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 Oliver Kiddle 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 Oliver Kiddle and the Zsh Development Group have been advised of
+ * the possibility of such damage.
+ *
+ * Oliver Kiddle 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 Oliver Kiddle and the
+ * Zsh Development Group have no obligation to provide maintenance,
+ * support, updates, enhancements, or modifications.
+ *
+ */
+
+#include "hlgroup.mdh"
+#include "hlgroup.pro"
+
+#define GROUPVAR ".zle.hlgroups"
+
+static const struct gsu_scalar pmesc_gsu =
+{ strgetfn, nullstrsetfn, nullunsetfn };
+
+/**/
+static char *
+convertattr(char *attrstr, int sgr)
+{
+    zattr atr;
+    char *r, *s;
+    int len;
+
+    match_highlight(attrstr, &atr, NULL);
+    s = zattrescape(atr, sgr ? NULL : &len);
+
+    if (sgr) {
+	char *c = s, *t = s - 1;
+
+	while (c[0] == '\033' && c[1] == '[') {
+	    c += 2;
+	    while (isdigit(*c) || *c == ';')
+		*++t = *c++;
+	    t++;
+	    if (*c != 'm')
+		break;
+	    *t = ';';
+	    c++;
+	}
+	if (t <= s) { /* always return at least "0" */
+	    *s = '0';
+	    t = s + 1;
+	}
+	*t = '\0';
+	len = t - s;
+    }
+
+    r = dupstring_wlen(s, len);
+    free(s);
+    return r;
+}
+
+/**/
+static HashNode
+getgroup(const char *name, int sgr)
+{
+    Param pm = NULL;
+    HashNode hn;
+    HashTable hlg;
+    Value v;
+    struct value vbuf;
+    char *var = GROUPVAR;
+
+    pm = (Param) hcalloc(sizeof(struct param));
+    pm->gsu.s = &pmesc_gsu;
+    pm->node.nam = dupstring(name);
+    pm->node.flags = PM_SCALAR|PM_SPECIAL;
+
+    if (!(v = getvalue(&vbuf, &var, 0)) ||
+	     PM_TYPE(v->pm->node.flags) != PM_HASHED ||
+	     !(hlg = v->pm->gsu.h->getfn(v->pm)) ||
+	     !(hn = gethashnode2(hlg, name)) ||
+	     (((Param) hn)->node.flags & PM_UNSET))
+    {
+	pm->u.str = dupstring("");
+	pm->node.flags |= PM_UNSET;
+    } else {
+	pm->u.str = convertattr(((Param) hn)->u.str, sgr);
+    }
+
+    return &pm->node;
+}
+
+/**/
+static void
+scangroup(ScanFunc func, int flags, int sgr)
+{
+    struct param pm;
+    int i;
+    HashNode hn;
+    HashTable hlg;
+    Value v;
+    struct value vbuf;
+    char *var = GROUPVAR;
+
+    if (!(v = getvalue(&vbuf, &var, 0)) ||
+	     PM_TYPE(v->pm->node.flags) != PM_HASHED)
+	return;
+    hlg = v->pm->gsu.h->getfn(v->pm);
+
+    memset((void *)&pm, 0, sizeof(struct param));
+    pm.node.flags = PM_SCALAR;
+    pm.gsu.s = &pmesc_gsu;
+
+    for (i = 0; i < hlg->hsize; i++)
+	for (hn = hlg->nodes[i]; hn; hn = hn->next) {
+	    pm.u.str = convertattr(((Param) hn)->u.str, sgr);
+	    pm.node.nam = hn->nam;
+	    func(&pm.node, flags);
+	}
+}
+/**/
+static HashNode
+getpmesc(UNUSED(HashTable ht), const char *name)
+{
+    return getgroup(name, 0);
+}
+
+/**/
+static void
+scanpmesc(UNUSED(HashTable ht), ScanFunc func, int flags)
+{
+    scangroup(func, flags, 0);
+}
+
+/**/
+static HashNode
+getpmsgr(UNUSED(HashTable ht), const char *name)
+{
+    return getgroup(name, 1);
+}
+
+/**/
+static void
+scanpmsgr(UNUSED(HashTable ht), ScanFunc func, int flags)
+{
+    scangroup(func, flags, 1);
+}
+
+static struct paramdef partab[] = {
+    SPECIALPMDEF(".zle.esc", PM_READONLY_SPECIAL, 0, getpmesc, scanpmesc),
+    SPECIALPMDEF(".zle.sgr", PM_READONLY_SPECIAL, 0, getpmsgr, scanpmsgr)
+};
+
+static struct features module_features = {
+    NULL, 0,
+    NULL, 0,
+    NULL, 0,
+    partab, sizeof(partab)/sizeof(*partab),
+    0
+};
+
+/**/
+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))
+{
+    return 0;
+}
+
+/**/
+int
+cleanup_(Module m)
+{
+    return setfeatureenables(m, &module_features, NULL);
+}
+
+/**/
+int
+finish_(UNUSED(Module m))
+{
+    return 0;
+}
diff --git a/Src/Modules/hlgroup.mdd b/Src/Modules/hlgroup.mdd
new file mode 100644
index 000000000..ee3ba7260
--- /dev/null
+++ b/Src/Modules/hlgroup.mdd
@@ -0,0 +1,7 @@
+name=zsh/hlgroup
+link=either
+load=yes
+
+autofeatures="p:.zle.esc p:.zle.sgr"
+
+objects="hlgroup.o"
diff --git a/Src/Modules/ksh93.c b/Src/Modules/ksh93.c
new file mode 100644
index 000000000..3206c11f3
--- /dev/null
+++ b/Src/Modules/ksh93.c
@@ -0,0 +1,287 @@
+/*
+ * ksh93.c - support for more ksh93 features
+ *
+ * This file is part of zsh, the Z shell.
+ *
+ * Copyright (c) 2022 Barton E. Schaefer
+ * 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 Barton E. Schaefer 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 Barton E. Schaefer and the Zsh
+ * Development Group have been advised of the possibility of such damage.
+ *
+ * Barton E. Schaefer 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
+ * Barton E. Schaefer and the Zsh Development Group have no
+ * obligation to provide maintenance, support, updates, enhancements, or
+ * modifications.
+ *
+ */
+
+#include "ksh93.mdh"
+#include "ksh93.pro"
+
+/* Implementing "namespace" requires creating a new keword.  Hrm. */
+
+/*
+ * Standard module configuration/linkage
+ */
+
+static struct builtin bintab[] = {
+    BUILTIN("nameref", BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "gur", "n")
+};
+
+#include "zsh.mdh"
+
+static void
+edcharsetfn(Param pm, char *x)
+{
+    /*
+     * To make this work like ksh, we must intercept $KEYS before the widget
+     * is looked up, so that changing the key sequence causes a different
+     * widget to be substituted.  Somewhat similar to "bindkey -s".
+     *
+     * Ksh93 adds SIGKEYBD to the trap list for this purpose.
+     */
+    ;
+}
+
+static char **
+matchgetfn(Param pm)
+{
+    char **zsh_match = getaparam("match");
+
+    /* For this to work accurately, ksh emulation should always imply
+     * that the (#m) and (#b) extendedglob operators are enabled.
+     *
+     * When we have a 0th element (ksharrays), it is $MATCH.  Elements
+     * 1st and larger mirror the $match array.
+     */
+
+    if (pm->u.arr)
+	freearray(pm->u.arr);
+    if (zsh_match && *zsh_match) {
+	if (isset(KSHARRAYS)) {
+	    char **ap =
+		(char **) zalloc(sizeof(char *) * (arrlen(zsh_match)+1));
+	    pm->u.arr = ap;
+	    *ap++ = ztrdup(getsparam("MATCH"));
+	    while (*zsh_match)
+		*ap = ztrdup(*zsh_match++);
+	} else
+	    pm->u.arr = zarrdup(zsh_match);
+    } else if (isset(KSHARRAYS)) {
+	pm->u.arr = mkarray(ztrdup(getsparam("MATCH")));
+    } else
+	pm->u.arr = NULL;
+
+    return arrgetfn(pm);
+}
+
+static const struct gsu_scalar constant_gsu =
+    { strgetfn, NULL, nullunsetfn };
+
+static const struct gsu_scalar sh_edchar_gsu =
+    { strvargetfn, edcharsetfn, nullunsetfn };
+static const struct gsu_scalar sh_edmode_gsu =
+    { strgetfn, nullstrsetfn, nullunsetfn };
+static const struct gsu_array sh_match_gsu =
+    { matchgetfn, arrsetfn, stdunsetfn };
+static const struct gsu_scalar sh_name_gsu =
+    { strvargetfn, nullstrsetfn, nullunsetfn };
+static const struct gsu_scalar sh_subscript_gsu =
+    { strvargetfn, nullstrsetfn, nullunsetfn };
+
+static char sh_unsetval[2];	/* Dummy to treat as NULL */
+static char *sh_name = sh_unsetval;
+static char *sh_subscript = sh_unsetval;
+static char *sh_edchar = sh_unsetval;
+static char sh_edmode[2];
+
+/*
+ * Some parameters listed here do not appear in ksh93.mdd autofeatures
+ * because they are only instantiated by ksh93_wrapper() below.  This
+ * obviously includes those commented out here.
+ */
+static struct paramdef partab[] = {
+    PARAMDEF(".sh.edchar", PM_SCALAR|PM_SPECIAL,
+	     &sh_edchar, &sh_edchar_gsu),
+    PARAMDEF(".sh.edmode", PM_SCALAR|PM_READONLY|PM_SPECIAL,
+	     &sh_edmode, &sh_edmode_gsu),
+    PARAMDEF(".sh.file", PM_NAMEREF|PM_READONLY, "ZSH_SCRIPT", &constant_gsu),
+    PARAMDEF(".sh.lineno", PM_NAMEREF|PM_READONLY, "LINENO", &constant_gsu),
+    PARAMDEF(".sh.match", PM_ARRAY|PM_READONLY, NULL, &sh_match_gsu),
+    PARAMDEF(".sh.name", PM_SCALAR|PM_READONLY|PM_SPECIAL,
+	     &sh_name, &sh_name_gsu),
+    PARAMDEF(".sh.subscript", PM_SCALAR|PM_READONLY|PM_SPECIAL,
+	     &sh_subscript, &sh_subscript_gsu),
+    PARAMDEF(".sh.subshell", PM_NAMEREF|PM_READONLY, "ZSH_SUBSHELL", &constant_gsu),
+    /* SPECIALPMDEF(".sh.value", 0, NULL, NULL, NULL), */
+    PARAMDEF(".sh.version", PM_NAMEREF|PM_READONLY, "ZSH_PATCHLEVEL", &constant_gsu)
+};
+
+static struct features module_features = {
+    bintab, sizeof(bintab)/sizeof(*bintab),
+    NULL, 0,
+    NULL, 0,
+    partab, sizeof(partab)/sizeof(*partab),
+    0
+};
+
+/**/
+static int
+ksh93_wrapper(Eprog prog, FuncWrap w, char *name)
+{
+    Funcstack f;
+    Param pm;
+    zlong num = funcstack->prev ? getiparam(".sh.level") : 0;
+
+    if (!EMULATION(EMULATE_KSH))
+	return 1;
+
+    if (num == 0)
+	for (f = funcstack; f; f = f->prev, num++);
+    else
+	num++;
+
+    queue_signals();
+    ++locallevel;		/* Make these local */
+#define LOCAL_NAMEREF (PM_LOCAL|PM_UNSET|PM_NAMEREF)
+    if ((pm = createparam(".sh.command", LOCAL_NAMEREF))) {
+	pm->level = locallevel;	/* Why is this necessary? */
+	/* Force scoping by assignent hack */
+	setloopvar(".sh.command", "ZSH_DEBUG_CMD");
+	pm->node.flags |= PM_READONLY;
+    }
+    /* .sh.edchar is in partab and below */
+    if (zleactive && (pm = createparam(".sh.edcol", LOCAL_NAMEREF))) {
+	pm->level = locallevel;
+	setloopvar(".sh.edcol", "CURSOR");
+	pm->node.flags |= (PM_NAMEREF|PM_READONLY);
+    }
+    /* .sh.edmode is in partab and below */
+    if (zleactive && (pm = createparam(".sh.edtext", LOCAL_NAMEREF))) {
+	pm->level = locallevel;
+	setloopvar(".sh.edtext", "BUFFER");
+	pm->node.flags |= PM_READONLY;
+    }
+
+    if ((pm = createparam(".sh.fun", PM_LOCAL|PM_UNSET))) {
+	pm->level = locallevel;
+	setsparam(".sh.fun", ztrdup(name));
+	pm->node.flags |= PM_READONLY;
+    }
+    if ((pm = createparam(".sh.level", PM_LOCAL|PM_UNSET))) {
+	pm->level = locallevel;
+	setiparam(".sh.level", num);
+    }
+    if (zleactive) {
+	extern mod_import_variable char *curkeymapname;	/* XXX */
+	extern mod_import_variable char *varedarg;	/* XXX */
+	/* bindkey -v forces VIMODE so this test is as good as any */
+	if (curkeymapname && isset(VIMODE) &&
+	    strcmp(curkeymapname, "main") == 0)
+	    strcpy(sh_edmode, "\033");
+	else
+	    strcpy(sh_edmode, "");
+	if (sh_edchar == sh_unsetval)
+	    sh_edchar = dupstring(getsparam("KEYS"));
+	if (varedarg) {
+	    char *ie = itype_end((sh_name = dupstring(varedarg)), INAMESPC, 0);
+	    if (ie && *ie) {
+		*ie++ = '\0';
+		/* Assume bin_vared has validated subscript */
+		sh_subscript = dupstring(ie);
+		ie = sh_subscript + strlen(sh_subscript);
+		*--ie = '\0';
+	    } else
+		sh_subscript = sh_unsetval;
+	    if ((pm = createparam(".sh.value", LOCAL_NAMEREF))) {
+		pm->level = locallevel;
+		setloopvar(".sh.value", "BUFFER");	/* Hack */
+		pm->node.flags |= PM_READONLY;
+	    }
+	} else
+	    sh_name = sh_subscript = sh_unsetval;
+    } else {
+	sh_edchar = sh_name = sh_subscript = sh_unsetval;
+	strcpy(sh_edmode, "");
+	/* TODO:
+	 * - disciplines
+	 * - special handling of .sh.value in math
+	 */
+    }
+    --locallevel;
+    unqueue_signals();
+
+    return 1;
+}
+
+static struct funcwrap wrapper[] = {
+    WRAPDEF(ksh93_wrapper),
+};
+
+/**/
+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_(Module m)
+{
+    return addwrapper(m, wrapper);
+}
+
+/**/
+int
+cleanup_(Module m)
+{
+    struct paramdef *p;
+
+    deletewrapper(m, wrapper);
+
+    /* Clean up namerefs, otherwise deleteparamdef() is confused */
+    for (p = partab; p < partab + sizeof(partab)/sizeof(*partab); ++p) {
+	if (p->flags & PM_NAMEREF) {
+	    HashNode hn = gethashnode2(paramtab, p->name);
+	    if (hn)
+		((Param)hn)->node.flags &= ~PM_NAMEREF;
+	}
+    }
+    return setfeatureenables(m, &module_features, NULL);
+}
+
+/**/
+int
+finish_(UNUSED(Module m))
+{
+    return 0;
+}
diff --git a/Src/Modules/ksh93.mdd b/Src/Modules/ksh93.mdd
new file mode 100644
index 000000000..85e35e9cb
--- /dev/null
+++ b/Src/Modules/ksh93.mdd
@@ -0,0 +1,10 @@
+name=zsh/ksh93
+link=either
+load=yes
+
+autofeatures="b:nameref"
+autofeatures_emu="b:nameref p:.sh.command p:.sh.edcol p:.sh.edtext p:.sh.file p:.sh.lineno p:.sh.match p:.sh.subshell p:.sh.version"
+
+moddeps="zsh/zle"
+
+objects="ksh93.o"
diff --git a/Src/Modules/mapfile.c b/Src/Modules/mapfile.c
index dd86fb596..84cdfea18 100644
--- a/Src/Modules/mapfile.c
+++ b/Src/Modules/mapfile.c
@@ -170,6 +170,8 @@ get_contents(char *fname)
 #ifdef USE_MMAP
     caddr_t mmptr;
     struct stat sbuf;
+#else
+    off_t size;
 #endif
     char *val;
     unmetafy(fname = ztrdup(fname), &fd);
@@ -196,12 +198,8 @@ get_contents(char *fname)
     close(fd);
 #else /* don't USE_MMAP */
     val = NULL;
-    if ((fd = open(fname, O_RDONLY | O_NOCTTY)) >= 0) {
-	LinkList ll;
-
-	if ((ll = readoutput(fd, 1, 0)))
-	    val = peekfirst(ll);
-    }
+    if ((size = zstuff(&val, fname)) > 0)
+	val = metafy(val, size, META_HEAPDUP);
 #endif /* USE_MMAP */
     free(fname);
     return val;
diff --git a/Src/Modules/param_private.c b/Src/Modules/param_private.c
index 065fa63d2..044617190 100644
--- a/Src/Modules/param_private.c
+++ b/Src/Modules/param_private.c
@@ -87,9 +87,52 @@ makeprivate(HashNode hn, UNUSED(int flags))
 	      ((pm->node.flags & (PM_SPECIAL|PM_REMOVABLE)) == PM_SPECIAL &&
 	       /* typeset_single() line 2300 discards PM_REMOVABLE -- why? */
 	       !is_private(pm->old))))) {
-	    zwarnnam("private", "can't change scope of existing param: %s",
-		     pm->node.nam);
-	    makeprivate_error = 1;
+	    if (is_private(pm->old)) {
+		if (pm->old->node.flags & PM_READONLY) {
+		    zerr("read-only variable: %s", pm->node.nam);
+		    makeprivate_error = 1;
+		} else if ((pm->node.flags | pm->old->node.flags) ==
+		    pm->old->node.flags) {
+		    /* private called twice on same parameter */
+		    Param tpm = pm;
+		    pm = pm->old;
+		    --locallevel;
+		    /* why have a union if we need this switch anyway? */
+		    switch (PM_TYPE(pm->node.flags)) {
+		    case PM_SCALAR:
+			pm->gsu.s->setfn(pm, tpm->u.str);
+			tpm->u.str = NULL;
+			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);
+			tpm->u.arr = NULL;
+			break;
+		    case PM_HASHED:
+			pm->gsu.h->setfn(pm, tpm->u.hash);
+			tpm->u.hash = NULL;
+			break;
+		    }
+		    ++locallevel;
+		    if (!(tpm->node.flags & PM_UNSET))
+			pm->node.flags &= ~PM_UNSET;
+		} else {
+		    zerrnam("private",
+			    "can't change type of private param: %s",
+			    pm->node.nam);
+		    makeprivate_error = 1;
+		}
+	    } else {
+		zerrnam("private", "can't change scope of existing param: %s",
+			pm->node.nam);
+		makeprivate_error = 1;
+	    }
 	    return;
 	}
 	struct gsu_closure *gsu = zalloc(sizeof(struct gsu_closure));
@@ -122,6 +165,7 @@ makeprivate(HashNode hn, UNUSED(int flags))
 	    break;
 	default:
 	    makeprivate_error = 1;
+	    zfree(gsu, sizeof(struct gsu_closure));
 	    break;
 	}
 	/* PM_HIDE so new parameters in deeper scopes do not shadow */
@@ -229,7 +273,9 @@ setfn_error(Param pm)
  * calling the original unsetfn.  This assures that if the old unsetfn
  * wants to use its getfn or setfn, they're unconditionally present.
  * The "explicit" flag indicates that "unset" was called, if zero the
- * parameter is going out of scope (see params.c).
+ * parameter is going out of scope (see params.c).  PM_DECLARED is
+ * asserted as if TYPESET_TO_UNSET were in use so that the private
+ * parameter is re-used rather than re-created when assigned again.
  *
  */
 
@@ -252,7 +298,7 @@ pps_setfn(Param pm, char *x)
 {
     struct gsu_closure *c = (struct gsu_closure *)(pm->gsu.s);
     GsuScalar gsu = (GsuScalar)(c->g);
-    if (locallevel == pm->level)
+    if (locallevel == pm->level || locallevel > private_wraplevel)
 	gsu->setfn(pm, x);
     else
 	setfn_error(pm);
@@ -267,9 +313,10 @@ pps_unsetfn(Param pm, int explicit)
     pm->gsu.s = gsu;
     if (locallevel <= pm->level)
 	gsu->unsetfn(pm, explicit);
-    if (explicit)
+    if (explicit) {
+	pm->node.flags |= PM_DECLARED;
 	pm->gsu.s = (GsuScalar)c;
-    else
+    } else
 	zfree(c, sizeof(struct gsu_closure));
 }
 
@@ -291,7 +338,7 @@ ppi_setfn(Param pm, zlong x)
 {
     struct gsu_closure *c = (struct gsu_closure *)(pm->gsu.i);
     GsuInteger gsu = (GsuInteger)(c->g);
-    if (locallevel == pm->level)
+    if (locallevel == pm->level || locallevel > private_wraplevel)
 	gsu->setfn(pm, x);
     else
 	setfn_error(pm);
@@ -306,9 +353,10 @@ ppi_unsetfn(Param pm, int explicit)
     pm->gsu.i = gsu;
     if (locallevel <= pm->level)
 	gsu->unsetfn(pm, explicit);
-    if (explicit)
+    if (explicit) {
+	pm->node.flags |= PM_DECLARED;
 	pm->gsu.i = (GsuInteger)c;
-    else
+    } else
 	zfree(c, sizeof(struct gsu_closure));
 }
 
@@ -330,7 +378,7 @@ ppf_setfn(Param pm, double x)
 {
     struct gsu_closure *c = (struct gsu_closure *)(pm->gsu.f);
     GsuFloat gsu = (GsuFloat)(c->g);
-    if (locallevel == pm->level)
+    if (locallevel == pm->level || locallevel > private_wraplevel)
 	gsu->setfn(pm, x);
     else
 	setfn_error(pm);
@@ -345,9 +393,10 @@ ppf_unsetfn(Param pm, int explicit)
     pm->gsu.f = gsu;
     if (locallevel <= pm->level)
 	gsu->unsetfn(pm, explicit);
-    if (explicit)
+    if (explicit) {
+	pm->node.flags |= PM_DECLARED;
 	pm->gsu.f = (GsuFloat)c;
-    else
+    } else
 	zfree(c, sizeof(struct gsu_closure));
 }
 
@@ -370,7 +419,7 @@ ppa_setfn(Param pm, char **x)
 {
     struct gsu_closure *c = (struct gsu_closure *)(pm->gsu.a);
     GsuArray gsu = (GsuArray)(c->g);
-    if (locallevel == pm->level)
+    if (locallevel == pm->level || locallevel > private_wraplevel)
 	gsu->setfn(pm, x);
     else
 	setfn_error(pm);
@@ -385,9 +434,10 @@ ppa_unsetfn(Param pm, int explicit)
     pm->gsu.a = gsu;
     if (locallevel <= pm->level)
 	gsu->unsetfn(pm, explicit);
-    if (explicit)
+    if (explicit) {
+	pm->node.flags |= PM_DECLARED;
 	pm->gsu.a = (GsuArray)c;
-    else
+    } else
 	zfree(c, sizeof(struct gsu_closure));
 }
 
@@ -411,7 +461,7 @@ pph_setfn(Param pm, HashTable x)
 {
     struct gsu_closure *c = (struct gsu_closure *)(pm->gsu.h);
     GsuHash gsu = (GsuHash)(c->g);
-    if (locallevel == pm->level)
+    if (locallevel == pm->level || locallevel > private_wraplevel)
 	gsu->setfn(pm, x);
     else
 	setfn_error(pm);
@@ -426,9 +476,10 @@ pph_unsetfn(Param pm, int explicit)
     pm->gsu.h = gsu;
     if (locallevel <= pm->level)
 	gsu->unsetfn(pm, explicit);
-    if (explicit)
+    if (explicit) {
+	pm->node.flags |= PM_DECLARED;
 	pm->gsu.h = (GsuHash)c;
-    else
+    } else
 	zfree(c, sizeof(struct gsu_closure));
 }
 
@@ -489,18 +540,19 @@ static struct funcwrap wrapper[] = {
 };
 
 /**/
+static int private_wraplevel = 0;
+
+/**/
 static int
 wrap_private(Eprog prog, FuncWrap w, char *name)
 {
-    static int wraplevel = 0;
-
-    if (wraplevel < locallevel /* && strcmp(name, "(anon)") != 0 */) {
-	int owl = wraplevel;
-	wraplevel = locallevel;
+    if (private_wraplevel < locallevel /* && strcmp(name, "(anon)") != 0 */) {
+	int owl = private_wraplevel;
+	private_wraplevel = locallevel;
 	scanhashtable(paramtab, 0, 0, 0, scopeprivate, PM_UNSET);
 	runshfunc(prog, w, name);
 	scanhashtable(paramtab, 0, 0, 0, scopeprivate, 0);
-	wraplevel = owl;
+	private_wraplevel = owl;
 	return 0;
     }
     return 1;
@@ -512,27 +564,50 @@ static GetNodeFunc getparamnode;
 static HashNode
 getprivatenode(HashTable ht, const char *nam)
 {
-    HashNode hn = getparamnode(ht, nam);
+    /* getparamnode() would follow namerefs, we must not do that here */
+    HashNode hn = gethashnode2(ht, nam);
     Param pm = (Param) hn;
 
-    while (!fakelevel && pm && locallevel > pm->level && is_private(pm)) {
+    /* autoload has precedence over nameref, so getparamnode() */
+    if (pm && (pm->node.flags & PM_AUTOLOAD)) {
+	hn = getparamnode(ht, nam);
+	pm = (Param) hn;
+	/* how would an autoloaded private behave?  return here? */
+    }
+    while (!fakelevel && pm && is_private(pm) && locallevel > pm->level) {
+	if (pm->level == private_wraplevel + 1) {
+	    /* Variable is in the current function scope */
+	    break;
+	}
+#if 0
 	if (!(pm->node.flags & PM_UNSET)) {
 	    /*
 	     * private parameters are always marked PM_UNSET before we
-	     * increment locallevel, so the only way we get here is
-	     * when createparam() wants a new parameter that is not at
-	     * the current locallevel and it has therefore cleared the
-	     * PM_UNSET flag.
+	     * increment locallevel, so there are three possible ways
+	     * to get here:
+	     *  1) createparam() wants a new parameter that is not at
+	     *  the current locallevel and it has therefore cleared the
+	     *  PM_UNSET flag
+	     *  2) locallevel has been incremented (startparamscope())
+	     *  outside the usual function call stack (private_wraplevel)
+	     *  3) dynamic scoping is fetching a value from a surrounding
+	     *  scope, we don't know if that's for assign or just expand
+	     * The first of those is now caught in createparam() when
+	     * testing PM_RO_BY_DESIGN and the second occurs only in
+	     * nofork substitution or handling of ZLE specials.  If the
+	     * third is an assignment, the GSU setfn rejects it.
 	     */
 	    DPUTS(pm->old, "BUG: PM_UNSET cleared in wrong scope");
-	    setfn_error(pm);
-	    /*
-	     * TODO: instead of throwing an error here, create a global
-	     * parameter, insert as pm->old, handle WARN_CREATE_GLOBAL.
-	     */
 	}
+#endif
 	pm = pm->old;
     }
+
+    /* resolve nameref after skipping private parameters */
+    if (pm && (pm->node.flags & PM_NAMEREF) &&
+	(pm->u.str || (pm->node.flags & PM_UNSET)))
+	pm = (Param) resolve_nameref(pm, NULL);
+
     return (HashNode)pm;
 }
 
@@ -571,7 +646,7 @@ printprivatenode(HashNode hn, int printflags)
 
 static struct builtin bintab[] = {
     /* Copied from BUILTIN("local"), "P" added */
-    BUILTIN("private", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_private, 0, -1, 0, "AE:%F:%HL:%PR:%TUZ:%ahi:%lmprtux", "P")
+    BUILTIN("private", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_private, 0, -1, 0, "AE:%F:%HL:%PR:%TUZ:%ahi:%lnmrtux", "P")
 };
 
 static struct features module_features = {
diff --git a/Src/Modules/parameter.c b/Src/Modules/parameter.c
index dbb61e474..7441c30b8 100644
--- a/Src/Modules/parameter.c
+++ b/Src/Modules/parameter.c
@@ -49,13 +49,15 @@ paramtypestr(Param pm)
 	if (pm->node.flags & PM_AUTOLOAD)
 	    return dupstring("undefined");
 
-	switch (PM_TYPE(f)) {
+	/* For simplicity we treat PM_NAMEREF as PM_TYPE(PM_SCALAR) */
+	switch (PM_TYPE(f)|(f & PM_NAMEREF)) {
 	case PM_SCALAR:  val = "scalar"; break;
 	case PM_ARRAY:   val = "array"; break;
 	case PM_INTEGER: val = "integer"; break;
 	case PM_EFLOAT:
 	case PM_FFLOAT:  val = "float"; break;
 	case PM_HASHED:  val = "association"; break;
+	case PM_NAMEREF: val = "nameref"; break;
 	}
 	DPUTS(!val, "BUG: type not handled in parameter");
 	val = dupstring(val);
@@ -103,10 +105,15 @@ getpmparameter(UNUSED(HashTable ht), const char *name)
     pm->node.nam = dupstring(name);
     pm->node.flags = PM_SCALAR | PM_READONLY;
     pm->gsu.s = &nullsetscalar_gsu;
-    if ((rpm = (Param) realparamtab->getnode(realparamtab, name)) &&
-	!(rpm->node.flags & PM_UNSET))
+    if ((rpm = (Param) realparamtab->getnode2(realparamtab, name)) &&
+	!(rpm->node.flags & PM_UNSET)) {
 	pm->u.str = paramtypestr(rpm);
-    else {
+	if ((rpm->node.flags & PM_NAMEREF) && rpm->u.str && *(rpm->u.str) &&
+	    (rpm = (Param) realparamtab->getnode(realparamtab, name)) &&
+	    !(rpm->node.flags & PM_UNSET)) {
+	    pm->u.str = zhtricat(pm->u.str, "-", paramtypestr(rpm));
+	}
+    } else {
 	pm->u.str = dupstring("");
 	pm->node.flags |= (PM_UNSET|PM_SPECIAL);
     }
@@ -302,7 +309,7 @@ setfunction(char *name, char *val, int dis)
     shfunc_set_sticky(shf);
 
     if (!strncmp(name, "TRAP", 4) &&
-	(sn = getsignum(name + 4)) != -1) {
+	(sn = getsigidx(name + 4)) != -1) {
 	if (settrap(sn, NULL, ZSIG_FUNC)) {
 	    freeeprog(shf->funcdef);
 	    zfree(shf, sizeof(*shf));
@@ -1226,9 +1233,16 @@ histwgetfn(UNUSED(Param pm))
             pushnode(l, getdata(n));
 
     while (he) {
+	char *hstr = he->node.nam;
+	int len = strlen(hstr);
 	for (iw = he->nwords - 1; iw >= 0; iw--) {
-	    h = he->node.nam + he->words[iw * 2];
-	    e = he->node.nam + he->words[iw * 2 + 1];
+	    int wbegin = he->words[iw * 2];
+	    int wend = he->words[iw * 2 + 1];
+
+	    if (wbegin < 0 || wbegin >= len || wend < 0 || wend > len)
+		break;
+	    h = hstr + wbegin;
+	    e = hstr + wend;
 	    sav = *e;
 	    *e = '\0';
 	    addlinknode(l, dupstring(h));
diff --git a/Src/Modules/pcre.c b/Src/Modules/pcre.c
index 6289e003e..67157cc01 100644
--- a/Src/Modules/pcre.c
+++ b/Src/Modules/pcre.c
@@ -34,11 +34,11 @@
 #define CPCRE_PLAIN 0
 
 /**/
-#if defined(HAVE_PCRE_COMPILE) && defined(HAVE_PCRE_EXEC)
-#include <pcre.h>
+#if defined(HAVE_PCRE2_COMPILE_8) && defined(HAVE_PCRE2_H)
+#define PCRE2_CODE_UNIT_WIDTH 8
+#include <pcre2.h>
 
-static pcre *pcre_pattern;
-static pcre_extra *pcre_hints;
+static pcre2_code *pcre_pattern;
 
 /**/
 static int
@@ -47,8 +47,6 @@ zpcre_utf8_enabled(void)
 #if defined(MULTIBYTE_SUPPORT) && defined(HAVE_NL_LANGINFO) && defined(CODESET)
     static int have_utf8_pcre = -1;
 
-    /* value can toggle based on MULTIBYTE, so don't
-     * be too eager with caching */
     if (have_utf8_pcre < -1)
 	return 0;
 
@@ -56,15 +54,11 @@ zpcre_utf8_enabled(void)
 	return 0;
 
     if ((have_utf8_pcre == -1) &&
-        (!strcmp(nl_langinfo(CODESET), "UTF-8"))) {
-
-	if (pcre_config(PCRE_CONFIG_UTF8, &have_utf8_pcre))
-	    have_utf8_pcre = -2; /* erk, failed to ask */
+       (pcre2_config(PCRE2_CONFIG_UNICODE, &have_utf8_pcre))) {
+           have_utf8_pcre = -2; /* erk, failed to ask */
     }
 
-    if (have_utf8_pcre < 0)
-	return 0;
-    return have_utf8_pcre;
+    return (have_utf8_pcre == 1) && (!strcmp(nl_langinfo(CODESET), "UTF-8"));
 
 #else
     return 0;
@@ -75,47 +69,38 @@ zpcre_utf8_enabled(void)
 static int
 bin_pcre_compile(char *nam, char **args, Options ops, UNUSED(int func))
 {
-    int pcre_opts = 0, pcre_errptr, target_len;
-    const char *pcre_error;
+    uint32_t pcre_opts = 0;
+    int target_len;
+    int pcre_error;
+    PCRE2_SIZE pcre_offset;
     char *target;
     
-    if(OPT_ISSET(ops,'a')) pcre_opts |= PCRE_ANCHORED;
-    if(OPT_ISSET(ops,'i')) pcre_opts |= PCRE_CASELESS;
-    if(OPT_ISSET(ops,'m')) pcre_opts |= PCRE_MULTILINE;
-    if(OPT_ISSET(ops,'x')) pcre_opts |= PCRE_EXTENDED;
-    if(OPT_ISSET(ops,'s')) pcre_opts |= PCRE_DOTALL;
+    if (OPT_ISSET(ops, 'a')) pcre_opts |= PCRE2_ANCHORED;
+    if (OPT_ISSET(ops, 'i')) pcre_opts |= PCRE2_CASELESS;
+    if (OPT_ISSET(ops, 'm')) pcre_opts |= PCRE2_MULTILINE;
+    if (OPT_ISSET(ops, 'x')) pcre_opts |= PCRE2_EXTENDED;
+    if (OPT_ISSET(ops, 's')) pcre_opts |= PCRE2_DOTALL;
     
     if (zpcre_utf8_enabled())
-	pcre_opts |= PCRE_UTF8;
-
-#ifdef HAVE_PCRE_STUDY
-    if (pcre_hints)
-#ifdef PCRE_CONFIG_JIT
-	pcre_free_study(pcre_hints);
-#else
-	pcre_free(pcre_hints);
-#endif
-    pcre_hints = NULL;
-#endif
+	pcre_opts |= PCRE2_UTF;
 
     if (pcre_pattern)
-	pcre_free(pcre_pattern);
+	pcre2_code_free(pcre_pattern);
     pcre_pattern = NULL;
 
     target = ztrdup(*args);
     unmetafy(target, &target_len);
 
-    if ((int)strlen(target) != target_len) {
-	zwarnnam(nam, "embedded NULs in PCRE pattern terminate pattern");
-    }
-
-    pcre_pattern = pcre_compile(target, pcre_opts, &pcre_error, &pcre_errptr, NULL);
+    pcre_pattern = pcre2_compile((PCRE2_SPTR) target, (PCRE2_SIZE) target_len,
+	    pcre_opts, &pcre_error, &pcre_offset, NULL);
 
     free(target);
 
     if (pcre_pattern == NULL)
     {
-	zwarnnam(nam, "error in regex: %s", pcre_error);
+	PCRE2_UCHAR buffer[256];
+	pcre2_get_error_message(pcre_error, buffer, sizeof(buffer));
+	zwarnnam(nam, "error in regex: %s", buffer);
 	return 1;
     }
     
@@ -123,67 +108,76 @@ bin_pcre_compile(char *nam, char **args, Options ops, UNUSED(int func))
 }
 
 /**/
-#ifdef HAVE_PCRE_STUDY
-
-/**/
 static int
 bin_pcre_study(char *nam, UNUSED(char **args), UNUSED(Options ops), UNUSED(int func))
 {
-    const char *pcre_error;
-
     if (pcre_pattern == NULL)
     {
 	zwarnnam(nam, "no pattern has been compiled for study");
 	return 1;
     }
-    
-    if (pcre_hints)
-#ifdef PCRE_CONFIG_JIT
-	pcre_free_study(pcre_hints);
-#else
-	pcre_free(pcre_hints);
-#endif
-    pcre_hints = NULL;
 
-    pcre_hints = pcre_study(pcre_pattern, 0, &pcre_error);
-    if (pcre_error != NULL)
-    {
-	zwarnnam(nam, "error while studying regex: %s", pcre_error);
-	return 1;
+    int jit = 0;
+    if (!pcre2_config(PCRE2_CONFIG_JIT, &jit) && jit) {
+	if (pcre2_jit_compile(pcre_pattern, PCRE2_JIT_COMPLETE) < 0) {
+	    zwarnnam(nam, "error while studying regex");
+	    return 1;
+	}
     }
     
     return 0;
 }
 
-/**/
-#else /* !HAVE_PCRE_STUDY */
+static int
+pcre_callout(pcre2_callout_block_8 *block, UNUSED(void *callout_data))
+{
+    Eprog prog;
+    int ret=0;
 
-# define bin_pcre_study bin_notavail
+    if (!block->callout_number &&
+	    ((prog = parse_string((char *) block->callout_string, 0))))
+    {
+	int ef = errflag, lv = lastval;
 
-/**/
-#endif /* !HAVE_PCRE_STUDY */
+	setsparam(".pcre.subject",
+		metafy((char *) block->subject, block->subject_length, META_DUP));
+	setiparam(".pcre.pos", block->current_position + 1);
+	execode(prog, 1, 0, "pcre");
+	ret = lastval | errflag;
+
+	/* Restore any user interrupt error status */
+	errflag = ef | (errflag & ERRFLAG_INT);
+	lastval = lv;
+    }
+
+    return ret;
+}
 
-/**/
 static int
-zpcre_get_substrings(char *arg, int *ovec, int captured_count, char *matchvar,
-		     char *substravar, int want_offset_pair, int matchedinarr,
-		     int want_begin_end)
+zpcre_get_substrings(pcre2_code *pat, char *arg, pcre2_match_data *mdata,
+	int captured_count, char *matchvar, char *substravar, char *namedassoc,
+	int want_offset_pair, int matchedinarr, int want_begin_end)
 {
-    char **captures, *match_all, **matches;
+    PCRE2_SIZE *ovec;
+    char *match_all, **matches;
     char offset_all[50];
     int capture_start = 1;
+    int vec_off;
+    PCRE2_SPTR ntable; /* table of named captures */
+    uint32_t ncount, nsize;
 
     if (matchedinarr) {
-	/* bash-style captures[0] entire-matched string in the array */
+	/* bash-style ovec[0] entire-matched string in the array */
 	capture_start = 0;
     }
 
-    /* captures[0] will be entire matched string, [1] first substring */
-    if (!pcre_get_substring_list(arg, ovec, captured_count, (const char ***)&captures)) {
-	int nelem = arrlen(captures)-1;
+    /* ovec[0] will be entire matched string, [1] first substring */
+    ovec = pcre2_get_ovector_pointer(mdata);
+    if (ovec) {
+	int nelem = captured_count - 1;
 	/* Set to the offsets of the complete match */
 	if (want_offset_pair) {
-	    sprintf(offset_all, "%d %d", ovec[0], ovec[1]);
+	    sprintf(offset_all, "%ld %ld", ovec[0], ovec[1]);
 	    setsparam("ZPCRE_OP", ztrdup(offset_all));
 	}
 	/*
@@ -192,7 +186,7 @@ zpcre_get_substrings(char *arg, int *ovec, int captured_count, char *matchvar,
 	 * ovec is length 2*(1+capture_list_length)
 	 */
 	if (matchvar) {
-	    match_all = metafy(captures[0], ovec[1] - ovec[0], META_DUP);
+	    match_all = metafy(arg + ovec[0], ovec[1] - ovec[0], META_DUP);
 	    setsparam(matchvar, match_all);
 	}
 	/*
@@ -207,21 +201,35 @@ zpcre_get_substrings(char *arg, int *ovec, int captured_count, char *matchvar,
 	 */
 	if (substravar &&
 	    (!want_begin_end || nelem)) {
-	    char **x, **y;
-	    int vec_off, i;
-	    y = &captures[capture_start];
+	    char **x;
+	    int i;
 	    matches = x = (char **) zalloc(sizeof(char *) * (captured_count+1-capture_start));
-	    for (i = capture_start; i < captured_count; i++, y++) {
+	    for (i = capture_start; i < captured_count; i++) {
 		vec_off = 2*i;
-		if (*y)
-		    *x++ = metafy(*y, ovec[vec_off+1]-ovec[vec_off], META_DUP);
-		else
-		    *x++ = NULL;
+		*x++ = metafy(arg + ovec[vec_off], ovec[vec_off+1]-ovec[vec_off], META_DUP);
 	    }
 	    *x = NULL;
 	    setaparam(substravar, matches);
 	}
 
+	if (namedassoc
+		&& !pcre2_pattern_info(pat, PCRE2_INFO_NAMECOUNT, &ncount) && ncount
+		&& !pcre2_pattern_info(pat, PCRE2_INFO_NAMEENTRYSIZE, &nsize)
+		&& !pcre2_pattern_info(pat, PCRE2_INFO_NAMETABLE, &ntable))
+	{
+	    char **hash, **hashptr;
+	    uint32_t nidx;
+	    hashptr = hash = (char **)zshcalloc((ncount+1)*2*sizeof(char *));
+	    for (nidx = 0; nidx < ncount; nidx++) {
+		vec_off = (ntable[nsize * nidx] << 9) + 2 * ntable[nsize * nidx + 1];
+		/* would metafy the key but pcre limits characters in the name */
+		*hashptr++ = ztrdup((char *) ntable + nsize * nidx + 2);
+		*hashptr++ = metafy(arg + ovec[vec_off],
+			ovec[vec_off+1]-ovec[vec_off], META_DUP);
+	    }
+	    sethparam(namedassoc, hash);
+	}
+
 	if (want_begin_end) {
 	    /*
 	     * cond-infix rather than builtin; also not bash; so we set a bunch
@@ -253,7 +261,8 @@ zpcre_get_substrings(char *arg, int *ovec, int captured_count, char *matchvar,
 	    setiparam("MEND", offs + !isset(KSHARRAYS) - 1);
 	    if (nelem) {
 		char **mbegin, **mend, **bptr, **eptr;
-		int i, *ipair;
+		int i;
+		size_t *ipair;
 
 		bptr = mbegin = zalloc(sizeof(char*)*(nelem+1));
 		eptr = mend = zalloc(sizeof(char*)*(nelem+1));
@@ -293,8 +302,6 @@ zpcre_get_substrings(char *arg, int *ovec, int captured_count, char *matchvar,
 		setaparam("mend", mend);
 	    }
 	}
-
-	pcre_free_substring_list((const char **)captures);
     }
 
     return 0;
@@ -320,29 +327,33 @@ getposint(char *instr, char *nam)
 static int
 bin_pcre_match(char *nam, char **args, Options ops, UNUSED(int func))
 {
-    int ret, capcount, *ovec, ovecsize, c;
+    int ret, c;
+    pcre2_match_data *pcre_mdata = NULL;
     char *matched_portion = NULL;
     char *plaintext = NULL;
-    char *receptacle = NULL;
+    char *receptacle;
+    char *named = NULL;
     int return_value = 1;
     /* The subject length and offset start are both int values in pcre_exec */
     int subject_len;
     int offset_start = 0;
     int want_offset_pair = 0;
+    int use_dfa = 0;
 
     if (pcre_pattern == NULL) {
 	zwarnnam(nam, "no pattern has been compiled");
 	return 1;
     }
 
-    matched_portion = "MATCH";
-    receptacle = "match";
-    if(OPT_HASARG(ops,c='a')) {
-	receptacle = OPT_ARG(ops,c);
-    }
-    if(OPT_HASARG(ops,c='v')) {
-	matched_portion = OPT_ARG(ops,c);
+    if (!(use_dfa = OPT_ISSET(ops, 'd'))) {
+	matched_portion = OPT_HASARG(ops, c='v') ? OPT_ARG(ops, c) : "MATCH";
+	named = OPT_HASARG(ops, c='A') ? OPT_ARG(ops, c) : ".pcre.match";
+    } else if (OPT_HASARG(ops, c='v') || OPT_HASARG(ops, c='A')) {
+	zwarnnam(nam, "-d cannot be combined with -%c", c);
+	return 1;
     }
+    receptacle = OPT_HASARG(ops, 'a') ? OPT_ARG(ops, 'a') : "match";
+
     if(OPT_HASARG(ops,c='n')) { /* The offset position to start the search, in bytes. */
 	if ((offset_start = getposint(OPT_ARG(ops,c), nam)) < 0)
 	    return 1;
@@ -350,36 +361,57 @@ bin_pcre_match(char *nam, char **args, Options ops, UNUSED(int func))
     /* For the entire match, 'Return' the offset byte positions instead of the matched string */
     if(OPT_ISSET(ops,'b')) want_offset_pair = 1;
 
-    if ((ret = pcre_fullinfo(pcre_pattern, pcre_hints, PCRE_INFO_CAPTURECOUNT, &capcount)))
-    {
-	zwarnnam(nam, "error %d in fullinfo", ret);
-	return 1;
-    }
-
-    ovecsize = (capcount+1)*3;
-    ovec = zalloc(ovecsize*sizeof(int));
-
     plaintext = ztrdup(*args);
     unmetafy(plaintext, &subject_len);
 
+    pcre2_match_context_8 *mcontext = pcre2_match_context_create(NULL);
+    pcre2_set_callout(mcontext, &pcre_callout, 0);
+
     if (offset_start > 0 && offset_start >= subject_len)
-	ret = PCRE_ERROR_NOMATCH;
-    else
-	ret = pcre_exec(pcre_pattern, pcre_hints, plaintext, subject_len, offset_start, 0, ovec, ovecsize);
+	ret = PCRE2_ERROR_NOMATCH;
+    else if (use_dfa) {
+	PCRE2_SIZE old, wscount = 128, capcount = 128;
+	void *workspace = zhalloc(sizeof(int) * wscount);
+	pcre_mdata = pcre2_match_data_create(capcount, NULL);
+	do {
+	    ret = pcre2_dfa_match(pcre_pattern, (PCRE2_SPTR) plaintext, subject_len,
+		offset_start, 0, pcre_mdata, mcontext, (int *) workspace, wscount);
+	    if (ret == PCRE2_ERROR_DFA_WSSIZE) {
+		old = wscount;
+		wscount += wscount / 2;
+		workspace = hrealloc(workspace, sizeof(int) * old, sizeof(int) * wscount);
+	    } else if (ret == 0) {
+		capcount += capcount / 2;
+		pcre2_match_data_free(pcre_mdata);
+		pcre_mdata = pcre2_match_data_create(capcount, NULL);
+	    } else
+		break;
+	} while(1);
+    } else {
+	pcre_mdata = pcre2_match_data_create_from_pattern(pcre_pattern, NULL);
+	ret = pcre2_match(pcre_pattern, (PCRE2_SPTR) plaintext, subject_len,
+		offset_start, 0, pcre_mdata, mcontext);
+	if (ret > 0)
+	    ret = pcre2_get_ovector_count(pcre_mdata);
+    }
 
     if (ret==0) return_value = 0;
-    else if (ret==PCRE_ERROR_NOMATCH) /* no match */;
+    else if (ret == PCRE2_ERROR_NOMATCH) /* no match */;
     else if (ret>0) {
-	zpcre_get_substrings(plaintext, ovec, ret, matched_portion, receptacle,
-			     want_offset_pair, 0, 0);
+	zpcre_get_substrings(pcre_pattern, plaintext, pcre_mdata, ret,
+		matched_portion, receptacle, named, want_offset_pair, use_dfa, 0);
 	return_value = 0;
     }
     else {
-	zwarnnam(nam, "error in pcre_exec [%d]", ret);
+	PCRE2_UCHAR buffer[256];
+	pcre2_get_error_message(ret, buffer, sizeof(buffer));
+	zwarnnam(nam, "error in pcre matching for %s: %s", *args, buffer);
     }
     
-    if (ovec)
-	zfree(ovec, ovecsize*sizeof(int));
+    if (pcre_mdata)
+	pcre2_match_data_free(pcre_mdata);
+    if (mcontext)
+	pcre2_match_context_free(mcontext);
     zsfree(plaintext);
 
     return return_value;
@@ -389,17 +421,19 @@ bin_pcre_match(char *nam, char **args, Options ops, UNUSED(int func))
 static int
 cond_pcre_match(char **a, int id)
 {
-    pcre *pcre_pat;
-    const char *pcre_err;
+    pcre2_code *pcre_pat = NULL;
+    int pcre_err;
+    PCRE2_SIZE pcre_erroff;
     char *lhstr, *rhre, *lhstr_plain, *rhre_plain, *avar, *svar;
-    int r = 0, pcre_opts = 0, pcre_errptr, capcnt, *ov, ovsize;
+    int r = 0, pcre_opts = 0;
+    pcre2_match_data *pcre_mdata = NULL;
     int lhstr_plain_len, rhre_plain_len;
     int return_value = 0;
 
     if (zpcre_utf8_enabled())
-	pcre_opts |= PCRE_UTF8;
+	pcre_opts |= PCRE2_UTF;
     if (isset(REMATCHPCRE) && !isset(CASEMATCH))
-	pcre_opts |= PCRE_CASELESS;
+	pcre_opts |= PCRE2_CASELESS;
 
     lhstr = cond_str(a,0,0);
     rhre = cond_str(a,1,0);
@@ -407,9 +441,6 @@ cond_pcre_match(char **a, int id)
     rhre_plain = ztrdup(rhre);
     unmetafy(lhstr_plain, &lhstr_plain_len);
     unmetafy(rhre_plain, &rhre_plain_len);
-    pcre_pat = NULL;
-    ov = NULL;
-    ovsize = 0;
 
     if (isset(BASHREMATCH)) {
 	svar = NULL;
@@ -421,27 +452,27 @@ cond_pcre_match(char **a, int id)
 
     switch(id) {
 	 case CPCRE_PLAIN:
-		if ((int)strlen(rhre_plain) != rhre_plain_len) {
-		    zwarn("embedded NULs in PCRE pattern terminate pattern");
-		}
-		pcre_pat = pcre_compile(rhre_plain, pcre_opts, &pcre_err, &pcre_errptr, NULL);
-		if (pcre_pat == NULL) {
-		    zwarn("failed to compile regexp /%s/: %s", rhre, pcre_err);
+		if (!(pcre_pat = pcre2_compile((PCRE2_SPTR) rhre_plain,
+			(PCRE2_SIZE) rhre_plain_len, pcre_opts,
+			&pcre_err, &pcre_erroff, NULL)))
+		{
+		    PCRE2_UCHAR buffer[256];
+		    pcre2_get_error_message(pcre_err, buffer, sizeof(buffer));
+		    zwarn("failed to compile regexp /%s/: %s", rhre, buffer);
 		    break;
 		}
-                pcre_fullinfo(pcre_pat, NULL, PCRE_INFO_CAPTURECOUNT, &capcnt);
-    		ovsize = (capcnt+1)*3;
-		ov = zalloc(ovsize*sizeof(int));
-    		r = pcre_exec(pcre_pat, NULL, lhstr_plain, lhstr_plain_len, 0, 0, ov, ovsize);
-		/* r < 0 => error; r==0 match but not enough size in ov
+		pcre_mdata = pcre2_match_data_create_from_pattern(pcre_pat, NULL);
+		r = pcre2_match(pcre_pat, (PCRE2_SPTR8) lhstr_plain, lhstr_plain_len,
+			0, 0, pcre_mdata, NULL);
+		/* r < 0 => error; r==0 match but not enough size in match data
 		 * r > 0 => (r-1) substrings found; r==1 => no substrings
 		 */
     		if (r==0) {
-		    zwarn("reportable zsh problem: pcre_exec() returned 0");
+		    zwarn("reportable zsh problem: pcre2_match() returned 0");
 		    return_value = 1;
 		    break;
 		}
-	        else if (r==PCRE_ERROR_NOMATCH) {
+		else if (r == PCRE2_ERROR_NOMATCH) {
 		    return_value = 0; /* no match */
 		    break;
 		}
@@ -450,9 +481,9 @@ cond_pcre_match(char **a, int id)
 		    break;
 		}
                 else if (r>0) {
-		    zpcre_get_substrings(lhstr_plain, ov, r, svar, avar, 0,
-					 isset(BASHREMATCH),
-					 !isset(BASHREMATCH));
+		    uint32_t ovec_count = pcre2_get_ovector_count(pcre_mdata);
+		    zpcre_get_substrings(pcre_pat, lhstr_plain, pcre_mdata, ovec_count, svar, avar,
+			    ".pcre.match", 0, isset(BASHREMATCH), !isset(BASHREMATCH));
 		    return_value = 1;
 		    break;
 		}
@@ -463,10 +494,10 @@ cond_pcre_match(char **a, int id)
 	free(lhstr_plain);
     if(rhre_plain)
 	free(rhre_plain);
+    if (pcre_mdata)
+	pcre2_match_data_free(pcre_mdata);
     if (pcre_pat)
-	pcre_free(pcre_pat);
-    if (ov)
-	zfree(ov, ovsize*sizeof(int));
+	pcre2_code_free(pcre_pat);
 
     return return_value;
 }
@@ -488,18 +519,18 @@ static struct conddef cotab[] = {
 
 static struct builtin bintab[] = {
     BUILTIN("pcre_compile", 0, bin_pcre_compile, 1, 1, 0, "aimxs",  NULL),
-    BUILTIN("pcre_match",   0, bin_pcre_match,   1, 1, 0, "a:v:n:b",    NULL),
+    BUILTIN("pcre_match",   0, bin_pcre_match,   1, 1, 0, "A:a:v:n:bd",    NULL),
     BUILTIN("pcre_study",   0, bin_pcre_study,   0, 0, 0, NULL,    NULL)
 };
 
 
 static struct features module_features = {
     bintab, sizeof(bintab)/sizeof(*bintab),
-#if defined(HAVE_PCRE_COMPILE) && defined(HAVE_PCRE_EXEC)
+#if defined(HAVE_PCRE2_COMPILE_8) && defined(HAVE_PCRE2_H)
     cotab, sizeof(cotab)/sizeof(*cotab),
-#else /* !(HAVE_PCRE_COMPILE && HAVE_PCRE_EXEC) */
+#else /* !(HAVE_PCRE2_COMPILE_8 && HAVE_PCRE2_H) */
     NULL, 0,
-#endif /* !(HAVE_PCRE_COMPILE && HAVE_PCRE_EXEC) */
+#endif /* !(HAVE_PCRE2_COMPILE_8 && HAVE_PCRE2_H) */
     NULL, 0,
     NULL, 0,
     0
@@ -546,19 +577,9 @@ cleanup_(Module m)
 int
 finish_(UNUSED(Module m))
 {
-#if defined(HAVE_PCRE_COMPILE) && defined(HAVE_PCRE_EXEC)
-#ifdef HAVE_PCRE_STUDY
-    if (pcre_hints)
-#ifdef PCRE_CONFIG_JIT
-	pcre_free_study(pcre_hints);
-#else
-	pcre_free(pcre_hints);
-#endif
-    pcre_hints = NULL;
-#endif
-
+#if defined(HAVE_PCRE2_COMPILE_8) && defined(HAVE_PCRE2_H)
     if (pcre_pattern)
-	pcre_free(pcre_pattern);
+	pcre2_code_free(pcre_pattern);
     pcre_pattern = NULL;
 #endif
 
diff --git a/Src/Modules/pcre.mdd b/Src/Modules/pcre.mdd
index 6eb3c691b..3e1579117 100644
--- a/Src/Modules/pcre.mdd
+++ b/Src/Modules/pcre.mdd
@@ -1,5 +1,5 @@
 name=zsh/pcre
-link=`if test x$enable_pcre = xyes && (pcre-config --version >/dev/null 2>/dev/null); then echo dynamic; else echo no; fi`
+link=`if test x$enable_pcre = xyes; then echo dynamic; else echo no; fi`
 load=no
 
 autofeatures="b:pcre_compile b:pcre_study b:pcre_match"
diff --git a/Src/Modules/stat.c b/Src/Modules/stat.c
index 0df9b35b7..c9f851974 100644
--- a/Src/Modules/stat.c
+++ b/Src/Modules/stat.c
@@ -406,7 +406,7 @@ bin_stat(char *name, char **args, Options ops, UNUSED(int func))
 	} else {
 	    for (; *arg; arg++) {
 		if (strchr("glLnNorstT", *arg))
-		    ops->ind[STOUC(*arg)] = 1;
+		    ops->ind[(unsigned char) *arg] = 1;
 		else if (*arg == 'A') {
 		    if (arg[1]) {
 			arrnam = arg+1;
diff --git a/Src/Modules/terminfo.c b/Src/Modules/terminfo.c
index 4596b41d2..f9ab64fb3 100644
--- a/Src/Modules/terminfo.c
+++ b/Src/Modules/terminfo.c
@@ -160,7 +160,7 @@ getterminfo(UNUSED(HashTable ht), const char *name)
 	pm->node.flags |= PM_SCALAR;
 	pm->gsu.s = &nullsetscalar_gsu;
     } else if ((tistr = (char *)tigetstr(nameu)) != NULL && tistr != (char *)-1) {
-	pm->u.str = dupstring(tistr);
+	pm->u.str = metafy(tistr, -1, META_HEAPDUP);
 	pm->node.flags |= PM_SCALAR;
 	pm->gsu.s = &nullsetscalar_gsu;
     } else {
@@ -280,7 +280,7 @@ scanterminfo(UNUSED(HashTable ht), ScanFunc func, int flags)
     for (capname = (char **)strnames; *capname; capname++) {
 	if ((tistr = (char *)tigetstr(*capname)) != NULL &&
 	    tistr != (char *)-1) {
-	    pm->u.str = dupstring(tistr);
+	    pm->u.str = metafy(tistr, -1, META_HEAPDUP);
 	    pm->node.nam = dupstring(*capname);
 	    func(&pm->node, flags);
 	}
diff --git a/Src/Modules/watch.c b/Src/Modules/watch.c
index d45c3cf3d..acc499518 100644
--- a/Src/Modules/watch.c
+++ b/Src/Modules/watch.c
@@ -255,8 +255,10 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
     while (*fmt)
 	if (*fmt == '\\') {
 	    if (*++fmt) {
-		if (prnt)
+		if (prnt) {
+		    applytextattributes(TSC_RAW);
 		    putchar(*fmt);
+		}
 		++fmt;
 	    } else if (fini)
 		return fmt;
@@ -266,8 +268,10 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 	else if (*fmt == fini)
 	    return ++fmt;
 	else if (*fmt != '%') {
-	    if (prnt)
+	    if (prnt) {
+		applytextattributes(TSC_RAW);
 		putchar(*fmt);
+	    }
 	    ++fmt;
 	} else {
 	    if (*++fmt == BEGIN3)
@@ -277,12 +281,15 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 	    else
 		switch (*(fm2 = fmt++)) {
 		case 'n':
+		    applytextattributes(TSC_RAW);
 		    printf("%.*s", (int)sizeof(u->ut_name), u->ut_name);
 		    break;
 		case 'a':
+		    applytextattributes(TSC_RAW);
 		    printf("%s", (!inout) ? "logged off" : "logged on");
 		    break;
 		case 'l':
+		    applytextattributes(TSC_RAW);
 		    if (!strncmp(u->ut_line, "tty", 3))
 			printf("%.*s", (int)sizeof(u->ut_line) - 3, u->ut_line + 3);
 		    else
@@ -290,6 +297,7 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 		    break;
 # ifdef WATCH_UTMP_UT_HOST
 		case 'm':
+		    applytextattributes(TSC_RAW);
 		    for (p = u->ut_host, i = sizeof(u->ut_host); i && *p; i--, p++) {
 			if (*p == '.' && !idigit(p[1]))
 			    break;
@@ -297,6 +305,7 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 		    }
 		    break;
 		case 'M':
+		    applytextattributes(TSC_RAW);
 		    printf("%.*s", (int)sizeof(u->ut_host), u->ut_host);
 		    break;
 # endif /* WATCH_UTMP_UT_HOST */
@@ -343,9 +352,11 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 		    len = ztrftime(buf, 40, fm2, tm, 0L);
 		    if (len > 0)
 			metafy(buf, len, META_NOALLOC);
+		    applytextattributes(TSC_RAW);
 		    printf("%s", (*buf == ' ') ? buf + 1 : buf);
 		    break;
 		case '%':
+		    applytextattributes(TSC_RAW);
 		    putchar('%');
 		    break;
 		case 'F':
@@ -354,16 +365,20 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 			atr = match_colour((const char**)&fmt, 1, 0);
 			if (*fmt == '}')
 			    fmt++;
-			if (!(atr & (TXT_ERROR | TXTNOFGCOLOUR))) {
-			    txtunset(TXT_ATTR_FG_COL_MASK);
-			    txtset(atr & TXT_ATTR_FG_ON_MASK);
-			    set_colour_attribute(atr, COL_SEQ_FG, TSC_RAW);
+			if (atr && atr != TXT_ERROR) {
+			    tsetattrs(atr);
+			    break;
 			}
-		    }
-		    break;
+		    } /* fall-through */
 		case 'f':
-		    txtunset(TXT_ATTR_FG_ON_MASK);
-		    set_colour_attribute(TXTNOFGCOLOUR, COL_SEQ_FG, TSC_RAW);
+		    tunsetattrs(TXTFGCOLOUR);
+		    break;
+		case 'H':
+		    if (*fmt == '{') {
+			fmt = parsehighlight(fmt + 1, '}', &atr);
+			if (atr && atr != TXT_ERROR)
+			    treplaceattrs(atr);
+		    }
 		    break;
 		case 'K':
 		    if (*fmt == '{') {
@@ -371,49 +386,43 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 			atr = match_colour((const char**)&fmt, 0, 0);
 			if (*fmt == '}')
 			    fmt++;
-			if (!(atr & (TXT_ERROR | TXTNOBGCOLOUR))) {
-			    txtunset(TXT_ATTR_BG_COL_MASK);
-			    txtset(atr & TXT_ATTR_BG_ON_MASK);
-			    set_colour_attribute(atr, COL_SEQ_BG, TSC_RAW);
+			if (atr && atr != TXT_ERROR) {
+			    tsetattrs(atr);
+			    break;
 			}
-		    }
-		    break;
+		    } /* fall-through */
 		case 'k':
-		    txtunset(TXT_ATTR_BG_ON_MASK);
-		    set_colour_attribute(TXTNOBGCOLOUR, COL_SEQ_BG, TSC_RAW);
+		    tunsetattrs(TXTBGCOLOUR);
 		    break;
 		case 'S':
-		    txtset(TXTSTANDOUT);
-		    tsetcap(TCSTANDOUTBEG, TSC_RAW);
+		    tsetattrs(TXTSTANDOUT);
 		    break;
 		case 's':
-		    txtunset(TXTSTANDOUT);
-		    tsetcap(TCSTANDOUTEND, TSC_RAW|TSC_DIRTY);
+		    tunsetattrs(TXTSTANDOUT);
 		    break;
 		case 'B':
-		    txtset(TXTBOLDFACE);
-		    tsetcap(TCBOLDFACEBEG, TSC_RAW|TSC_DIRTY);
+		    tsetattrs(TXTBOLDFACE);
 		    break;
 		case 'b':
-		    txtunset(TXTBOLDFACE);
-		    tsetcap(TCALLATTRSOFF, TSC_RAW|TSC_DIRTY);
+		    tunsetattrs(TXTBOLDFACE);
 		    break;
 		case 'U':
-		    txtset(TXTUNDERLINE);
-		    tsetcap(TCUNDERLINEBEG, TSC_RAW);
+		    tsetattrs(TXTUNDERLINE);
 		    break;
 		case 'u':
-		    txtunset(TXTUNDERLINE);
-		    tsetcap(TCUNDERLINEEND, TSC_RAW|TSC_DIRTY);
+		    tunsetattrs(TXTUNDERLINE);
 		    break;
 		default:
+		    applytextattributes(TSC_RAW);
 		    putchar('%');
 		    putchar(*fm2);
 		    break;
 		}
 	}
-    if (prnt)
+    if (prnt) {
+	applytextattributes(TSC_RAW);
 	putchar('\n');
+    }
 
     return fmt;
 }
@@ -421,20 +430,23 @@ watchlog2(int inout, WATCH_STRUCT_UTMP *u, char *fmt, int prnt, int fini)
 /* See if the watch entry matches */
 
 static int
-watchlog_match(char *teststr, char *actual, int len)
+watchlog_match(char *teststr, char *actual, size_t buflen)
 {
     int ret = 0;
     Patprog pprog;
     char *str = dupstring(teststr);
+    size_t len = strnlen(actual, buflen);
+    char *user = metafy(actual, len,
+	    len == buflen ? META_HEAPDUP : META_USEHEAP);
 
     tokenize(str);
 
     if ((pprog = patcompile(str, PAT_STATIC, 0))) {
 	queue_signals();
-	if (pattry(pprog, actual))
+	if (pattry(pprog, user))
 	    ret = 1;
 	unqueue_signals();
-    } else if (!strncmp(actual, teststr, len))
+    } else if (!strcmp(user, teststr))
 	ret = 1;
     return ret;
 }
@@ -454,10 +466,17 @@ watchlog(int inout, WATCH_STRUCT_UTMP *u, char **w, char *fmt)
 	(void)watchlog2(inout, u, fmt, 1, 0);
 	return;
     }
-    if (*w && !strcmp(*w, "notme") &&
-	strncmp(u->ut_name, get_username(), sizeof(u->ut_name))) {
-	(void)watchlog2(inout, u, fmt, 1, 0);
-	return;
+    if (*w && !strcmp(*w, "notme")) {
+	int len = strnlen(u->ut_name, sizeof(u->ut_name));
+	char *username = metafy(u->ut_name, len,
+				(len == sizeof(u->ut_name) ?
+				 META_HEAPDUP /* allow for nul terminator */ :
+				 META_USEHEAP));
+	if (strcmp(username, get_username())) {
+	    (void)watchlog2(inout, u, fmt, 1, 0);
+	    return;
+	}
+	w++;
     }
     for (; *w; w++) {
 	bad = 0;
@@ -486,7 +505,7 @@ watchlog(int inout, WATCH_STRUCT_UTMP *u, char **w, char *fmt)
 		for (vv = ++v; *vv && *vv != '%'; vv++);
 		sav = *vv;
 		*vv = '\0';
-		if (!watchlog_match(v, u->ut_host, strlen(v)))
+		if (!watchlog_match(v, u->ut_host, sizeof(u->ut_host)))
 		    bad = 1;
 		*vv = sav;
 		v = vv;
@@ -565,7 +584,7 @@ readwtab(WATCH_STRUCT_UTMP **head, int initial_sz)
 
     if (sz)
 	qsort((void *) *head, sz, sizeof(WATCH_STRUCT_UTMP),
-	           (int (*) _((const void *, const void *)))ucmp);
+	           (int (*) (const void *, const void *))ucmp);
     return sz;
 }
 
diff --git a/Src/Modules/zftp.c b/Src/Modules/zftp.c
index e8e239e76..0c26828fd 100644
--- a/Src/Modules/zftp.c
+++ b/Src/Modules/zftp.c
@@ -127,7 +127,7 @@ typedef int (*readwrite_t)(int, char *, off_t, int);
 
 struct zftpcmd {
     const char *nam;
-    int (*fun) _((char *, char **, int));
+    int (*fun) (char *, char **, int);
     int min, max, flags;
 };
 
@@ -944,9 +944,9 @@ zfopendata(char *name, union tcp_sockaddr *zdsockp, int *is_passivep)
 		return 1;
 	    }
 	    for (i = 0; i < 4; i++)
-		iaddr[i] = STOUC(nums[i]);
-	    iport[0] = STOUC(nums[4]);
-	    iport[1] = STOUC(nums[5]);
+		iaddr[i] = (unsigned char) nums[i];
+	    iport[0] = (unsigned char) nums[4];
+	    iport[1] = (unsigned char) nums[5];
 
 	    memcpy(&zdsockp->in.sin_addr, iaddr, sizeof(iaddr));
 	    memcpy(&zdsockp->in.sin_port, iport, sizeof(iport));
@@ -2438,7 +2438,7 @@ zftp_type(char *name, char **args, int flags)
 	fflush(stdout);
 	return 0;
     } else {
-	nt = toupper(STOUC(*str));
+	nt = toupper((unsigned char) *str);
 	/*
 	 * RFC959 specifies other types, but these are the only
 	 * ones we know what to do with.
@@ -2472,7 +2472,7 @@ zftp_mode(char *name, char **args, UNUSED(int flags))
 	fflush(stdout);
 	return 0;
     }
-    nt = str[0] = toupper(STOUC(*str));
+    nt = str[0] = toupper((unsigned char) *str);
     if (str[1] || (nt != 'S' && nt != 'B')) {
 	zwarnnam(name, "transfer mode %s not recognised", str);
 	return 1;
@@ -3075,7 +3075,7 @@ bin_zftp(char *name, char **args, UNUSED(Options ops), UNUSED(int func))
     if ((prefs = getsparam_u("ZFTP_PREFS"))) {
 	zfprefs = 0;
 	for (ptr = prefs; *ptr; ptr++) {
-	    switch (toupper(STOUC(*ptr))) {
+	    switch (toupper((unsigned char) *ptr)) {
 	    case 'S':
 		/* sendport */
 		zfprefs |= ZFPF_SNDP;
@@ -3172,7 +3172,7 @@ static struct features module_features = {
 int
 setup_(UNUSED(Module m))
 {
-    return (require_module("zsh/net/tcp", NULL, 0) == 1);
+    return 0;
 }
 
 /**/
diff --git a/Src/Modules/zprof.c b/Src/Modules/zprof.c
index 56cdab888..171a15b90 100644
--- a/Src/Modules/zprof.c
+++ b/Src/Modules/zprof.c
@@ -163,9 +163,9 @@ bin_zprof(UNUSED(char *nam), UNUSED(char **args), Options ops, UNUSED(int func))
 	*ap = NULL;
 
 	qsort(fs, ncalls, sizeof(f),
-	      (int (*) _((const void *, const void *))) cmpsfuncs);
+	      (int (*) (const void *, const void *)) cmpsfuncs);
 	qsort(as, narcs, sizeof(a),
-	      (int (*) _((const void *, const void *))) cmpparcs);
+	      (int (*) (const void *, const void *)) cmpparcs);
 
 	printf("num  calls                time                       self            name\n-----------------------------------------------------------------------------------\n");
 	for (fp = fs, i = 1; *fp; fp++, i++) {
@@ -179,7 +179,7 @@ bin_zprof(UNUSED(char *nam), UNUSED(char **args), Options ops, UNUSED(int func))
 		   (*fp)->name);
 	}
 	qsort(fs, ncalls, sizeof(f),
-	      (int (*) _((const void *, const void *))) cmptfuncs);
+	      (int (*) (const void *, const void *)) cmptfuncs);
 
 	for (fp = fs; *fp; fp++) {
 	    printf("\n-----------------------------------------------------------------------------------\n\n");
diff --git a/Src/Modules/zpty.c b/Src/Modules/zpty.c
index dfd2a2a7a..c2656698c 100644
--- a/Src/Modules/zpty.c
+++ b/Src/Modules/zpty.c
@@ -638,7 +638,7 @@ ptyread(char *nam, Ptycmd cmd, char **args, int noblock, int mustmatch)
 		readchar = cmd->read;
 		cmd->read = -1;
 	    } else
-		readchar = STOUC(buf[used]);
+		readchar = (unsigned char) buf[used];
 	    if (imeta(readchar)) {
 		buf[used++] = Meta;
 		buf[used++] = (char) (readchar ^ 32);
diff --git a/Src/Modules/zutil.c b/Src/Modules/zutil.c
index 2f17c03f1..5eccea7a9 100644
--- a/Src/Modules/zutil.c
+++ b/Src/Modules/zutil.c
@@ -462,6 +462,28 @@ lookupstyle(char *ctxt, char *style)
 }
 
 static int
+testforstyle(char *ctxt, char *style)
+{
+    Style s;
+    Stypat p;
+    int found = 0;
+
+    s = (Style)zstyletab->getnode2(zstyletab, style);
+    if (s) {
+	MatchData match;
+	savematch(&match);
+	for (p = s->pats; p; p = p->next)
+	    if (pattry(p->prog, ctxt)) {
+		found = 1;
+		break;
+	    }
+	restorematch(&match);
+    }
+
+    return !found;	/* 0 == success */
+}
+
+static int
 bin_zstyle(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
 {
     int min, max, n, add = 0, list = ZSLIST_NONE, eval = 0;
@@ -570,6 +592,7 @@ bin_zstyle(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
     case 't': min = 2; max = -1; break;
     case 'T': min = 2; max = -1; break;
     case 'm': min = 3; max =  3; break;
+    case 'q': min = 2; max =  2; break;
     case 'g': min = 1; max =  3; break;
     default:
 	zwarnnam(nam, "invalid option: %s", args[0]);
@@ -723,6 +746,15 @@ bin_zstyle(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
 	    return 1;
 	}
 	break;
+    case 'q':
+	{
+	    int success;
+	    queue_signals();	/* Protect PAT_STATIC */
+	    success = testforstyle(args[1], args[2]);
+	    unqueue_signals();
+	    return success;
+	}
+	break;
     case 'g':
 	{
 	    int ret = 1;
@@ -795,11 +827,11 @@ static char *zformat_substring(char* instr, char **specs, char **outp,
 
 	    if (idigit(*s)) {
 		for (min = 0; idigit(*s); s++)
-		    min = (min * 10) + (int) STOUC(*s) - '0';
+		    min = (min * 10) + (int) (unsigned char) *s - '0';
 	    }
 
 	    /* Ternary expressions */
-	    testit = (STOUC(*s) == '(');
+	    testit = ((unsigned char) *s == '(');
 	    if (testit && s[1] == '-')
 	    {
 		/* Allow %(-1... etc. */
@@ -808,25 +840,25 @@ static char *zformat_substring(char* instr, char **specs, char **outp,
 	    }
 	    if ((*s == '.' || testit) && idigit(s[1])) {
 		for (max = 0, s++; idigit(*s); s++)
-		    max = (max * 10) + (int) STOUC(*s) - '0';
+		    max = (max * 10) + (int) (unsigned char) *s - '0';
 	    } else if (*s == '.' || testit)
 		s++;
 
-	    if (testit && STOUC(*s)) {
+	    if (testit && (unsigned char) *s) {
 		int actval, testval, endcharl;
 
 		/* Only one number is useful for ternary expressions. */
 		testval = (min >= 0) ? min : (max >= 0) ? max : 0;
 
-		if (specs[STOUC(*s)] && *specs[STOUC(*s)]) {
+		if (specs[(unsigned char) *s] && *specs[(unsigned char) *s]) {
 		    if (presence) {
 			if (testval)
 #ifdef MULTIBYTE_SUPPORT
 			    if (isset(MULTIBYTE))
-				actval = MB_METASTRWIDTH(specs[STOUC(*s)]);
+				actval = MB_METASTRWIDTH(specs[(unsigned char) *s]);
 			    else
 #endif
-				actval = strlen(specs[STOUC(*s)]);
+				actval = strlen(specs[(unsigned char) *s]);
 		        else
 			    actval = 1;
 			actval = right ? (testval < actval) : (testval >= actval);
@@ -834,7 +866,7 @@ static char *zformat_substring(char* instr, char **specs, char **outp,
 			if (right) /* put the sign back */
 			    testval *= -1;
 			/* zero means values are equal, i.e. true */
-			actval = (int)mathevali(specs[STOUC(*s)]) - testval;
+			actval = (int) mathevali(specs[(unsigned char) *s]) - testval;
 		    }
 		} else
 		    actval = presence ? !right : testval;
@@ -855,7 +887,7 @@ static char *zformat_substring(char* instr, char **specs, char **outp,
 		    return NULL;
 	    } else if (skip) {
 		continue;
-	    } else if ((spec = specs[STOUC(*s)])) {
+	    } else if ((spec = specs[(unsigned char) *s])) {
 		int len;
 
 		if ((len = strlen(spec)) > max && max >= 0)
@@ -950,7 +982,7 @@ bin_zformat(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
 		    zwarnnam(nam, "invalid argument: %s", *ap);
 		    return 1;
 		}
-		specs[STOUC(ap[0][0])] = ap[0] + 2;
+		specs[(unsigned char) ap[0][0]] = ap[0] + 2;
 	    }
 	    out = (char *) zhalloc(olen = 128);
 
@@ -965,7 +997,7 @@ bin_zformat(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
     case 'a':
 	{
 	    char **ap, *cp;
-	    int nbc = 0, colon = 0, pre = 0, suf = 0;
+	    int nbc = 0, pre = 0, suf = 0;
 #ifdef MULTIBYTE_SUPPORT
 	    int prechars = 0;
 #endif /* MULTIBYTE_SUPPORT */
@@ -980,7 +1012,6 @@ bin_zformat(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
 		    int dchars = 0;
 #endif /* MULTIBYTE_SUPPORT */
 
-		    colon++;
 		    if ((d = cp - *ap - nbc) > pre)
 			pre = d;
 #ifdef MULTIBYTE_SUPPORT
@@ -1378,11 +1409,11 @@ rmatch(RParseResult *sm, char *subj, char *var1, char *var2, int comp)
 					     "zregexparse-guard"), !lastval))) {
 		LinkNode aln;
 		char **mend;
-		int len;
+		int len = 0;
 
 		queue_signals();
-		mend = getaparam("mend");
-		len = atoi(mend[0]);
+		if ((mend = getaparam("mend")))
+		    len = atoi(mend[0]);
 		unqueue_signals();
 
 		for (i = len; i; i--)
@@ -1864,7 +1895,7 @@ bin_zparseopts(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
 	d->vals = d->last = NULL;
 	opt_descs = d;
 	if (!o[1])
-	    sopts[STOUC(*o)] = d;
+	    sopts[(unsigned char) *o] = d;
 	if ((flags & ZOF_MAP) && !map_opt_desc(d)) {
 	    zwarnnam(nam, "cyclic option mapping: %s", args[-1]);
 	    return 1;
@@ -1888,7 +1919,7 @@ bin_zparseopts(char *nam, char **args, UNUSED(Options ops), UNUSED(int func))
 	}
 	if (!(d = lookup_opt(o + 1))) {
 	    while (*++o) {
-		if (!(d = sopts[STOUC(*o)])) {
+		if (!(d = sopts[(unsigned char) *o])) {
 		    if (fail) {
 			if (*o != '-')
 			    zwarnnam(nam, "bad option: -%c", *o);
diff --git a/Src/Zle/compcore.c b/Src/Zle/compcore.c
index 4ac5d089f..09282d42d 100644
--- a/Src/Zle/compcore.c
+++ b/Src/Zle/compcore.c
@@ -1230,14 +1230,14 @@ check_param(char *s, int set, int test)
 	else if (idigit(*e))
 	    while (idigit(*e))
 		e++;
-	else if ((ie = itype_end(e, IIDENT, 0)) != e) {
+	else if ((ie = itype_end(e, INAMESPC, 0)) != e) {
 	    do {
 		e = ie;
 		if (comppatmatch && *comppatmatch &&
 		    (*e == Star || *e == Quest))
 		    ie = e + 1;
 		else
-		    ie = itype_end(e, IIDENT, 0);
+		    ie = itype_end(e, INAMESPC, 0);
 	    } while (ie != e);
 	}
 
@@ -2249,8 +2249,9 @@ addmatches(Cadata dat, char **argv)
 	    llpl = strlen(lpre);
 	    llsl = strlen(lsuf);
 
-	    if (llpl + (int)strlen(compqiprefix) + (int)strlen(lipre) != origlpre
-	     || llsl + (int)strlen(compqisuffix) + (int)strlen(lisuf) != origlsuf)
+	    /* This used to reference compqiprefix and compqisuffix, why? */
+	    if (llpl + (int)strlen(qipre) + (int)strlen(lipre) != origlpre
+	     || llsl + (int)strlen(qisuf) + (int)strlen(lisuf) != origlsuf)
 		lenchanged = 1;
 
 	    /* Test if there is an existing -P prefix. */
@@ -2898,9 +2899,9 @@ add_match_data(int alt, char *str, char *orig, Cline line,
 		*t++ = '$';
 		*t++ = '\'';
 		*t++ = '\\';
-		*t++ = '0' + ((STOUC(curchar) >> 6) & 7);
-		*t++ = '0' + ((STOUC(curchar) >> 3) & 7);
-		*t++ = '0' + (STOUC(curchar) & 7);
+		*t++ = '0' + (((unsigned char) curchar >> 6) & 7);
+		*t++ = '0' + (((unsigned char) curchar >> 3) & 7);
+		*t++ = '0' + ((unsigned char) curchar & 7);
 		*t++ = '\'';
 	    } while (cnt == MB_INCOMPLETE && fs < fe);
 	    /* Scanning restarts from the spot after the char we skipped. */
@@ -3252,7 +3253,7 @@ makearray(LinkList l, int type, int flags, int *np, int *nlp, int *llp)
 	    /* Now sort the array (it contains matches). */
 	    matchorder = flags;
 	    qsort((void *) rp, n, sizeof(Cmatch),
-		  (int (*) _((const void *, const void *)))matchcmp);
+		  (int (*) (const void *, const void *))matchcmp);
 
 	    /* since the matches are sorted and the default is to remove
 	     * all duplicates, -1 (remove only consecutive dupes) is a no-op,
@@ -3294,7 +3295,7 @@ makearray(LinkList l, int type, int flags, int *np, int *nlp, int *llp)
 		sp = (Cmatch *) zhalloc((n + 1) * sizeof(Cmatch));
 		memcpy(sp, rp, (n + 1) * sizeof(Cmatch));
 		qsort((void *) sp, n, sizeof(Cmatch),
-		      (int (*) _((const void *, const void *)))matchcmp);
+		      (int (*) (const void *, const void *))matchcmp);
 		for (asp = sp + 1; *asp; asp++) {
 		    Cmatch *ap = asp - 1, *bp = asp;
 		    if (matcheq(*ap, *bp)) {
diff --git a/Src/Zle/complete.c b/Src/Zle/complete.c
index 67a60963e..342611f1f 100644
--- a/Src/Zle/complete.c
+++ b/Src/Zle/complete.c
@@ -518,7 +518,7 @@ parse_class(Cpattern p, char *iptr)
 	    ch = range_type((char *)iptr, nptr-iptr);
 	    iptr = nptr + 2;
 	    if (ch != PP_UNKWN)
-		*optr++ = STOUC(Meta) + ch;
+		*optr++ = (unsigned char) Meta + ch;
 	} else {
 	    /* characters stay metafied */
 	    char *ptr1 = iptr;
@@ -829,7 +829,9 @@ bin_compadd(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))
 
  ca_args:
 
-    if (mstr && (match = parse_cmatcher(name, mstr)) == pcm_err) {
+    if (mstr && (dat.aflags & CAF_MATCH) &&
+	    (match = parse_cmatcher(name, mstr)) == pcm_err)
+    {
 	zsfree(mstr);
 	zfree(dat.dpar, dparsize);
 	return 1;
diff --git a/Src/Zle/complist.c b/Src/Zle/complist.c
index 0dc64db6a..5619160a9 100644
--- a/Src/Zle/complist.c
+++ b/Src/Zle/complist.c
@@ -291,12 +291,12 @@ getcolval(char *s, int multi)
 	    case '?': *p = '\177'; break;
 	    default:
 		if (*s >= '0' && *s <= '7') {
-		    int i = STOUC(*s);
+		    int i = (unsigned char) *s;
 
 		    if (*++s >= '0' && *s <= '7') {
-			i = (i * 8) + STOUC(*s);
+			i = (i * 8) + (unsigned char) *s;
 			if (*++s >= '0' && *s <= '7')
-			    i = (i * 8) + STOUC(*s);
+			    i = (i * 8) + (unsigned char) *s;
 		    }
 		    *p = (char) i;
 		} else
@@ -305,7 +305,7 @@ getcolval(char *s, int multi)
 	} else if (*s == '^') {
 	    if ((s[1] >= '@' && s[1] <= '_') ||
 		(s[1] >= 'a' && s[1] <= 'z'))
-		*p = (char) (STOUC(*s) & ~0x60);
+		*p = (char) ((unsigned char) *s & ~0x60);
 	    else if (s[1] == '?')
 		*p = '\177';
 	    else {
@@ -794,7 +794,7 @@ clnicezputs(int do_colors, char *s, int ml)
 	 */
 	for (t = sptr; *t; t++) {
 	    /* Input is metafied... */
-	    int nc = (*t == Meta) ? STOUC(*++t ^ 32) : STOUC(*t);
+	    int nc = (*t == Meta) ? (unsigned char) (*++t ^ 32) : (unsigned char) *t;
 	    /* Is the screen full? */
 	    if (ml == mlend - 1 && col == zterm_columns - 1) {
 		mlprinted = ml - oml;
@@ -852,7 +852,7 @@ clnicezputs(int do_colors, char *s, int ml)
 	    cc = *s++ ^ 32;
 
 	for (t = nicechar(cc); *t; t++) {
-	    int nc = (*t == Meta) ? STOUC(*++t ^ 32) : STOUC(*t);
+	    int nc = (*t == Meta) ? (unsigned char) (*++t ^ 32) : (unsigned char) *t;
 	    if (ml == mlend - 1 && col == zterm_columns - 1) {
 		mlprinted = ml - oml;
 		return 0;
@@ -1072,7 +1072,7 @@ static int
 compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 {
     char *p, nc[2*DIGBUFSIZE + 12], nbuf[2*DIGBUFSIZE + 12];
-    int l = 0, cc = 0, b = 0, s = 0, u = 0, m, ask, beg, stat;
+    int l = 0, cc = 0, m, ask, beg, stat;
 
     if ((stat = !fmt)) {
 	if (mlbeg >= 0) {
@@ -1118,48 +1118,46 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 		m = 0;
 		switch (cchar) {
 		case ZWC('%'):
-		    if (dopr == 1)
+		    if (dopr == 1) {
+			applytextattributes(0);
 			putc('%', shout);
+		    }
 		    cc++;
 		    break;
 		case ZWC('n'):
 		    if (!stat) {
 			sprintf(nc, "%d", n);
-			if (dopr == 1)
+			if (dopr == 1) {
+			    applytextattributes(0);
 			    fputs(nc, shout);
+			}
 			/* everything here is ASCII... */
 			cc += strlen(nc);
 		    }
 		    break;
 		case ZWC('B'):
-		    b = 1;
 		    if (dopr)
-			tcout(TCBOLDFACEBEG);
+			tsetattrs(TXTBOLDFACE);
 		    break;
 		case ZWC('b'):
-		    b = 0; m = 1;
 		    if (dopr)
-			tcout(TCALLATTRSOFF);
+			tunsetattrs(TXTBOLDFACE);
 		    break;
 		case ZWC('S'):
-		    s = 1;
 		    if (dopr)
-			tcout(TCSTANDOUTBEG);
+			tsetattrs(TXTSTANDOUT);
 		    break;
 		case ZWC('s'):
-		    s = 0; m = 1;
 		    if (dopr)
-			tcout(TCSTANDOUTEND);
+			tunsetattrs(TXTSTANDOUT);
 		    break;
 		case ZWC('U'):
-		    u = 1;
 		    if (dopr)
-			tcout(TCUNDERLINEBEG);
+			tsetattrs(TXTUNDERLINE);
 		    break;
 		case ZWC('u'):
-		    u = 0; m = 1;
 		    if (dopr)
-			tcout(TCUNDERLINEEND);
+			tunsetattrs(TXTUNDERLINE);
 		    break;
 		case ZWC('F'):
 		case ZWC('K'):
@@ -1173,20 +1171,28 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 		    } else
 			atr = match_colour(NULL, is_fg, arg);
 		    if (atr != TXT_ERROR && dopr)
-			set_colour_attribute(atr, is_fg ? COL_SEQ_FG :
-					     COL_SEQ_BG, 0);
+			tsetattrs(atr);
 		    break;
 		case ZWC('f'):
 		    if (dopr)
-			set_colour_attribute(TXTNOFGCOLOUR, COL_SEQ_FG, 0);
+			tunsetattrs(TXTFGCOLOUR);
 		    break;
 		case ZWC('k'):
 		    if (dopr)
-			set_colour_attribute(TXTNOBGCOLOUR, COL_SEQ_BG, 0);
+			tunsetattrs(TXTBGCOLOUR);
+		    break;
+		case ZWC('H'):
+		    if (*p == '{') {
+			p = parsehighlight(p + 1, '}', &atr);
+			if (atr != TXT_ERROR && dopr)
+			    treplaceattrs(atr);
+		    }
 		    break;
 		case ZWC('{'):
 		    if (arg)
 			cc += arg;
+		    if (dopr)
+			applytextattributes(0);
 		    for (; *p && (*p != '%' || p[1] != '}'); p++)
 			if (dopr)
 			    putc(*p == Meta ? *++p ^ 32 : *p, shout);
@@ -1197,7 +1203,7 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 		    if (stat) {
 			sprintf(nc, "%d/%d", (n ? mlastm : mselect),
 				listdat.nlist);
-			m = 2;
+			m = 1;
 		    }
 		    break;
 		case ZWC('M'):
@@ -1205,20 +1211,20 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 			sprintf(nbuf, "%d/%d", (n ? mlastm : mselect),
 				listdat.nlist);
 			sprintf(nc, "%-9s", nbuf);
-			m = 2;
+			m = 1;
 		    }
 		    break;
 		case ZWC('l'):
 		    if (stat) {
 			sprintf(nc, "%d/%d", ml + 1, listdat.nlines);
-			m = 2;
+			m = 1;
 		    }
 		    break;
 		case ZWC('L'):
 		    if (stat) {
 			sprintf(nbuf, "%d/%d", ml + 1, listdat.nlines);
 			sprintf(nc, "%-9s", nbuf);
-			m = 2;
+			m = 1;
 		    }
 		    break;
 		case ZWC('p'):
@@ -1230,7 +1236,7 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 				    ((ml + 1) * 100) / listdat.nlines);
 			else
 			    strcpy(nc, "Top");
-			m = 2;
+			m = 1;
 		    }
 		    break;
 		case ZWC('P'):
@@ -1242,25 +1248,19 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 				    ((ml + 1) * 100) / listdat.nlines);
 			else
 			    strcpy(nc, "Top   ");
-			m = 2;
+			m = 1;
 		    }
 		    break;
 		}
-		if (m == 2 && dopr == 1) {
+		if (m && dopr) {
 		    /* nc only contains ASCII text */
 		    int l = strlen(nc);
 
 		    if (l + cc > zterm_columns - 2)
 			nc[l -= l + cc - (zterm_columns - 2)] = '\0';
+		    applytextattributes(0);
 		    fputs(nc, shout);
 		    cc += l;
-		} else if (dopr && m == 1) {
-		    if (b)
-			tcout(TCBOLDFACEBEG);
-		    if (s)
-			tcout(TCSTANDOUTBEG);
-		    if (u)
-			tcout(TCUNDERLINEBEG);
 		}
 	    } else
 		break;
@@ -1276,6 +1276,7 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 		cc = 0;
 	    }
 	    if (dopr == 1) {
+		applytextattributes(0);
 		if (ml == mlend - 1 && (cc % zterm_columns) ==
 		    zterm_columns - 1) {
 		    dopr = 0;
@@ -1311,6 +1312,8 @@ compprintfmt(char *fmt, int n, int dopr, int doesc, int ml, int *stop)
 	}
     }
     if (dopr) {
+	treplaceattrs(0);
+	applytextattributes(0);
         if (!(cc % zterm_columns))
             fputs(" \010", shout);
         cleareol();
diff --git a/Src/Zle/compmatch.c b/Src/Zle/compmatch.c
index 56e5509a4..ddcecd589 100644
--- a/Src/Zle/compmatch.c
+++ b/Src/Zle/compmatch.c
@@ -2045,12 +2045,12 @@ join_strs(int la, char *sa, int lb, char *sb)
 				zlelineasstring(line, mp->llen, 0, &convlen,
 						NULL, 0);
 			    if (rr <= convlen) {
-				char *or = rs;
+				ptrdiff_t diff = rp - rs;
 				int alloclen = (convlen > 20) ? convlen : 20;
 
 				rs = realloc(rs, (rl += alloclen));
 				rr += alloclen;
-				rp += rs - or;
+				rp = rs + diff;
 			    }
 			    memcpy(rp, convstr, convlen);
 			    rp += convlen;
@@ -2073,11 +2073,11 @@ join_strs(int la, char *sa, int lb, char *sb)
 	} else {
 	    /* Same character, just take it. */
 	    if (rr <= 1 /* HERE charlen */) {
-		char *or = rs;
+		ptrdiff_t diff = rp - rs;
 
 		rs = realloc(rs, (rl += 20));
 		rr += 20;
-		rp += rs - or;
+		rp = rs + diff;
 	    }
 	    /* HERE: multibyte char */
 	    *rp++ = *sa;
diff --git a/Src/Zle/compresult.c b/Src/Zle/compresult.c
index 57789c0f3..cd8c7dd64 100644
--- a/Src/Zle/compresult.c
+++ b/Src/Zle/compresult.c
@@ -897,7 +897,7 @@ void
 do_allmatches(UNUSED(int end))
 {
     int first = 1, nm = nmatches - 1, omc = menucmp, oma = menuacc, e;
-    Cmatch *mc;
+    Cmatch *mc = 0;
     struct menuinfo mi;
     char *p = (brbeg ? ztrdup(lastbrbeg->str) : NULL);
 
@@ -915,10 +915,10 @@ do_allmatches(UNUSED(int end))
 #endif
     }
 
+    if (minfo.group)
+	mc = (minfo.group)->matches;
 
-    mc = (minfo.group)->matches;
-
-    while (1) {
+    while (mc) {
 	if (!((*mc)->flags & CMF_ALL)) {
 	    if (!first)
 		accept_last();
@@ -1731,8 +1731,6 @@ calclist(int showall)
                                  width < zterm_columns && nth < g->dcount;
                                  nth++, tcol++) {
 
-                                m = *p;
-
                                 if (tcol == tcols) {
                                     tcol = 0;
                                     tlines++;
@@ -1994,7 +1992,6 @@ printlist(int over, CLPrintFunc printm, int showall)
 		     (listdat.onlyexpl & ((*e)->always > 0 ? 2 : 1)))) {
 		    if (pnl) {
 			putc('\n', shout);
-			pnl = 0;
 			ml++;
 			if (cl >= 0 && --cl <= 1) {
 			    cl = -1;
@@ -2087,7 +2084,6 @@ printlist(int over, CLPrintFunc printm, int showall)
                         (showall || !(m->flags & (CMF_HIDE|CMF_NOLIST)))) {
 			if (pnl) {
 			    putc('\n', shout);
-			    pnl = 0;
 			    ml++;
 			    if (cl >= 0 && --cl <= 1) {
 				cl = -1;
diff --git a/Src/Zle/computil.c b/Src/Zle/computil.c
index 77ccdebf7..360667884 100644
--- a/Src/Zle/computil.c
+++ b/Src/Zle/computil.c
@@ -911,7 +911,7 @@ struct cadef {
     Caarg rest;			/* the rest-argument */
     char **defs;		/* the original strings */
     int ndefs;			/* number of ... */
-    int lastt;			/* last time this was used */
+    time_t lastt;		/* last time this was used */
     Caopt *single;		/* array of single-letter options */
     char *match;		/* -M spec to use */
     int argsactive;		/* if normal arguments are still allowed */
@@ -2935,7 +2935,7 @@ struct cvdef {
     Cvval vals;			/* value definitions */
     char **defs;		/* original strings */
     int ndefs;			/* number of ... */
-    int lastt;			/* last time used */
+    time_t lastt;		/* last time used */
     int words;                  /* if to look at other words */
 };
 
diff --git a/Src/Zle/textobjects.c b/Src/Zle/textobjects.c
index c93777b65..a68c5296e 100644
--- a/Src/Zle/textobjects.c
+++ b/Src/Zle/textobjects.c
@@ -283,9 +283,9 @@ selectargument(UNUSED(char **args))
     free(linein);
 
     if (IS_THINGY(bindk, selectinshellword)) {
-	ZLE_CHAR_T *match = ZWS("`\'\"");
-	ZLE_CHAR_T *lmatch = ZWS("\'({"), *rmatch = ZWS("\')}");
-	ZLE_CHAR_T *ematch = match, *found;
+	const ZLE_CHAR_T *match = ZWS("`\'\"");
+	const ZLE_CHAR_T *lmatch = ZWS("\'({"), *rmatch = ZWS("\')}");
+	const ZLE_CHAR_T *ematch = match, *found;
 	int start, end = zlecs;
 	/* for 'in' widget, don't include initial blanks ... */
 	while (mark < zlecs && ZC_iblank(zleline[mark]))
diff --git a/Src/Zle/zle.h b/Src/Zle/zle.h
index 391586c4a..5bb9e7a5e 100644
--- a/Src/Zle/zle.h
+++ b/Src/Zle/zle.h
@@ -186,7 +186,7 @@ typedef struct thingy *Thingy;
 
 /* widgets (ZLE functions) */
 
-typedef int (*ZleIntFunc) _((char **));
+typedef int (*ZleIntFunc) (char **);
 
 struct widget {
     int flags;		/* flags (see below) */
@@ -258,6 +258,9 @@ struct modifier {
 #define MOD_NULL  (1<<5)   /* throw away text for the vi cut buffer */
 #define MOD_CHAR  (1<<6)   /* force character-wise movement */
 #define MOD_LINE  (1<<7)   /* force line-wise movement */
+#define MOD_PRI   (1<<8)   /* OS primary selection for the vi cut buffer */
+#define MOD_CLIP  (1<<9)   /* OS clipboard for the vi cut buffer */
+#define MOD_OSSEL (MOD_PRI | MOD_CLIP)  /* either system selection */
 
 /* current modifier status */
 
@@ -316,7 +319,7 @@ struct vichange {
 
 typedef struct keymap *Keymap;
 
-typedef void (*KeyScanFunc) _((char *, Thingy, char *, void *));
+typedef void (*KeyScanFunc) (char *, Thingy, char *, void *);
 
 #define invicmdmode() (!strcmp(curkeymapname, "vicmd"))
 
@@ -432,6 +435,8 @@ enum {
 struct region_highlight {
     /* Attributes turned on in the region */
     zattr atr;
+    /* Priority for this region relative to others that overlap */
+    int layer;
     /* Start of the region */
     int start;
     /* Start of the region in metafied ZLE line */
@@ -487,11 +492,7 @@ typedef struct {
      */
     REFRESH_CHAR chr;
     /*
-     * Its attributes.  'On' attributes (TXT_ATTR_ON_MASK) are
-     * applied before the character, 'off' attributes (TXT_ATTR_OFF_MASK)
-     * after it.  'On' attributes are present for all characters that
-     * need the effect; 'off' attributes are only present for the
-     * last character in the sequence.
+     * Its attributes.
      */
     zattr atr;
 } REFRESH_ELEMENT;
@@ -523,7 +524,7 @@ typedef REFRESH_ELEMENT *REFRESH_STRING;
     ((int)((unsigned)(x) - ZSH_INVALID_WCHAR_BASE))
 /* Turn a single byte character into a private wide character */
 #define ZSH_CHAR_TO_INVALID_WCHAR(x)			\
-    ((wchar_t)(STOUC(x) + ZSH_INVALID_WCHAR_BASE))
+    ((wchar_t)((unsigned char) x + ZSH_INVALID_WCHAR_BASE))
 #endif
 
 
diff --git a/Src/Zle/zle_hist.c b/Src/Zle/zle_hist.c
index cfaa70dae..0fdad70d9 100644
--- a/Src/Zle/zle_hist.c
+++ b/Src/Zle/zle_hist.c
@@ -68,6 +68,13 @@ Keymap isearch_keymap;
  */
 #define GETZLETEXT(ent)	((ent)->zle_text ? (ent)->zle_text : (ent)->node.nam)
 
+/*
+ * Flag that edits have been made to a zle line.
+ * If not set, nothing to forget.
+ */
+/**/
+int have_edits = 0;
+
 /**/
 void
 remember_edits(void)
@@ -81,6 +88,7 @@ remember_edits(void)
 	    if (ent->zle_text)
 		free(ent->zle_text);
 	    ent->zle_text = zlemetaline ? ztrdup(line) : line;
+	    have_edits = 1;
 	} else if (!zlemetaline)
 	    free(line);
     }
@@ -90,6 +98,10 @@ remember_edits(void)
 void
 forget_edits(void)
 {
+    if (!have_edits) {
+       return;
+    }
+    have_edits = 0;
     Histent he;
 
     for (he = hist_ring; he; he = up_histent(he)) {
diff --git a/Src/Zle/zle_keymap.c b/Src/Zle/zle_keymap.c
index d90838f03..5012917f5 100644
--- a/Src/Zle/zle_keymap.c
+++ b/Src/Zle/zle_keymap.c
@@ -404,7 +404,7 @@ static void
 scankeys(HashNode hn, UNUSED(int flags))
 {
     Key k = (Key) hn;
-    int f = k->nam[0] == Meta ? STOUC(k->nam[1])^32 : STOUC(k->nam[0]);
+    int f = k->nam[0] == Meta ? (unsigned char) k->nam[1]^32 : (unsigned char) k->nam[0];
     char m[3];
 
     while(skm_last < f) {
@@ -566,7 +566,7 @@ mod_export int
 bindkey(Keymap km, const char *seq, Thingy bind, char *str)
 {
     Key k;
-    int f = seq[0] == Meta ? STOUC(seq[1])^32 : STOUC(seq[0]);
+    int f = seq[0] == Meta ? (unsigned char) seq[1]^32 : (unsigned char) seq[0];
     char *buf, *ptr;
 
     if(km->flags & KM_IMMUTABLE)
@@ -661,7 +661,7 @@ keybind(Keymap km, char *seq, char **strp)
     Key k;
 
     if(ztrlen(seq) == 1) {
-	int f = seq[0] == Meta ? STOUC(seq[1])^32 : STOUC(seq[0]);
+	int f = seq[0] == Meta ? (unsigned char) seq[1]^32 : (unsigned char) seq[0];
 	Thingy bind = km->first[f];
 
 	if(bind)
@@ -687,7 +687,7 @@ keyisprefix(Keymap km, char *seq)
     if(!*seq)
 	return 1;
     if(ztrlen(seq) == 1) {
-	int f = seq[0] == Meta ? STOUC(seq[1])^32 : STOUC(seq[0]);
+	int f = seq[0] == Meta ? (unsigned char) seq[1]^32 : (unsigned char) seq[0];
 
 	if(km->first[f])
 	    return 0;
@@ -745,7 +745,7 @@ bin_bindkey(char *name, char **argv, Options ops, UNUSED(int func))
     static struct opn {
 	char o;
 	char selp;
-	int (*func) _((char *, char *, Keymap, char **, Options, char));
+	int (*func) (char *, char *, Keymap, char **, Options, char);
 	int min, max;
     } const opns[] = {
 	{ 'l', 0, bin_bindkey_lsmaps, 0,  -1 },
@@ -764,10 +764,10 @@ bin_bindkey(char *name, char **argv, Options ops, UNUSED(int func))
     int n;
 
     /* select operation and ensure no clashing arguments */
-    for(op = opns; op->o && !OPT_ISSET(ops,STOUC(op->o)); op++) ;
+    for(op = opns; op->o && !OPT_ISSET(ops,(unsigned char) op->o); op++) ;
     if(op->o)
 	for(opp = op; (++opp)->o; )
-	    if(OPT_ISSET(ops,STOUC(opp->o))) {
+	    if(OPT_ISSET(ops,(unsigned char) opp->o)) {
 		zwarnnam(name, "incompatible operation selection options");
 		return 1;
 	    }
@@ -1049,7 +1049,7 @@ bin_bindkey_bind(char *name, char *kmname, Keymap km, char **argv, Options ops,
 	    char m[3];
 
 	    if(len < 2 || len > 2 + (bseq[1] == '-') ||
-	       (first = STOUC(bseq[0])) > (last = STOUC(bseq[len - 1]))) {
+	       (first = (unsigned char) bseq[0]) > (last = (unsigned char) bseq[len - 1])) {
 		zwarnnam(name, "malformed key range `%s'", useq);
 		ret = 1;
 	    } else {
@@ -1149,8 +1149,8 @@ scanbindlist(char *seq, Thingy bind, char *str, void *magic)
     if(bind == bs->bind && (bind || !strcmp(str, bs->str)) &&
        ztrlen(seq) == 1 && ztrlen(bs->lastseq) == 1) {
 	int l = bs->lastseq[1] ?
-	    STOUC(bs->lastseq[1]) ^ 32 : STOUC(bs->lastseq[0]);
-	int t = seq[1] ? STOUC(seq[1]) ^ 32 : STOUC(seq[0]);
+	    (unsigned char) bs->lastseq[1] ^ 32 : (unsigned char) bs->lastseq[0];
+	int t = seq[1] ? (unsigned char) seq[1] ^ 32 : (unsigned char) seq[0];
 
 	if(t == l + 1) {
 	    zsfree(bs->lastseq);
@@ -1315,7 +1315,7 @@ default_bindings(void)
     Keymap vismap = newkeymap(NULL, "visual");
     Keymap smap = newkeymap(NULL, ".safe");
     Keymap vimaps[2], vilmaps[2], kptr;
-    char buf[3], *ed;
+    char buf[3];
     int i;
 
     /* vi insert mode and emacs mode:  *
@@ -1445,20 +1445,14 @@ default_bindings(void)
 	}
 
     /* Put the keymaps in the right namespace.  The "main" keymap  *
-     * will be linked to the "emacs" keymap, except that if VISUAL *
-     * or EDITOR contain the string "vi" then it will be linked to *
-     * the "viins" keymap.                                         */
+     * will be linked to the "emacs" keymap.                       */
     linkkeymap(vmap, "viins", 0);
     linkkeymap(emap, "emacs", 0);
     linkkeymap(amap, "vicmd", 0);
     linkkeymap(oppmap, "viopp", 0);
     linkkeymap(vismap, "visual", 0);
     linkkeymap(smap, ".safe", 1);
-    if (((ed = zgetenv("VISUAL")) && strstr(ed, "vi")) ||
-	((ed = zgetenv("EDITOR")) && strstr(ed, "vi")))
-	linkkeymap(vmap, "main", 0);
-    else
-	linkkeymap(emap, "main", 0);
+    linkkeymap(emap, "main", 0);
 
     /* the .safe map cannot be modified or deleted */
     smap->flags |= KM_IMMUTABLE;
@@ -1526,10 +1520,10 @@ getrestchar_keybuf(void)
      */
     while (1) {
 	if (bufind < buflen) {
-	    c = STOUC(keybuf[bufind++]);
+	    c = (unsigned char) keybuf[bufind++];
 	    if (c == Meta) {
 		DPUTS(bufind == buflen, "Meta at end of keybuf");
-		c = STOUC(keybuf[bufind++]) ^ 32;
+		c = (unsigned char) keybuf[bufind++] ^ 32;
 	    }
 	} else {
 	    /*
@@ -1586,7 +1580,7 @@ getkeymapcmd(Keymap km, Thingy *funcp, char **strp)
     Thingy func = t_undefinedkey;
     char *str = NULL;
     int lastlen = 0, lastc = lastchar;
-    int timeout = 0;
+    int timeout = 0, csi = 0;
 
     keybuflen = 0;
     keybuf[0] = 0;
@@ -1636,7 +1630,31 @@ getkeymapcmd(Keymap km, Thingy *funcp, char **strp)
 	    }
 #endif
 	}
-	if (!ispfx)
+
+	/* CSI key sequences have a well defined structure so if we currently
+	 * have an incomplete one, loop so the rest of it will be included in
+	 * the key sequence if that arrives within the timeout. */
+	if (!csi && keybuflen >= 3 && keybuf[keybuflen - 3] == '\033' &&
+		keybuf[keybuflen - 2] == '[')
+	    csi = keybuflen - 1;
+	if (csi) {
+	    if (keybuf[keybuflen - 2] == Meta || keybuf[keybuflen - 1] < 0x20
+		   || keybuf[keybuflen - 1] > 0x3f) {
+	    /* If we reach the end of a valid CSI sequence and the matched key
+	     * binding is for part of the CSI introduction, select instead the
+	     * undefined-key widget and consume the full sequence from the
+	     * input buffer. */
+		if (keybuf[keybuflen - 1] >= 0x40 &&
+			keybuf[keybuflen - 1] <= 0x7e && lastlen > csi - 2 &&
+			lastlen <= csi) {
+		    func = t_undefinedkey;
+		    lastlen = keybuflen;
+		}
+		csi = 0;
+	    }
+	}
+
+	if (!ispfx && !csi)
 	    break;
     }
     if(!lastlen && keybuflen)
diff --git a/Src/Zle/zle_main.c b/Src/Zle/zle_main.c
index 9edf30e01..1afb1bf58 100644
--- a/Src/Zle/zle_main.c
+++ b/Src/Zle/zle_main.c
@@ -737,6 +737,7 @@ raw_getbyte(long do_keytmout, char *cptr, int full)
 			) {
 			/* Handle the fd. */
 			char *fdbuf;
+			Thingy save_lbindk = refthingy(lbindk);
 			{
 			    char buf[BDIGBUFSIZE];
 			    convbase(buf, lwatch_fd->fd, 10);
@@ -779,6 +780,8 @@ raw_getbyte(long do_keytmout, char *cptr, int full)
 			     */
 			    errtry = 1;
 			}
+			unrefthingy(lbindk);
+			lbindk = save_lbindk;
 		    }
 		}
 		/* Function may have invalidated the display. */
@@ -876,7 +879,7 @@ getbyte(long do_keytmout, int *timeout, int full)
 #endif
 
     if (kungetct)
-	ret = STOUC(kungetbuf[--kungetct]);
+	ret = (unsigned char) kungetbuf[--kungetct];
     else {
 	for (;;) {
 	    int q = queue_signal_level();
@@ -940,7 +943,7 @@ getbyte(long do_keytmout, int *timeout, int full)
 	else if (cc == '\n')
 	    cc = '\r';
 
-	ret = STOUC(cc);
+	ret = (unsigned char) cc;
     }
     /*
      * curvichg.buf is raw bytes, not wide characters, so is dealt
@@ -1230,9 +1233,9 @@ zleread(char **lp, char **rp, int flags, int context, char *init, char *finish)
 	char *pptbuf;
 	int pptlen;
 
-	pptbuf = unmetafy(promptexpand(lp ? *lp : NULL, 0, NULL, NULL,
-				       &pmpt_attr),
+	pptbuf = unmetafy(promptexpand(lp ? *lp : NULL, 0, NULL, NULL),
 			  &pptlen);
+	pmpt_attr = txtcurrentattrs;
 	write_loop(2, pptbuf, pptlen);
 	free(pptbuf);
 	return shingetline();
@@ -1267,10 +1270,13 @@ zleread(char **lp, char **rp, int flags, int context, char *init, char *finish)
     fetchttyinfo = 0;
     trashedzle = 0;
     raw_lp = lp;
-    lpromptbuf = promptexpand(lp ? *lp : NULL, 1, NULL, NULL, &pmpt_attr);
+    txtcurrentattrs = txtpendingattrs = txtunknownattrs = 0;
+    lpromptbuf = promptexpand(lp ? *lp : NULL, 1, NULL, NULL);
+    pmpt_attr = txtcurrentattrs;
     raw_rp = rp;
-    rpmpt_attr = pmpt_attr;
-    rpromptbuf = promptexpand(rp ? *rp : NULL, 1, NULL, NULL, &rpmpt_attr);
+    rpromptbuf = promptexpand(rp ? *rp : NULL, 1, NULL, NULL);
+    rpmpt_attr = txtcurrentattrs;
+    prompt_attr = mixattrs(pmpt_attr, rpmpt_attr);
     free_prepostdisplay();
 
     zlereadflags = flags;
@@ -2009,17 +2015,18 @@ reexpandprompt(void)
 	    char *new_lprompt, *new_rprompt;
 	    looping = reexpanding;
 
-	    new_lprompt = promptexpand(raw_lp ? *raw_lp : NULL, 1, NULL, NULL,
-				       &pmpt_attr);
+	    txtcurrentattrs = txtpendingattrs = txtunknownattrs = 0;
+	    new_lprompt = promptexpand(raw_lp ? *raw_lp : NULL, 1, NULL, NULL);
+	    pmpt_attr = txtcurrentattrs;
 	    free(lpromptbuf);
 	    lpromptbuf = new_lprompt;
 
 	    if (looping != reexpanding)
 		continue;
 
-	    rpmpt_attr = pmpt_attr;
-	    new_rprompt = promptexpand(raw_rp ? *raw_rp : NULL, 1, NULL, NULL,
-				       &rpmpt_attr);
+	    new_rprompt = promptexpand(raw_rp ? *raw_rp : NULL, 1, NULL, NULL);
+	    rpmpt_attr = txtcurrentattrs;
+	    prompt_attr = mixattrs(pmpt_attr, rpmpt_attr);
 	    free(rpromptbuf);
 	    rpromptbuf = new_rprompt;
 	} while (looping != reexpanding);
@@ -2065,6 +2072,8 @@ trashzle(void)
 	trashedzle = 1;
 	zrefresh();
 	showinglist = sl;
+	treplaceattrs(prompt_attr);
+	applytextattributes(0);
 	moveto(nlnct, 0);
 	if (clearflag && tccan(TCCLEAREOD)) {
 	    tcout(TCCLEAREOD);
diff --git a/Src/Zle/zle_refresh.c b/Src/Zle/zle_refresh.c
index 30b5d4447..f076bdd61 100644
--- a/Src/Zle/zle_refresh.c
+++ b/Src/Zle/zle_refresh.c
@@ -36,8 +36,8 @@
  * non-zero width followed by an arbitrary (but typically small)
  * number of characters that have zero width (combining characters).
  *
- * The allocated size for each array is given by ?mw_size; nmw_ind
- * is the next free element, i.e. nmwbuf[nmw_ind] will be the next
+ * The allocated size for each array is given by omw_size and nmw_size;
+ * nmw_ind is the next free element, i.e. nmwbuf[nmw_ind] will be the next
  * element to be written (we never insert into omwbuf).  We initialise
  * nmw_ind to 1 to avoid the index stored in the character looking like a
  * NULL.  This wastees a word but it's safer than messing with pointers.
@@ -149,7 +149,7 @@ char *lpromptbuf, *rpromptbuf;
 /* Text attributes after displaying prompts */
 
 /**/
-zattr pmpt_attr, rpmpt_attr;
+zattr pmpt_attr, rpmpt_attr, prompt_attr;
 
 /* number of lines displayed */
 
@@ -203,12 +203,18 @@ int predisplaylen, postdisplaylen;
 
 
 /*
- * Attributes used by default on the command line, and
- * attributes for highlighting special (unprintable) characters
- * displayed on screen.
+ * Attributes used by default on the command line,
+ * for highlighting special (unprintable) characters displayed on screen,
+ * and for ellipsis continuation markers.
  */
 
-static zattr default_atr_on, special_atr_on;
+static zattr default_attr, special_attr, ellipsis_attr;
+
+/*
+ * Layer applied to highlighting for special characters
+ */
+
+static int special_layer;
 
 /*
  * Array of region highlights, no special termination.
@@ -245,20 +251,20 @@ char *tcout_func_name;
 int cost;
 
 # define SELECT_ADD_COST(X)	(cost += X)
-# define zputc(a)		(zwcputc(a, NULL), cost++)
+# define zputc(a)		(zwcputc(a), cost++)
 # define zwrite(a, b)		(zwcwrite((a), (b)), \
 				 cost += ((b) * ZLE_CHAR_SIZE))
 #else
 # define SELECT_ADD_COST(X)
-# define zputc(a)		zwcputc(a, NULL)
+# define zputc(a)		zwcputc(a)
 # define zwrite(a, b)		zwcwrite((a), (b))
 #endif
 
-static const REFRESH_ELEMENT zr_cr = { ZWC('\r'), 0 };
+static const REFRESH_ELEMENT zr_cr = { ZWC('\r'), TXT_ERROR };
 #ifdef MULTIBYTE_SUPPORT
-static const REFRESH_ELEMENT zr_dt = { ZWC('.'), 0 };
+static const REFRESH_ELEMENT zr_dt = { ZWC('.'), TXT_ERROR };
 #endif
-static const REFRESH_ELEMENT zr_nl = { ZWC('\n'), 0 };
+static const REFRESH_ELEMENT zr_nl = { ZWC('\n'), TXT_ERROR };
 static const REFRESH_ELEMENT zr_sp = { ZWC(' '), 0 };
 static const REFRESH_ELEMENT zr_zr = { ZWC('\0'), 0 };
 
@@ -269,10 +275,10 @@ static const REFRESH_ELEMENT zr_zr = { ZWC('\0'), 0 };
 static const REFRESH_ELEMENT zr_end_ellipsis[] = {
     { ZWC(' '), 0 },
     { ZWC('<'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
     { ZWC(' '), 0 },
 };
 #define ZR_END_ELLIPSIS_SIZE	\
@@ -281,16 +287,16 @@ static const REFRESH_ELEMENT zr_end_ellipsis[] = {
 static const REFRESH_ELEMENT zr_mid_ellipsis1[] = {
     { ZWC(' '), 0 },
     { ZWC('<'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
 };
 #define ZR_MID_ELLIPSIS1_SIZE	\
     ((int)(sizeof(zr_mid_ellipsis1)/sizeof(zr_mid_ellipsis1[0])))
 
 static const REFRESH_ELEMENT zr_mid_ellipsis2[] = {
-    { ZWC('>'), 0 },
+    { ZWC('>'), TXT_ERROR },
     { ZWC(' '), 0 },
 };
 #define ZR_MID_ELLIPSIS2_SIZE	\
@@ -298,10 +304,10 @@ static const REFRESH_ELEMENT zr_mid_ellipsis2[] = {
 
 static const REFRESH_ELEMENT zr_start_ellipsis[] = {
     { ZWC('>'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
-    { ZWC('.'), 0 },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
+    { ZWC('.'), TXT_ERROR },
 };
 #define ZR_START_ELLIPSIS_SIZE	\
     ((int)(sizeof(zr_start_ellipsis)/sizeof(zr_start_ellipsis[0])))
@@ -316,14 +322,15 @@ static void
 zle_set_highlight(void)
 {
     char **atrs = getaparam("zle_highlight");
-    int special_atr_on_set = 0;
-    int region_atr_on_set = 0;
-    int isearch_atr_on_set = 0;
-    int suffix_atr_on_set = 0;
-    int paste_atr_on_set = 0;
+    int special_attr_set = 0;
+    int region_attr_set = 0;
+    int isearch_attr_set = 0;
+    int suffix_attr_set = 0;
+    int paste_attr_set = 0;
+    int ellipsis_attr_set = 0;
     struct region_highlight *rhp;
 
-    special_atr_on = default_atr_on = 0;
+    special_attr = default_attr = 0;
     if (!region_highlights) {
 	region_highlights = (struct region_highlight *)
 	    zshcalloc(N_SPECIAL_HIGHLIGHTS*sizeof(struct region_highlight));
@@ -336,46 +343,63 @@ zle_set_highlight(void)
 	}
     }
 
+    /* Default layers */
+    region_highlights[0].layer = 20; /* region */
+    region_highlights[1].layer = 20; /* isearch */
+    region_highlights[2].layer = 10; /* suffix */
+    region_highlights[3].layer = 15; /* paste */
+    special_layer = 30;
+
     if (atrs) {
 	for (; *atrs; atrs++) {
 	    if (!strcmp(*atrs, "none")) {
 		/* reset attributes for consistency... usually unnecessary */
-		special_atr_on = default_atr_on = 0;
-		special_atr_on_set = 1;
-		paste_atr_on_set = region_atr_on_set =
-		    isearch_atr_on_set = suffix_atr_on_set = 1;
+		special_attr = default_attr = 0;
+		special_attr_set = 1;
+		paste_attr_set = region_attr_set =
+		    isearch_attr_set = suffix_attr_set = 1;
 	    } else if (strpfx("default:", *atrs)) {
-		match_highlight(*atrs + 8, &default_atr_on);
+		match_highlight(*atrs + 8, &default_attr, NULL);
 	    } else if (strpfx("special:", *atrs)) {
-		match_highlight(*atrs + 8, &special_atr_on);
-		special_atr_on_set = 1;
+		match_highlight(*atrs + 8, &special_attr, &special_layer);
+		special_attr_set = 1;
 	    } else if (strpfx("region:", *atrs)) {
-		match_highlight(*atrs + 7, &region_highlights[0].atr);
-		region_atr_on_set = 1;
+		match_highlight(*atrs + 7, &(region_highlights[0].atr),
+			&(region_highlights[0].layer));
+		region_attr_set = 1;
 	    } else if (strpfx("isearch:", *atrs)) {
-		match_highlight(*atrs + 8, &(region_highlights[1].atr));
-		isearch_atr_on_set = 1;
+		match_highlight(*atrs + 8, &(region_highlights[1].atr),
+			&(region_highlights[1].layer));
+		isearch_attr_set = 1;
 	    } else if (strpfx("suffix:", *atrs)) {
-		match_highlight(*atrs + 7, &(region_highlights[2].atr));
-		suffix_atr_on_set = 1;
+		match_highlight(*atrs + 7, &(region_highlights[2].atr),
+			&(region_highlights[2].layer));
+		suffix_attr_set = 1;
 	    } else if (strpfx("paste:", *atrs)) {
-		match_highlight(*atrs + 6, &(region_highlights[3].atr));
-		paste_atr_on_set = 1;
+		match_highlight(*atrs + 6, &(region_highlights[3].atr),
+			&(region_highlights[3].layer));
+		paste_attr_set = 1;
+	    } else if (strpfx("ellipsis:", *atrs)) {
+		match_highlight(*atrs + 9, &ellipsis_attr, NULL);
+		ellipsis_attr_set = 1;
 	    }
 	}
     }
 
-    /* Defaults */
-    if (!special_atr_on_set)
-	special_atr_on = TXTSTANDOUT;
-    if (!region_atr_on_set)
+    /* Default attributes */
+    if (!special_attr_set)
+	special_attr = TXTSTANDOUT;
+    if (!region_attr_set)
 	region_highlights[0].atr = TXTSTANDOUT;
-    if (!isearch_atr_on_set)
+    if (!isearch_attr_set)
 	region_highlights[1].atr = TXTUNDERLINE;
-    if (!suffix_atr_on_set)
+    if (!suffix_attr_set)
 	region_highlights[2].atr = TXTBOLDFACE;
-    if (!paste_atr_on_set)
+    if (!paste_attr_set)
 	region_highlights[3].atr = TXTSTANDOUT;
+    if (!ellipsis_attr_set)
+	ellipsis_attr = TXTBGCOLOUR | ((zattr) 3 << TXT_ATTR_BG_COL_SHIFT) |
+		TXTFGCOLOUR | ((zattr) 4 << TXT_ATTR_FG_COL_SHIFT);
 
     allocate_colour_buffer();
 }
@@ -400,14 +424,13 @@ zle_free_highlight(void)
 char **
 get_region_highlight(UNUSED(Param pm))
 {
-    int arrsize = n_region_highlights;
+    int arrsize = n_region_highlights - N_SPECIAL_HIGHLIGHTS;
     char **retarr, **arrp;
     struct region_highlight *rhp;
 
     /* region_highlights may not have been set yet */
-    if (!arrsize)
+    if (!n_region_highlights)
 	return hmkarray(NULL);
-    arrsize -= N_SPECIAL_HIGHLIGHTS;
     DPUTS(arrsize < 0, "arrsize is negative from n_region_highlights");
     arrp = retarr = (char **)zhalloc((arrsize+1)*sizeof(char *));
 
@@ -415,20 +438,18 @@ get_region_highlight(UNUSED(Param pm))
     for (rhp = region_highlights + N_SPECIAL_HIGHLIGHTS;
 	 arrsize--;
 	 rhp++, arrp++) {
-	char digbuf1[DIGBUFSIZE], digbuf2[DIGBUFSIZE];
-	int atrlen, alloclen;
-	const char memo_equals[] = "memo=";
-
-	sprintf(digbuf1, "%d", rhp->start);
-	sprintf(digbuf2, "%d", rhp->end);
-
-	atrlen = output_highlight(rhp->atr, NULL);
-	alloclen = atrlen + strlen(digbuf1) + strlen(digbuf2) +
-	    3; /* 2 spaces, 1 terminating NUL */
+	char digbuf[2 * DIGBUFSIZE], layerbuf[7 + DIGBUFSIZE];
+	int offset;
+	const char memo_equals[] = " memo=";
+	int alloclen = sprintf(digbuf, "%d %d", rhp->start, rhp->end) +
+	    output_highlight(rhp->atr, NULL) +
+	    2; /* space and terminating NUL */
 	if (rhp->flags & ZRH_PREDISPLAY)
-	    alloclen += 2; /* "P " */
+	    alloclen++; /* "P" */
+	if (rhp->layer != 10)
+	    alloclen += sprintf(layerbuf, ",layer=%d", rhp->layer);
 	if (rhp->memo)
-	    alloclen += 1 /* space */ + strlen(memo_equals) + strlen(rhp->memo);
+	    alloclen += sizeof(memo_equals) - 1 + strlen(rhp->memo);
 	*arrp = (char *)zhalloc(alloclen * sizeof(char));
 	/*
 	 * On input we allow a space after the flags.
@@ -437,13 +458,14 @@ get_region_highlight(UNUSED(Param pm))
 	 * into three words, and then check the first to
 	 * see if there are flags.  However, it's arguable.
 	 */
-	sprintf(*arrp, "%s%s %s ",
+	offset = sprintf(*arrp, "%s%s ",
 		(rhp->flags & ZRH_PREDISPLAY) ? "P" : "",
-		digbuf1, digbuf2);
-	(void)output_highlight(rhp->atr, *arrp + strlen(*arrp));
+		digbuf);
+	(void)output_highlight(rhp->atr, *arrp + offset);
 
+	if (rhp->layer != 10)
+	    strcat(*arrp, layerbuf);
 	if (rhp->memo) {
-	    strcat(*arrp, " ");
 	    strcat(*arrp, memo_equals);
 	    strcat(*arrp, rhp->memo);
 	}
@@ -452,12 +474,10 @@ get_region_highlight(UNUSED(Param pm))
     return retarr;
 }
 
-
 /*
  * The parameter system requires the pm argument, but this
  * may be NULL if called directly.
  */
-
 /**/
 void
 set_region_highlight(UNUSED(Param pm), char **aval)
@@ -516,7 +536,8 @@ set_region_highlight(UNUSED(Param pm), char **aval)
 	while (inblank(*strp))
 	    strp++;
 
-	strp = (char*) match_highlight(strp, &rhp->atr);
+	rhp->layer = 10; /* default */
+	strp = (char*) match_highlight(strp, &rhp->atr, &rhp->layer);
 
 	while (inblank(*strp))
 	    strp++;
@@ -571,22 +592,6 @@ unset_region_highlight(Param pm, int exp)
 }
 
 
-/* The last attributes that were on. */
-static zattr lastatr;
-
-/*
- * Clear the last attributes that we set:  used when we're going
- * to be outputting stuff that shouldn't show up as text.
- */
-static void
-clearattributes(void)
-{
-    if (lastatr) {
-	settextattributes(TXT_ATTR_OFF_FROM_ON(lastatr));
-	lastatr = 0;
-    }
-}
-
 /*
  * Output a termcap capability, clearing any text attributes so
  * as not to mess up the display.
@@ -595,7 +600,7 @@ clearattributes(void)
 static void
 tcoutclear(int cap)
 {
-    clearattributes();
+    cleartextattributes(0);
     tcout(cap);
 }
 
@@ -603,47 +608,20 @@ tcoutclear(int cap)
  * Output the character.  This must come from the new video
  * buffer, nbuf, since we access the multiword buffer nmwbuf
  * directly.
- *
- * curatrp may be NULL, otherwise points to an integer specifying
- * what attributes were turned on for a character output immediately
- * before, in order to optimise output of attribute changes.
  */
 
 /**/
 void
-zwcputc(const REFRESH_ELEMENT *c, zattr *curatrp)
+zwcputc(const REFRESH_ELEMENT *c)
 {
-    /*
-     * Safety: turn attributes off if last heard of turned on.
-     * This differs from *curatrp, which is an optimisation for
-     * writing lots of stuff at once.
-     */
 #ifdef MULTIBYTE_SUPPORT
     mbstate_t mbstate;
     int i;
     VARARR(char, mbtmp, MB_CUR_MAX + 1);
 #endif
 
-    if (lastatr & ~c->atr) {
-	/* Stuff on we don't want, turn it off */
-	settextattributes(TXT_ATTR_OFF_FROM_ON(lastatr & ~c->atr));
-	lastatr = 0;
-    }
-
-    /*
-     * Don't output "on" attributes in a string of characters with
-     * the same attributes.  Be careful in case a different colour
-     * needs setting.
-     */
-    if ((c->atr & TXT_ATTR_ON_MASK) &&
-	(!curatrp ||
-	 ((*curatrp & TXT_ATTR_ON_VALUES_MASK) !=
-	  (c->atr & TXT_ATTR_ON_VALUES_MASK)))) {
-	/* Record just the control flags we might need to turn off... */
-	lastatr = c->atr & TXT_ATTR_ON_MASK;
-	/* ...but set including the values for colour attributes */
-	settextattributes(c->atr & TXT_ATTR_ON_VALUES_MASK);
-    }
+    treplaceattrs(c->atr);
+    applytextattributes(0);
 
 #ifdef MULTIBYTE_SUPPORT
     if (c->atr & TXT_MULTIWORD_MASK) {
@@ -664,35 +642,15 @@ zwcputc(const REFRESH_ELEMENT *c, zattr *curatrp)
 #else
     fputc(c->chr, shout);
 #endif
-
-    /*
-     * Always output "off" attributes since we only turn off at
-     * the end of a chunk of highlighted text.
-     */
-    if (c->atr & TXT_ATTR_OFF_MASK) {
-	settextattributes(c->atr & TXT_ATTR_OFF_MASK);
-	lastatr &= ~((c->atr & TXT_ATTR_OFF_MASK) >> TXT_ATTR_OFF_ON_SHIFT);
-    }
-    if (curatrp) {
-	/*
-	 * Remember the current attributes:  those that are turned
-	 * on, less those that are turned off again.  Include
-	 * colour attributes here in case the colour changes to
-	 * another non-default one.
-	 */
-	*curatrp = (c->atr & TXT_ATTR_ON_VALUES_MASK) &
-	    ~((c->atr & TXT_ATTR_OFF_MASK) >> TXT_ATTR_OFF_ON_SHIFT);
-    }
 }
 
 static int
 zwcwrite(const REFRESH_STRING s, size_t i)
 {
     size_t j;
-    zattr curatr = 0;
 
     for (j = 0; j < i; j++)
-	zwcputc(s + j, &curatr);
+	zwcputc(s + j);
     return i; /* TODO something better for error indication */
 }
 
@@ -939,29 +897,6 @@ snextline(Rparams rpms)
     rpms->sen = rpms->s + winw;
 }
 
-
-/**/
-static void
-settextattributes(zattr atr)
-{
-    if (txtchangeisset(atr, TXTNOBOLDFACE))
-	tsetcap(TCALLATTRSOFF, 0);
-    if (txtchangeisset(atr, TXTNOSTANDOUT))
-	tsetcap(TCSTANDOUTEND, 0);
-    if (txtchangeisset(atr, TXTNOUNDERLINE))
-	tsetcap(TCUNDERLINEEND, 0);
-    if (txtchangeisset(atr, TXTBOLDFACE))
-	tsetcap(TCBOLDFACEBEG, 0);
-    if (txtchangeisset(atr, TXTSTANDOUT))
-	tsetcap(TCSTANDOUTBEG, 0);
-    if (txtchangeisset(atr, TXTUNDERLINE))
-	tsetcap(TCUNDERLINEBEG, 0);
-    if (txtchangeisset(atr, TXTFGCOLOUR|TXTNOFGCOLOUR))
-	set_colour_attribute(atr, COL_SEQ_FG, 0);
-    if (txtchangeisset(atr, TXTBGCOLOUR|TXTNOBGCOLOUR))
-	set_colour_attribute(atr, COL_SEQ_BG, 0);
-}
-
 #ifdef MULTIBYTE_SUPPORT
 /*
  * Add a multiword glyph at the screen location base.
@@ -1043,7 +978,6 @@ zrefresh(void)
     int tmppos;			/* t - tmpline				     */
     int tmpalloced;		/* flag to free tmpline when finished	     */
     int remetafy;		/* flag that zle line is metafied	     */
-    zattr txtchange;		/* attributes set after prompts              */
     int rprompt_off = 1;	/* Offset of rprompt from right of screen    */
     struct rparams rpms;
 #ifdef MULTIBYTE_SUPPORT
@@ -1192,9 +1126,7 @@ zrefresh(void)
 #endif
 	/* we probably should only have explicitly set attributes */
 	tsetcap(TCALLATTRSOFF, 0);
-	tsetcap(TCSTANDOUTEND, 0);
-	tsetcap(TCUNDERLINEEND, 0);
-	txtattrmask = 0;
+	txtcurrentattrs = txtpendingattrs = txtunknownattrs = 0;
 
 	if (trashedzle && !clearflag)
 	    reexpandprompt(); 
@@ -1218,9 +1150,8 @@ zrefresh(void)
 	    zputs(lpromptbuf, shout);
 	    if (lpromptwof == winw)
 		zputs("\n", shout);	/* works with both hasam and !hasam */
-	} else {
-	    txtchange = pmpt_attr;
-	    settextattributes(txtchange);
+	    /* lpromptbuf includes literal escapes so we need to update for it */
+	    txtcurrentattrs = txtpendingattrs = pmpt_attr;
 	}
 	if (clearflag) {
 	    zputc(&zr_cr);
@@ -1263,45 +1194,40 @@ zrefresh(void)
     rpms.s = nbuf[rpms.ln = 0] + lpromptw;
     rpms.sen = *nbuf + winw;
     for (t = tmpline, tmppos = 0; tmppos < tmpll; t++, tmppos++) {
-	unsigned ireg;
-	zattr base_atr_on = default_atr_on, base_atr_off = 0;
-	zattr all_atr_on, all_atr_off;
+	zattr base_attr = mixattrs(default_attr, prompt_attr);
+	zattr all_attr;
 	struct region_highlight *rhp;
+	int layer, nextlayer = 0;
 	/*
 	 * Calculate attribute based on region.
 	 */
-	for (ireg = 0, rhp = region_highlights;
-	     ireg < n_region_highlights;
-	     ireg++, rhp++) {
-	    int offset;
-	    if (rhp->flags & ZRH_PREDISPLAY)
-		offset = 0;	/* include predisplay in start end */
-	    else
-		offset = predisplaylen; /* increment over it */
-	    if (rhp->start + offset <= tmppos &&
-		tmppos < rhp->end + offset) {
-		if (rhp->atr & (TXTFGCOLOUR|TXTBGCOLOUR)) {
-		    /* override colour with later entry */
-		    base_atr_on = (base_atr_on & ~TXT_ATTR_ON_VALUES_MASK) |
-			rhp->atr;
-		} else {
-		    /* no colour set yet */
-		    base_atr_on |= rhp->atr;
+	do {
+	    unsigned ireg;
+	    layer = nextlayer;
+	    nextlayer = special_layer;
+	    for (ireg = 0, rhp = region_highlights;
+		ireg < n_region_highlights;
+		ireg++, rhp++) {
+		if (rhp->layer == layer) {
+		    int offset;
+		    if (rhp->flags & ZRH_PREDISPLAY)
+			offset = 0;	/* include predisplay in start end */
+		    else
+			offset = predisplaylen; /* increment over it */
+		    if (rhp->start + offset <= tmppos &&
+			tmppos < rhp->end + offset) {
+			base_attr = mixattrs(rhp->atr, base_attr);
+			if (layer > special_layer)
+			    all_attr = mixattrs(rhp->atr, all_attr);
+		    }
+		} else if (rhp->layer > layer && rhp->layer < nextlayer) {
+		    nextlayer = rhp->layer;
 		}
-		if (tmppos == rhp->end + offset - 1 ||
-		    tmppos == tmpll - 1)
-		    base_atr_off |= TXT_ATTR_OFF_FROM_ON(rhp->atr);
 	    }
-	}
-	if (special_atr_on & (TXTFGCOLOUR|TXTBGCOLOUR)) {
-	    /* keep colours from special attributes */
-	    all_atr_on = special_atr_on |
-		(base_atr_on & ~TXT_ATTR_COLOUR_ON_MASK);
-	} else {
-	    /* keep colours from standard attributes */
-	    all_atr_on = special_atr_on | base_atr_on;
-	}
-	all_atr_off = TXT_ATTR_OFF_FROM_ON(all_atr_on);
+	    if (special_layer == layer) {
+		all_attr = mixattrs(special_attr, base_attr);
+	    }
+	} while (nextlayer > layer);
 
 	if (t == scs)			/* if cursor is here, remember it */
 	    rpms.nvcs = rpms.s - nbuf[rpms.nvln = rpms.ln];
@@ -1319,10 +1245,9 @@ zrefresh(void)
 	    } else {
 		do {
 		    rpms.s->chr = ZWC(' ');
-		    rpms.s->atr = base_atr_on;
+		    rpms.s->atr = base_attr;
 		    rpms.s++;
 		} while ((++t0) & 7);
-		rpms.s[-1].atr |= base_atr_off;
 	    }
 	}
 #ifdef MULTIBYTE_SUPPORT
@@ -1341,11 +1266,9 @@ zrefresh(void)
 		    rpms.s->chr = ZWC(' ');
 		    if (!started)
 			started = 1;
-		    rpms.s->atr = all_atr_on;
+		    rpms.s->atr = all_attr;
 		    rpms.s++;
 		} while (rpms.s < rpms.sen);
-		if (started)
-		    rpms.s[-1].atr |= all_atr_off;
 		if (nextline(&rpms, 1))
 		    break;
 		if (t == scs) {
@@ -1369,15 +1292,11 @@ zrefresh(void)
 		 * occurrence.
 		 */
 		rpms.s->chr = ZWC('?');
-		rpms.s->atr = all_atr_on | all_atr_off;
+		rpms.s->atr = all_attr;
 		rpms.s++;
 	    } else {
 		/* We can fit it without reaching the end of the line. */
-		/*
-		 * As we don't actually output the WEOF, we attach
-		 * any off attributes to the character itself.
-		 */
-		rpms.s->atr = base_atr_on | base_atr_off;
+		rpms.s->atr = base_attr;
 		if (ichars > 1) {
 		    /*
 		     * Glyph includes combining characters.
@@ -1393,7 +1312,7 @@ zrefresh(void)
 		while (--width > 0) {
 		    rpms.s->chr = WEOF;
 		    /* Not used, but be consistent... */
-		    rpms.s->atr = base_atr_on | base_atr_off;
+		    rpms.s->atr = base_attr;
 		    rpms.s++;
 		}
 	    }
@@ -1410,17 +1329,16 @@ zrefresh(void)
 #endif
 	    ) {	/* other control character */
 	    rpms.s->chr = ZWC('^');
-	    rpms.s->atr = all_atr_on;
+	    rpms.s->atr = all_attr;
 	    rpms.s++;
 	    if (rpms.s == rpms.sen) {
 		/* text wrapped */
-		rpms.s[-1].atr |= all_atr_off;
 		if (nextline(&rpms, 1))
 		    break;
 	    }
 	    rpms.s->chr = (((unsigned int)*t & ~0x80u) > 31) ?
 		ZWC('?') : (*t | ZWC('@'));
-	    rpms.s->atr = all_atr_on | all_atr_off;
+	    rpms.s->atr = all_attr;
 	    rpms.s++;
 	}
 #ifdef MULTIBYTE_SUPPORT
@@ -1432,7 +1350,6 @@ zrefresh(void)
 	    char dispchars[11];
 	    char *dispptr = dispchars;
 	    wchar_t wc;
-	    int started = 0;
 
 #ifdef __STDC_ISO_10646__
 	    if (ZSH_INVALID_WCHAR_TEST(*t)) {
@@ -1449,31 +1366,23 @@ zrefresh(void)
 		if (mbtowc(&wc, dispptr, 1) == 1 /* paranoia */)
 		{
 		    rpms.s->chr = wc;
-		    if (!started)
-			started = 1;
-		    rpms.s->atr = all_atr_on;
+		    rpms.s->atr = all_attr;
 		    rpms.s++;
 		    if (rpms.s == rpms.sen) {
 			/* text wrapped */
-			if (started) {
-			    rpms.s[-1].atr |= all_atr_off;
-			    started = 0;
-			}
 			if (nextline(&rpms, 1))
 			    break;
 		    }
 		}
 		dispptr++;
 	    }
-	    if (started)
-		rpms.s[-1].atr |= all_atr_off;
 	    if (*dispptr) /* nextline said stop processing */
 		break;
 	}
 #else
 	else {			/* normal character */
 	    rpms.s->chr = *t;
-	    rpms.s->atr = base_atr_on | base_atr_off;
+	    rpms.s->atr = base_attr;
 	    rpms.s++;
 	}
 #endif
@@ -1499,13 +1408,12 @@ zrefresh(void)
 
     if (statusline) {
 	int outll, outsz;
-	zattr all_atr_on, all_atr_off;
+	zattr all_attr;
 	char *statusdup = ztrdup(statusline);
 	ZLE_STRING_T outputline =
 	    stringaszleline(statusdup, 0, &outll, &outsz, NULL); 
 
-	all_atr_on = special_atr_on;
-	all_atr_off = TXT_ATTR_OFF_FROM_ON(all_atr_on);
+	all_attr = special_attr;
 
 	rpms.tosln = rpms.ln + 1;
 	nbuf[rpms.ln][winw + 1] = zr_zr;	/* text not wrapped */
@@ -1525,7 +1433,7 @@ zrefresh(void)
 		}
 		if (width > rpms.sen - rpms.s) {
 		    rpms.s->chr = ZWC('?');
-		    rpms.s->atr = all_atr_on | all_atr_off;
+		    rpms.s->atr = all_attr;
 		    rpms.s++;
 		} else {
 		    rpms.s->chr = *u;
@@ -1542,7 +1450,7 @@ zrefresh(void)
 #endif
 	    if (ZC_icntrl(*u)) { /* simplified processing in the status line */
 		rpms.s->chr = ZWC('^');
-		rpms.s->atr = all_atr_on;
+		rpms.s->atr = all_attr;
 		rpms.s++;
 		if (rpms.s == rpms.sen) {
 		    nbuf[rpms.ln][winw + 1] = zr_nl;/* text wrapped */
@@ -1550,7 +1458,7 @@ zrefresh(void)
 		}
 		rpms.s->chr = (((unsigned int)*u & ~0x80u) > 31)
 		    ? ZWC('?') : (*u | ZWC('@'));
-		rpms.s->atr = all_atr_on | all_atr_off;
+		rpms.s->atr = all_attr;
 		rpms.s++;
 	    } else {
 		rpms.s->chr = *u;
@@ -1603,6 +1511,7 @@ zrefresh(void)
 	}
 #endif
 	ZR_memcpy(rpms.sen, zr_end_ellipsis, ZR_END_ELLIPSIS_SIZE);
+	rpms.sen[1].atr = ellipsis_attr;
 #ifdef MULTIBYTE_SUPPORT
 	/* Extend to the end if we backed off for a wide character */
 	if (extra_ellipsis) {
@@ -1638,6 +1547,7 @@ zrefresh(void)
 	}
 #endif
 	ZR_memcpy(rpms.sen, zr_mid_ellipsis1, ZR_MID_ELLIPSIS1_SIZE);
+	rpms.sen[1].atr = ellipsis_attr;
 	rpms.sen += ZR_MID_ELLIPSIS1_SIZE;
 #ifdef MULTIBYTE_SUPPORT
 	/* Extend if we backed off for a wide character */
@@ -1647,6 +1557,7 @@ zrefresh(void)
 	}
 #endif
 	ZR_memcpy(rpms.sen, zr_mid_ellipsis2, ZR_MID_ELLIPSIS2_SIZE);
+	rpms.sen[1].atr = prompt_attr;
 	nbuf[rpms.tosln][winw] = nbuf[rpms.tosln][winw + 1] = zr_zr;
     }
 
@@ -1679,7 +1590,9 @@ zrefresh(void)
 	t0 = winw - lpromptw;
 	t0 = t0 > ZR_START_ELLIPSIS_SIZE ? ZR_START_ELLIPSIS_SIZE : t0;
 	ZR_memcpy(nbuf[0] + lpromptw, zr_start_ellipsis, t0);
+	(*nbuf + lpromptw)->atr = ellipsis_attr;
 	ZR_memset(nbuf[0] + lpromptw + t0, zr_sp, winw - t0 - lpromptw);
+	(*nbuf + lpromptw + t0)->atr = prompt_attr;
 	nbuf[0][winw] = nbuf[0][winw + 1] = zr_zr;
     }
 
@@ -1725,9 +1638,9 @@ zrefresh(void)
 
     /* output the right-prompt if appropriate */
 	if (put_rpmpt && !iln && !oput_rpmpt) {
-	    zattr attrchange;
-
 	    moveto(0, winw - rprompt_off - rpromptw);
+	    treplaceattrs(pmpt_attr);
+	    applytextattributes(0);
 	    zputs(rpromptbuf, shout);
 	    if (rprompt_off) {
 		vcs = winw - rprompt_off;
@@ -1735,39 +1648,7 @@ zrefresh(void)
 		zputc(&zr_cr);
 		vcs = 0;
 	    }
-	/* reset character attributes to that set by the main prompt */
-	    txtchange = pmpt_attr;
-	    /*
-	     * Keep attributes that have actually changed,
-	     * which are ones off in rpmpt_attr and on in
-	     * pmpt_attr, and vice versa.
-	     */
-	    attrchange = txtchange &
-		(TXT_ATTR_OFF_FROM_ON(rpmpt_attr) |
-		 TXT_ATTR_ON_FROM_OFF(rpmpt_attr));
-	    /*
-	     * Careful in case the colour changed.
-	     */
-	    if (txtchangeisset(txtchange, TXTFGCOLOUR) &&
-		(!txtchangeisset(rpmpt_attr, TXTFGCOLOUR) ||
-		 ((txtchange ^ rpmpt_attr) & TXT_ATTR_FG_COL_MASK)))
-	    {
-		attrchange |=
-		    txtchange & (TXTFGCOLOUR | TXT_ATTR_FG_COL_MASK);
-	    }
-	    if (txtchangeisset(txtchange, TXTBGCOLOUR) &&
-		(!txtchangeisset(rpmpt_attr, TXTBGCOLOUR) ||
-		 ((txtchange ^ rpmpt_attr) & TXT_ATTR_BG_COL_MASK)))
-	    {
-		attrchange |=
-		    txtchange & (TXTBGCOLOUR | TXT_ATTR_BG_COL_MASK);
-	    }
-	    /*
-	     * Now feed these changes into the usual function,
-	     * if necessary.
-	     */
-	    if (attrchange)
-		settextattributes(attrchange);
+	    txtcurrentattrs = txtpendingattrs = rpmpt_attr;
 	}
     }
 
@@ -1780,11 +1661,6 @@ individually */
 	    refreshline(iln);
     }
 
-/* reset character attributes */
-    if (clearf && postedit) {
-	if ((txtchange = pmpt_attr ? pmpt_attr : rpmpt_attr))
-	    settextattributes(txtchange);
-    }
     clearf = 0;
     oput_rpmpt = put_rpmpt;
 
@@ -1984,8 +1860,6 @@ refreshline(int ln)
 /* 3: main display loop - write out the buffer using whatever tricks we can */
 
     for (;;) {
-	zattr now_off;
-
 #ifdef MULTIBYTE_SUPPORT
 	if ((!nl->chr || nl->chr != WEOF) && (!ol->chr || ol->chr != WEOF)) {
 #endif
@@ -2087,7 +1961,7 @@ refreshline(int ln)
 			     * deletions, so turn off text attributes.
 			     */
 			    if (first) {
-				clearattributes();
+				cleartextattributes(0);
 				first = 0;
 			    }
 			    tc_delchars(i);
@@ -2176,13 +2050,8 @@ refreshline(int ln)
 	    break;
 	do {
 #endif
-	    /*
-	     * If an attribute was on here but isn't any more,
-	     * output the sequence to turn it off.
-	     */
-	    now_off = ol->atr & ~nl->atr & TXT_ATTR_ON_MASK;
-	    if (now_off)
-		settextattributes(TXT_ATTR_OFF_FROM_ON(now_off));
+	    treplaceattrs(nl->atr);
+	    applytextattributes(0);
 
 	    /*
 	     * This is deliberately called if nl->chr is WEOF
@@ -2560,8 +2429,8 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 
     for (t0 = 0; t0 < tmpll; t0++) {
 	unsigned ireg;
-	zattr base_atr_on = 0, base_atr_off = 0;
-	zattr all_atr_on, all_atr_off;
+	zattr base_attr = 0;
+	zattr all_attr;
 	struct region_highlight *rhp;
 	/*
 	 * Calculate attribute based on region.
@@ -2576,38 +2445,28 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 		offset = predisplaylen; /* increment over it */
 	    if (rhp->start + offset <= t0 &&
 		t0 < rhp->end + offset) {
-		if (base_atr_on & (TXTFGCOLOUR|TXTBGCOLOUR)) {
+		if (base_attr & (TXTFGCOLOUR|TXTBGCOLOUR)) {
 		    /* keep colour already set */
-		    base_atr_on |= rhp->atr & ~TXT_ATTR_COLOUR_ON_MASK;
+		    base_attr |= rhp->atr & ~TXT_ATTR_COLOUR_MASK;
 		} else {
 		    /* no colour set yet */
-		    base_atr_on |= rhp->atr;
+		    base_attr |= rhp->atr;
 		}
-		if (t0 == rhp->end + offset - 1 ||
-		    t0 == tmpll - 1)
-		    base_atr_off |= TXT_ATTR_OFF_FROM_ON(rhp->atr);
 	    }
 	}
-	if (special_atr_on & (TXTFGCOLOUR|TXTBGCOLOUR)) {
-	    /* keep colours from special attributes */
-	    all_atr_on = special_atr_on |
-		(base_atr_on & ~TXT_ATTR_COLOUR_ON_MASK);
-	} else {
-	    /* keep colours from standard attributes */
-	    all_atr_on = special_atr_on | base_atr_on;
-	}
-	all_atr_off = TXT_ATTR_OFF_FROM_ON(all_atr_on);
+	all_attr = mixattrs(special_attr, base_attr);
 
+	if (t0 == tmpcs)
+	    nvcs = vp - vbuf;
 	if (tmpline[t0] == ZWC('\t')) {
 	    for (*vp++ = zr_sp; (vp - vbuf) & 7; )
 		*vp++ = zr_sp;
-	    vp[-1].atr |= base_atr_off;
 	} else if (tmpline[t0] == ZWC('\n')) {
 	    vp->chr = ZWC('\\');
-	    vp->atr = all_atr_on;
+	    vp->atr = all_attr;
 	    vp++;
 	    vp->chr = ZWC('n');
-	    vp->atr = all_atr_on | all_atr_off;
+	    vp->atr = all_attr;
 	    vp++;
 #ifdef MULTIBYTE_SUPPORT
 	} else if (WC_ISPRINT(tmpline[t0]) &&
@@ -2623,7 +2482,7 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 		}
 	    } else
 		ichars = 1;
-	    vp->atr = base_atr_on | base_atr_off;
+	    vp->atr = base_attr;
 	    if (ichars > 1)
 		addmultiword(vp, tmpline+t0, ichars);
 	    else
@@ -2631,7 +2490,7 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 	    vp++;
 	    while (--width > 0) {
 		vp->chr = WEOF;
-		vp->atr = base_atr_on | base_atr_off;
+		vp->atr = base_attr;
 		vp++;
 	    }
 	    t0 += ichars - 1;
@@ -2641,14 +2500,14 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 		   && (unsigned)tmpline[t0] <= 0xffU
 #endif
 		   ) {
-	    ZLE_INT_T t = tmpline[++t0];
+	    ZLE_INT_T t = tmpline[t0];
 
 	    vp->chr = ZWC('^');
-	    vp->atr = all_atr_on;
+	    vp->atr = all_attr;
 	    vp++;
 	    vp->chr = (((unsigned int)t & ~0x80u) > 31) ?
 		ZWC('?') : (t | ZWC('@'));
-	    vp->atr = all_atr_on | all_atr_off;
+	    vp->atr = all_attr;
 	    vp++;
 	}
 #ifdef MULTIBYTE_SUPPORT
@@ -2656,7 +2515,6 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 	    char dispchars[11];
 	    char *dispptr = dispchars;
 	    wchar_t wc;
-	    int started = 0;
 
 	    if ((unsigned)tmpline[t0] > 0xffffU) {
 		sprintf(dispchars, "<%.08x>", (unsigned)tmpline[t0]);
@@ -2666,25 +2524,19 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
 	    while (*dispptr) {
 		if (mbtowc(&wc, dispptr, 1) == 1 /* paranoia */) {
 		    vp->chr = wc;
-		    if (!started)
-			started = 1;
-		    vp->atr = all_atr_on;
+		    vp->atr = all_attr;
 		    vp++;
 		}
 		dispptr++;
 	    }
-	    if (started)
-		vp[-1].atr |= all_atr_off;
 	}
 #else
 	else {
 	    vp->chr = tmpline[t0];
-	    vp->atr = base_atr_on | base_atr_off;
+	    vp->atr = base_attr;
 	    vp++;
 	}
 #endif
-	if (t0 == tmpcs)
-	    nvcs = vp - vbuf - 1;
     }
     if (t0 == tmpcs)
 	nvcs = vp - vbuf;
@@ -2699,11 +2551,11 @@ singlerefresh(ZLE_STRING_T tmpline, int tmpll, int tmpcs)
     }
     if (winpos) {
 	vbuf[winpos].chr = ZWC('<');	/* line continues to the left */
-	vbuf[winpos].atr = 0;
+	vbuf[winpos].atr = ellipsis_attr;
     }
     if ((int)ZR_strlen(vbuf + winpos) > (winw - hasam)) {
 	vbuf[winpos + winw - hasam - 1].chr = ZWC('>');	/* line continues to right */
-	vbuf[winpos + winw - hasam - 1].atr = 0;
+	vbuf[winpos + winw - hasam - 1].atr = ellipsis_attr;
 	vbuf[winpos + winw - hasam] = zr_zr;
     }
     ZR_strcpy(nbuf[0], vbuf + winpos);
diff --git a/Src/Zle/zle_thingy.c b/Src/Zle/zle_thingy.c
index cd3f2c356..f71435b01 100644
--- a/Src/Zle/zle_thingy.c
+++ b/Src/Zle/zle_thingy.c
@@ -344,7 +344,7 @@ bin_zle(char *name, char **args, Options ops, UNUSED(int func))
 {
     static struct opn {
 	char o;
-	int (*func) _((char *, char **, Options, char));
+	int (*func) (char *, char **, Options, char);
 	int min, max;
     } const opns[] = {
 	{ 'l', bin_zle_list, 0, -1 },
@@ -366,10 +366,10 @@ bin_zle(char *name, char **args, Options ops, UNUSED(int func))
     int n;
 
     /* select operation and ensure no clashing arguments */
-    for(op = opns; op->o && !OPT_ISSET(ops,STOUC(op->o)); op++) ;
+    for(op = opns; op->o && !OPT_ISSET(ops, (unsigned char) op->o); op++) ;
     if(op->o)
 	for(opp = op; (++opp)->o; )
-	    if(OPT_ISSET(ops,STOUC(opp->o))) {
+	    if(OPT_ISSET(ops, (unsigned char) opp->o)) {
 		zwarnnam(name, "incompatible operation selection options");
 		return 1;
 	    }
diff --git a/Src/Zle/zle_tricky.c b/Src/Zle/zle_tricky.c
index fdd168763..aa3c71bc2 100644
--- a/Src/Zle/zle_tricky.c
+++ b/Src/Zle/zle_tricky.c
@@ -576,7 +576,7 @@ parambeg(char *s)
 	    while (idigit(*e))
 		e++;
 	else
-	    e = itype_end(e, IIDENT, 0);
+	    e = itype_end(e, INAMESPC, 0);
 
 	/* Now make sure that the cursor is inside the name. */
 	if (offs <= e - s && offs >= b - s && n <= 0) {
@@ -765,7 +765,7 @@ docomplete(int lst)
 			    else if (idigit(*q))
 				do q++; while (idigit(*q));
 			    else
-				q = itype_end(q, IIDENT, 0);
+				q = itype_end(q, INAMESPC, 0);
 			    sav = *q;
 			    *q = '\0';
 			    if (zlemetacs - wb == q - s &&
@@ -1315,6 +1315,8 @@ get_comp_string(void)
 	    ins = (tok == REPEAT ? 2 : (tok != STRING && tok != TYPESET));
 	    zsfree(cmdstr);
 	    cmdstr = ztrdup(tokstr);
+	    untokenize(cmdstr);
+	    remnulargs(cmdstr);
 	    cmdtok = tok;
 	    /*
 	     * If everything before is a redirection, or anything
@@ -1497,7 +1499,8 @@ get_comp_string(void)
 	if (varq)
 	    tt = clwords[clwpos];
 
-	s = itype_end(tt, IIDENT, 0);
+	/* The only place we complete namespaces, see IIDENT below */
+	s = itype_end(tt, INAMESPC, 0);
 	sav = *s;
 	*s = '\0';
 	zsfree(varname);
@@ -1568,6 +1571,8 @@ get_comp_string(void)
 
 	i = 0;
 	MB_METACHARINIT();
+	/* All further uses of IIDENT in this file should change to   *
+         * INAMESPC if this case is changed.  Too ugly to risk now.   */
 	if (itype_end(s, IIDENT, 1) == s)
 	    nnb = s + MB_METACHARLEN(s);
 	else
@@ -1641,7 +1646,7 @@ get_comp_string(void)
 	} else {
 	    /* In mathematical expression, we complete parameter names  *
 	     * (even if they don't have a `$' in front of them).  So we *
-	     * have to find that name.                                  */
+	     * have to find that name.  See above regarding INAMESPC    */
 	    char *cspos = zlemetaline + zlemetacs, *wptr, *cptr;
 	    we = itype_end(cspos, IIDENT, 0) - zlemetaline;
 
@@ -2426,7 +2431,7 @@ mod_export int
 printfmt(char *fmt, int n, int dopr, int doesc)
 {
     char *p = fmt, nc[DIGBUFSIZE];
-    int l = 0, cc = 0, b = 0, s = 0, u = 0, m;
+    int l = 0, cc = 0;
 
     MB_METACHARINIT();
     for (; *p; ) {
@@ -2437,48 +2442,45 @@ printfmt(char *fmt, int n, int dopr, int doesc)
 	    if (idigit(*++p))
 		arg = zstrtol(p, &p, 10);
 	    if (*p) {
-		m = 0;
 		switch (*p) {
 		case '%':
-		    if (dopr)
+		    if (dopr) {
+			applytextattributes(0);
 			putc('%', shout);
+		    }
 		    cc++;
 		    break;
 		case 'n':
 		    sprintf(nc, "%d", n);
-		    if (dopr)
+		    if (dopr) {
+			applytextattributes(0);
 			fputs(nc, shout);
+		    }
 		    cc += MB_METASTRWIDTH(nc);
 		    break;
 		case 'B':
-		    b = 1;
 		    if (dopr)
-			tcout(TCBOLDFACEBEG);
+			tsetattrs(TXTBOLDFACE);
 		    break;
 		case 'b':
-		    b = 0; m = 1;
 		    if (dopr)
-			tcout(TCALLATTRSOFF);
+			tunsetattrs(TXTBOLDFACE);
 		    break;
 		case 'S':
-		    s = 1;
 		    if (dopr)
-			tcout(TCSTANDOUTBEG);
+			tsetattrs(TXTSTANDOUT);
 		    break;
 		case 's':
-		    s = 0; m = 1;
 		    if (dopr)
-			tcout(TCSTANDOUTEND);
+			tunsetattrs(TXTSTANDOUT);
 		    break;
 		case 'U':
-		    u = 1;
 		    if (dopr)
-			tcout(TCUNDERLINEBEG);
+			tsetattrs(TXTUNDERLINE);
 		    break;
 		case 'u':
-		    u = 0; m = 1;
 		    if (dopr)
-			tcout(TCUNDERLINEEND);
+			tunsetattrs(TXTUNDERLINE);
 		    break;
 		case 'F':
 		case 'K':
@@ -2491,18 +2493,27 @@ printfmt(char *fmt, int n, int dopr, int doesc)
 		    } else
 			atr = match_colour(NULL, is_fg, arg);
 		    if (atr != TXT_ERROR)
-			set_colour_attribute(atr, is_fg ? COL_SEQ_FG :
-					     COL_SEQ_BG, 0);
+			tsetattrs(atr);
 		    break;
 		case 'f':
-		    set_colour_attribute(TXTNOFGCOLOUR, COL_SEQ_FG, 0);
+		    tunsetattrs(TXTFGCOLOUR);
 		    break;
 		case 'k':
-		    set_colour_attribute(TXTNOBGCOLOUR, COL_SEQ_BG, 0);
+		    tunsetattrs(TXTBGCOLOUR);
+		    break;
+		case 'H':
+		    if (p[1] == '{') {
+			p = parsehighlight(p + 2, '}', &atr);
+			--p;
+			if (atr != TXT_ERROR)
+			    treplaceattrs(atr);
+		    }
 		    break;
 		case '{':
 		    if (arg)
 			cc += arg;
+		    if (dopr)
+			applytextattributes(0);
 		    for (p++; *p && (*p != '%' || p[1] != '}'); p++) {
 			if (*p == Meta) {
 			    p++;
@@ -2518,14 +2529,6 @@ printfmt(char *fmt, int n, int dopr, int doesc)
 			p--;
 		    break;
 		}
-		if (dopr && m) {
-		    if (b)
-			tcout(TCBOLDFACEBEG);
-		    if (s)
-			tcout(TCSTANDOUTBEG);
-		    if (u)
-			tcout(TCUNDERLINEBEG);
-		}
 	    } else
 		break;
 	    p++;
@@ -2533,6 +2536,7 @@ printfmt(char *fmt, int n, int dopr, int doesc)
 	    if (*p == '\n') {
 		cc++;
 		if (dopr) {
+		    applytextattributes(0);
 		    if (tccan(TCCLEAREOL))
 			tcout(TCCLEAREOL);
 		    else {
@@ -2551,6 +2555,7 @@ printfmt(char *fmt, int n, int dopr, int doesc)
 		convchar_t cchar;
 		int clen = MB_METACHARLENCONV(p, &cchar);
 		if (dopr) {
+		    applytextattributes(0);
 		    while (clen--) {
 			if (*p == Meta) {
 			    p++;
@@ -2568,6 +2573,8 @@ printfmt(char *fmt, int n, int dopr, int doesc)
 	}
     }
     if (dopr) {
+	treplaceattrs(0);
+	applytextattributes(0);
         if (!(cc % zterm_columns))
             fputs(" \010", shout);
 	if (tccan(TCCLEAREOL))
diff --git a/Src/Zle/zle_utils.c b/Src/Zle/zle_utils.c
index 526216fa7..e2b86e863 100644
--- a/Src/Zle/zle_utils.c
+++ b/Src/Zle/zle_utils.c
@@ -512,12 +512,13 @@ stringaszleline(char *instr, int incs, int *outll, int *outsz, int *outcs)
 	    *outcs = outptr - outstr;
 	*outll = outptr - outstr;
     } else {
+	*outstr = ZWC('\0');
 	*outll = 0;
 	if (outcs)
 	    *outcs = 0;
     }
 #else
-    memcpy(outstr, instr, ll);
+    strcpy(outstr, instr);
     *outll = ll;
     if (outcs)
 	*outcs = incs;
@@ -580,7 +581,7 @@ struct zle_region;
 struct zle_region  {
     struct zle_region *next;
     /* Entries of region_highlight, as needed */
-    int atr;
+    zattr atr;
     int start;
     int end;
     int flags;
@@ -799,7 +800,7 @@ spaceinline(int ct)
 		if (rhp->start_meta - sub >= zlemetacs) {
 		    rhp->start_meta += ct;
 		}
-		if (rhp->end_meta - sub >= zlemetacs) {
+		if (rhp->end_meta - sub >= zlemetacs && (!predisplaylen || zlemetacs)) {
 		    rhp->end_meta += ct;
 		}
 	    }
@@ -827,7 +828,7 @@ spaceinline(int ct)
 		if (rhp->start - sub >= zlecs) {
 		    rhp->start += ct;
 		}
-		if (rhp->end - sub >= zlecs) {
+		if (rhp->end - sub >= zlecs && (!predisplaylen || zlecs)) {
 		    rhp->end += ct;
 		}
 	    }
@@ -866,13 +867,13 @@ shiftchars(int to, int cnt)
 		    if (rhp->start_meta - sub > to + cnt)
 			rhp->start_meta -= cnt;
 		    else
-			rhp->start_meta = to;
+			rhp->start_meta = to + sub;
 		}
 		if (rhp->end_meta - sub > to) {
 		    if (rhp->end_meta - sub > to + cnt)
 			rhp->end_meta -= cnt;
 		    else
-			rhp->end_meta = to;
+			rhp->end_meta = to + sub;
 		}
 	    }
 	}
@@ -896,13 +897,13 @@ shiftchars(int to, int cnt)
 		    if (rhp->start - sub > to + cnt)
 			rhp->start -= cnt;
 		    else
-			rhp->start = to;
+			rhp->start = to + sub;
 		}
 		if (rhp->end - sub > to) {
 		    if (rhp->end - sub > to + cnt)
 			rhp->end -= cnt;
 		    else
-			rhp->end = to;
+			rhp->end = to + sub;
 		}
 	    }
 	}
@@ -936,6 +937,28 @@ cut(int i, int ct, int flags)
   cuttext(zleline + i, ct, flags);
 }
 
+static char*
+base64_encode(const char *src, size_t len) {
+    static const char* base64_table =
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+    const unsigned char *end = (unsigned char *)src + len;
+    const unsigned char *in = (unsigned char *)src;
+    char *ret = zhalloc(1 + 4 * ((len + 2) / 3)); /* 4 bytes out for 3 in */
+    char *cur = ret;
+
+    for (; end - in > 0; in += 3, cur += 4) {
+        unsigned int n = *in << 16;
+        cur[3] = end - in > 2 ? base64_table[(n |= in[2]) & 0x3f] : '=';
+        cur[2] = end - in > 1 ? base64_table[((n |= in[1]<<8) >> 6) & 0x3f] : '=';
+        cur[1] = base64_table[(n >> 12) & 0x3f];
+        cur[0] = base64_table[n >> 18];
+    }
+    *cur = '\0';
+
+    return ret;
+}
+
 /*
  * As cut, but explicitly supply the text together with its length.
  */
@@ -948,7 +971,15 @@ cuttext(ZLE_STRING_T line, int ct, int flags)
 	return;
 
     UNMETACHECK();
-    if (zmod.flags & MOD_VIBUF) {
+    if (zmod.flags & MOD_OSSEL) {
+	int cutll;
+	char *mbcut = zlelineasstring(line, ct, 0, &cutll, NULL, 1);
+	unmetafy(mbcut, &cutll);
+	mbcut = base64_encode(mbcut, cutll);
+
+	fprintf(shout, "\033]52;%c;%s\a", zmod.flags & MOD_CLIP ? 'c' : 'p',
+		mbcut);
+    } else if (zmod.flags & MOD_VIBUF) {
 	struct cutbuffer *b = &vibuf[zmod.vibuf];
 
 	if (!(zmod.flags & MOD_VIAPP) || !b->buf) {
@@ -1220,7 +1251,7 @@ getzlequery(void)
 	REFRESH_ELEMENT re;
 	re.chr = c;
 	re.atr = 0;
-	zwcputc(&re, NULL);
+	zwcputc(&re);
     }
     return c == ZWC('y');
 }
@@ -1235,7 +1266,7 @@ bindztrdup(char *str)
     char *buf, *ptr, *ret;
 
     for(ptr = str; *ptr; ptr++) {
-	c = *ptr == Meta ? STOUC(*++ptr) ^ 32 : STOUC(*ptr);
+	c = *ptr == Meta ? (unsigned char) *++ptr ^ 32 : (unsigned char) *ptr;
 	if(c & 0x80) {
 	    len += 3;
 	    c &= 0x7f;
@@ -1249,7 +1280,7 @@ bindztrdup(char *str)
     }
     ptr = buf = zalloc(len);
     for(; *str; str++) {
-	c = *str == Meta ? STOUC(*++str) ^ 32 : STOUC(*str);
+	c = *str == Meta ? (unsigned char) *++str ^ 32 : (unsigned char) *str;
 	if(c & 0x80) {
 	    *ptr++ = '\\';
 	    *ptr++ = 'M';
diff --git a/Src/Zle/zle_vi.c b/Src/Zle/zle_vi.c
index 0f198d0e8..6692df830 100644
--- a/Src/Zle/zle_vi.c
+++ b/Src/Zle/zle_vi.c
@@ -1014,6 +1014,9 @@ int
 visetbuffer(char **args)
 {
     ZLE_INT_T ch;
+    const ZLE_CHAR_T *match = ZWS("_*+");
+    int registermod[] = { MOD_NULL, MOD_PRI, MOD_CLIP };
+    ZLE_CHAR_T *found;
 
     if (*args) {
 	ch = **args;
@@ -1022,12 +1025,12 @@ visetbuffer(char **args)
     } else {
 	ch = getfullchar(0);
     }
-    if (ch == ZWC('_')) {
-	zmod.flags |= MOD_NULL;
+    if ((found = ZS_strchr(match, ch))) {
+	zmod.flags |= registermod[found - match];
 	prefixflag = 1;
 	return 0;
     } else
-	zmod.flags &= ~MOD_NULL;
+	zmod.flags &= ~(MOD_NULL | MOD_OSSEL);
     if ((ch < ZWC('0') || ch > ZWC('9')) &&
 	 (ch < ZWC('a') || ch > ZWC('z')) &&
 	 (ch < ZWC('A') || ch > ZWC('Z')))
diff --git a/Src/builtin.c b/Src/builtin.c
index a7b7755a7..7bfb1ce1d 100644
--- a/Src/builtin.c
+++ b/Src/builtin.c
@@ -55,7 +55,7 @@ static struct builtin builtins[] =
     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("declare", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%afghi:%klmnp:%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),
@@ -88,7 +88,7 @@ static struct builtin builtins[] =
     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("local", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%ahi:%lnp:%rtux", NULL),
     BUILTIN("logout", 0, bin_break, 0, 1, BIN_LOGOUT, NULL, NULL),
 
 #if defined(ZSH_MEM) & defined(ZSH_MEM_DEBUG)
@@ -121,12 +121,12 @@ static struct builtin builtins[] =
     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("typeset", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%afghi:%klp:%rtuxmnz", 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("unset", BINF_PSPECIAL, bin_unset, 1, -1, BIN_UNSET, "fmvn", 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),
@@ -2030,6 +2030,25 @@ typeset_single(char *cname, char *pname, Param pm, int func,
     int usepm, tc, keeplocal = 0, newspecial = NS_NONE, readonly, dont_set = 0;
     char *subscript;
 
+    if (pm && (pm->node.flags & PM_NAMEREF) && !((off|on) & PM_NAMEREF) &&
+	(pm->level == locallevel || !(on & PM_LOCAL))) {
+	if ((pm = (Param)resolve_nameref(pm, NULL)))
+	    pname = pm->node.nam;
+	if (pm && (pm->node.flags & PM_NAMEREF) &&
+	    (on & ~(PM_NAMEREF|PM_LOCAL|PM_READONLY))) {
+	    /* Changing type of PM_SPECIAL|PM_AUTOLOAD is a fatal error.  *
+	     * Should this be a fatal error as well, rather than warning? */
+	    if (pm->width)
+		zwarnnam(cname,
+			 "%s: can't change type via subscript reference",
+			 pm->u.str);
+	    else
+		zwarnnam(cname, "%s: can't change type of a named reference",
+			 pname);
+	    return NULL;
+	}
+    }
+
     /*
      * 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
@@ -2040,7 +2059,7 @@ typeset_single(char *cname, char *pname, Param pm, int func,
      * POSIXBUILTINS horror: we need to retain the 'readonly' or 'export'
      * flags of an unset parameter.
      */
-    usepm = pm && (!(pm->node.flags & PM_UNSET) ||
+    usepm = pm && (!(pm->node.flags & PM_UNSET) || OPT_ISSET(ops, 'p') ||
 		   (isset(POSIXBUILTINS) &&
 		    (pm->node.flags & (PM_READONLY|PM_EXPORTED))));
 
@@ -2088,15 +2107,27 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 	    return NULL;
 	}
 	tc = 1;
-	usepm = 0;
+	if (OPT_MINUS(ops,'p'))
+	    usepm = (on & pm->node.flags);
+	else if (OPT_PLUS(ops,'p'))
+	    usepm = (off & pm->node.flags);
+	else
+	    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;
+	if ((tc = chflags && chflags != (PM_EFLOAT|PM_FFLOAT))) {
+	    if (OPT_MINUS(ops,'p'))
+		usepm = (on & pm->node.flags);
+	    else if (OPT_PLUS(ops,'p'))
+		usepm = (off & pm->node.flags);
+	    else
+		usepm = 0;
+	}
+
     }
 
     /*
@@ -2148,20 +2179,23 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 	    }
 	    if (err)
 	    {
-		zerrnam(cname, "%s: can't change type of a special parameter",
-			pname);
+		if (!OPT_ISSET(ops,'p'))
+		    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);
+	    if (!OPT_ISSET(ops,'p'))
+		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)) {
+    if (isset(POSIXBUILTINS) && !OPT_ISSET(ops,'p')) {
 	/*
 	 * Stricter rules about retaining readonly attribute in this case.
 	 */
@@ -2190,6 +2224,11 @@ typeset_single(char *cname, char *pname, Param pm, int func,
      *   ii. we are creating a new local parameter
      */
     if (usepm) {
+	if (OPT_MINUS(ops,'p') && on &&
+	    !((on & pm->node.flags) || ((on & PM_LOCAL) && pm->level)))
+	    return NULL;
+	else if (OPT_PLUS(ops,'p') && off && !(off & pm->node.flags))
+	    return NULL;
 	if ((asg->flags & ASG_ARRAY) ?
 	    !(PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED)) :
 	    (asg->value.scalar && (PM_TYPE(pm->node.flags &
@@ -2199,17 +2238,27 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 	}
 	on &= ~PM_LOCAL;
 	if (!on && !roff && !ASG_VALUEP(asg)) {
+	    int with_ns = OPT_ISSET(ops,'m') ? PRINT_WITH_NAMESPACE : 0;
 	    if (OPT_ISSET(ops,'p'))
-		paramtab->printnode(&pm->node, PRINT_TYPESET);
+		paramtab->printnode(&pm->node, PRINT_TYPESET|with_ns);
 	    else if (!OPT_ISSET(ops,'g') &&
 		     (unset(TYPESETSILENT) || OPT_ISSET(ops,'m')))
-		paramtab->printnode(&pm->node, PRINT_INCLUDEVALUE);
+		paramtab->printnode(&pm->node, PRINT_INCLUDEVALUE|with_ns);
 	    return pm;
 	}
 	if ((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) {
 	    zerrnam(cname, "%s: restricted", pname);
 	    return pm;
 	}
+	if ((pm->node.flags & PM_READONLY) && !(off & PM_READONLY) &&
+	    /* It seems as though these checks should not be specific to
+	     * PM_NAMEREF, but changing that changes historic behavior */
+	    ((on & PM_NAMEREF) != (pm->node.flags & PM_NAMEREF) ||
+	     (asg && (pm->node.flags & PM_NAMEREF)))) {
+	    zerrnam(cname, "%s: read-only %s", pname,
+		    (pm->node.flags & PM_NAMEREF) ? "reference" : "variable");
+	    return NULL;
+	}
 	if ((on & PM_UNIQUE) && !(pm->node.flags & PM_READONLY & ~off)) {
 	    Param apm;
 	    char **x;
@@ -2231,6 +2280,10 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 		    arrfixenv(pm->node.nam, x);
 	    }
 	}
+	if (OPT_ISSET(ops,'p')) {
+	    paramtab->printnode(&pm->node, PRINT_TYPESET|PRINT_WITH_NAMESPACE);
+	    return pm;
+	}
 	if (usepm == 2)		/* do not change the PM_UNSET flag */
 	    pm->node.flags = (pm->node.flags | (on & ~PM_READONLY)) & ~off;
 	else {
@@ -2286,10 +2339,9 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 	if (errflag)
 	    return NULL;
 	pm->node.flags |= (on & PM_READONLY);
-	if (OPT_ISSET(ops,'p'))
-	    paramtab->printnode(&pm->node, PRINT_TYPESET);
 	return pm;
-    }
+    } else if (OPT_ISSET(ops,'p'))
+	return NULL;	/* Nothing to print */
 
     if ((asg->flags & ASG_ARRAY) ?
 	!(on & (PM_ARRAY|PM_HASHED)) :
@@ -2304,7 +2356,7 @@ typeset_single(char *cname, char *pname, Param pm, int func,
      * or we're converting the type of a parameter.  In the
      * last case only, we need to delete the old parameter.
      */
-    if (tc) {
+    if (tc && !OPT_ISSET(ops,'p')) {
 	/* Maintain existing readonly/exported status... */
 	on |= ~off & (PM_READONLY|PM_EXPORTED) & pm->node.flags;
 	/* ...but turn off existing readonly so we can delete it */
@@ -2406,6 +2458,11 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 		return NULL;
 	}
     } else if ((subscript = strchr(pname, '['))) {
+	if (on & PM_NAMEREF) {
+	    zerrnam(cname,
+		    "%s: reference variable cannot be an array", pname);
+	    return NULL;
+	}
 	if (on & PM_READONLY) {
 	    zerrnam(cname,
 		    "%s: can't create readonly array elements", pname);
@@ -2452,6 +2509,8 @@ typeset_single(char *cname, char *pname, Param pm, int func,
 		    "%s: inconsistent array element or slice assignment", pname);
 	    return NULL;
 	}
+    } else if (!pm && OPT_ISSET(ops,'p')) {
+	return NULL;
     }
     /*
      * As we can hide existing parameters, we allow a name if
@@ -2613,7 +2672,7 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
     char *optstr = TYPESET_OPTSTR;
     int on = 0, off = 0, roff, bit = PM_ARRAY;
     int i;
-    int returnval = 0, printflags = 0;
+    int returnval = 0, printflags = PRINT_WITH_NAMESPACE;
     int hasargs = *argv != NULL || (assigns && firstnode(assigns));
 
     /* POSIXBUILTINS is set for bash/ksh and both ignore -p with args */
@@ -2629,17 +2688,34 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
     if (func == BIN_READONLY && isset(POSIXBUILTINS) && !OPT_PLUS(ops, 'g'))
 	ops->ind['g'] = 1;
 
+#if 0
+    /* "local" rejects -m, this should too ... what about +m ? */
+    if (locallevel && OPT_MINUS(ops, 'm') &&
+	!(OPT_MINUS(ops, 'g') || OPT_ISSET(ops, 'p'))) {
+	zerrnam(name, "bad option: -m");
+	return 1;
+    }
+#endif
+
     /* 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);
+	int optval = (unsigned char) *optstr;
 	if (OPT_MINUS(ops,optval))
 	    on |= bit;
 	else if (OPT_PLUS(ops,optval))
 	    off |= bit;
     }
+    if (OPT_MINUS(ops,'n')) {
+	if ((on|off) & ~(PM_READONLY|PM_UPPER)) {
+	    zwarnnam(name, "no other attributes allowed with -n");
+	    return 1;
+	}
+	on |= PM_NAMEREF;
+    } else if (OPT_PLUS(ops,'n'))
+	off |= PM_NAMEREF;
     roff = off;
 
     /* Sanity checks on the options.  Remove conflicting options. */
@@ -2673,7 +2749,6 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
 
     queue_signals();
 
-    /* Given no arguments, list whatever the options specify. */
     if (OPT_ISSET(ops,'p')) {
 
 	if (isset(POSIXBUILTINS) && SHELL_EMULATION() != EMULATE_KSH) {
@@ -2699,8 +2774,14 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
 	    /* -p0 treated as -p for consistency */
 	}
     }
+
+    /* Given no arguments, list whatever the options specify. */
     if (!hasargs) {
 	int exclude = 0;
+
+	if (!OPT_ISSET(ops,'m'))
+	    printflags &= ~PRINT_WITH_NAMESPACE;
+	
 	if (!OPT_ISSET(ops,'p')) {
 	    if (!(on|roff))
 		printflags |= PRINT_TYPE;
@@ -2718,10 +2799,18 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
 	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;
+    /* Using *name here is cheating, "local" allows no -g option */
+    if ((*name == 'l' || OPT_PLUS(ops,'g')))
+        on |= PM_LOCAL;
+    else if (!OPT_ISSET(ops,'g')) {
+        if (OPT_MINUS(ops, 'x')) {
+	    if (isset(GLOBALEXPORT))
+		ops->ind['g'] = 1;
+	    else if (locallevel)
+		on |= PM_LOCAL;
+        } else if (!(OPT_ISSET(ops,'x') || OPT_ISSET(ops,'m')))
+            on |= PM_LOCAL;
+    }
 
     if ((on & PM_TIED) && !OPT_ISSET(ops, 'p')) {
 	Param apm;
@@ -2956,6 +3045,13 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
     /* With the -m option, treat arguments as glob patterns */
     if (OPT_ISSET(ops,'m')) {
 	if (!OPT_ISSET(ops,'p')) {
+	    if (on & PM_NAMEREF) {
+		/* It's generally unwise to mass-change the types of
+		 * parameters, but for namerefs it would be fatal */
+		unqueue_signals();
+		zerrnam(name, "invalid reference");
+		return 1;
+	    }
 	    if (!(on|roff))
 		printflags |= PRINT_TYPE;
 	    if (!on)
@@ -3022,6 +3118,47 @@ bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func)
 	    }
 	    continue;
 	}
+
+	if (on & PM_NAMEREF) {
+	    if (asg->value.scalar &&
+		((pm = (Param)resolve_nameref((Param)hn, asg)) &&
+		 (pm->node.flags & PM_NAMEREF))) {
+		if (pm->node.flags & PM_SPECIAL) {
+		    zwarnnam(name, "%s: invalid reference", pm->node.nam);
+		    returnval = 1;
+		    continue;
+		} else if (pm->u.str && strcmp(pm->u.str, asg->name) == 0) {
+		    zwarnnam(name, "%s: invalid self reference", asg->name);
+		    returnval = 1;
+		    continue;
+		}
+	    }
+	    if (hn) {
+		/* namerefs always start over fresh */
+		if (((Param)hn)->level >= locallevel ||
+		    (!(on & PM_LOCAL) && ((Param)hn)->level < locallevel)) {
+		    Param oldpm = (Param)hn;
+		    if (!asg->value.scalar &&
+			PM_TYPE(oldpm->node.flags) == PM_SCALAR &&
+			oldpm->u.str)
+			asg->value.scalar = dupstring(oldpm->u.str);
+		    /* Defer read-only error to typeset_single() */
+		    if (!(hn->flags & PM_READONLY)) {
+			unsetparam_pm(oldpm, 0, 1);
+			hn = NULL;
+		    }
+		}
+		/* Passing a NULL pm to typeset_single() makes the
+		 * nameref read-only before assignment, which breaks
+		 *   typeset -rn ref=var
+		 * so this is special-cased to permit that action
+		 * like assign-at-create for other parameter types.
+		 */
+		if (hn && !(hn->flags & PM_READONLY))
+		    hn = NULL;
+	    }
+	}
+
 	if (!typeset_single(name, asg->name, (Param)hn,
 			    func, on, off, roff, asg, NULL,
 			    ops, 0))
@@ -3308,16 +3445,16 @@ bin_functions(char *name, char **argv, Options ops, int func)
 	    newsh->sticky = sticky_emulation_dup(shf->sticky, 0);
 	/* is newsh a signal trap? (adapted from exec.c) */
 	if (!strncmp(s, "TRAP", 4)) {
-	    int signum = getsignum(s + 4);
-	    if (signum != -1) {
-		if (settrap(signum, NULL, ZSIG_FUNC)) {
+	    int sigidx = getsigidx(s + 4);
+	    if (sigidx != -1) {
+		if (settrap(sigidx, NULL, ZSIG_FUNC)) {
 		    freeeprog(newsh->funcdef);
 		    dircache_set(&newsh->filename, NULL);
 		    zfree(newsh, sizeof(*newsh));
 		    return 1;
 		}
 		/* Remove any old node explicitly */
-		removetrapnode(signum);
+		removetrapnode(sigidx);
 	    }
 	}
 	shfunctab->addnode(shfunctab, ztrdup(s), &newsh->node);
@@ -3596,15 +3733,15 @@ bin_functions(char *name, char **argv, Options ops, int func)
 		/* no flags, so just print */
 		printshfuncexpand(&shf->node, pflags, expand);
 	} else if (on & PM_UNDEFINED) {
-	    int signum = -1, ok = 1;
+	    int sigidx = -1, ok = 1;
 
 	    if (!strncmp(*argv, "TRAP", 4) &&
-		(signum = getsignum(*argv + 4)) != -1) {
+		(sigidx = getsigidx(*argv + 4)) != -1) {
 		/*
 		 * Because of the possibility of alternative names,
 		 * we must remove the trap explicitly.
 		 */
-		removetrapnode(signum);
+		removetrapnode(sigidx);
 	    }
 
 	    if (**argv == '/') {
@@ -3640,8 +3777,8 @@ bin_functions(char *name, char **argv, Options ops, int func)
 	    shfunc_set_sticky(shf);
 	    add_autoload_function(shf, *argv);
 
-	    if (signum != -1) {
-		if (settrap(signum, NULL, ZSIG_FUNC)) {
+	    if (sigidx != -1) {
+		if (settrap(sigidx, NULL, ZSIG_FUNC)) {
 		    shfunctab->removenode(shfunctab, *argv);
 		    shfunctab->freenode(&shf->node);
 		    returnval = 1;
@@ -3715,7 +3852,11 @@ bin_unset(char *name, char **argv, Options ops, int func)
 			if ((!(pm->node.flags & PM_RESTRICTED) ||
 			     unset(RESTRICTED)) &&
 			    pattry(pprog, pm->node.nam)) {
-			    unsetparam_pm(pm, 0, 1);
+			    if (!OPT_ISSET(ops,'n') &&
+				(pm->node.flags & PM_NAMEREF) && pm->u.str)
+				unsetparam(pm->u.str);
+			    else
+				unsetparam_pm(pm, 0, 1);
 			    match++;
 			}
 		    }
@@ -3767,6 +3908,11 @@ bin_unset(char *name, char **argv, Options ops, int func)
 	    zerrnam(name, "%s: restricted", pm->node.nam);
 	    returnval = 1;
 	} else if (ss) {
+	    if ((pm->node.flags & PM_NAMEREF) &&
+		(!(pm = (Param)resolve_nameref(pm, NULL)) || pm->width)) {
+		/* warning? */
+		continue;
+	    }
 	    if (PM_TYPE(pm->node.flags) == PM_HASHED) {
 		HashTable tht = paramtab;
 		if ((paramtab = pm->gsu.h->getfn(pm)))
@@ -3805,6 +3951,18 @@ bin_unset(char *name, char **argv, Options ops, int func)
 		returnval = 1;
 	    }
 	} else {
+	    if (!OPT_ISSET(ops,'n')) {
+		int ref = (pm->node.flags & PM_NAMEREF);
+		if (!(pm = (Param)resolve_nameref(pm, NULL)))
+		    continue;
+		if (ref && pm->level < locallevel &&
+		    !(pm->node.flags & PM_READONLY)) {
+		    /* Just mark unset, do not remove from table */
+		    stdunsetfn(pm, 0);
+		    pm->node.flags |= PM_DECLARED;
+		    continue;
+		}
+	    }
 	    if (unsetparam_pm(pm, 0, 1))
 		returnval = 1;
 	}
@@ -3941,6 +4099,7 @@ bin_whence(char *nam, char **argv, Options ops, int func)
     /* Take arguments literally -- do not glob */
     queue_signals();
     for (; *argv; argv++) {
+	informed = 0;
 	if (!OPT_ISSET(ops,'p') && !allmatched) {
 	    char *suf;
 
@@ -4603,6 +4762,8 @@ bin_print(char *name, char **args, Options ops, int func)
     /* compute lengths, and interpret according to -P, -D, -e, etc. */
     argc = arrlen(args);
     len = (int *) hcalloc(argc * sizeof(int));
+    if (OPT_ISSET(ops, 'P'))
+	txtunknownattrs = TXT_ATTR_ALL;
     for (n = 0; n < argc; n++) {
 	/* first \ sequences */
 	if (fmt ||
@@ -4633,7 +4794,7 @@ bin_print(char *name, char **args, Options ops, int func)
 	     */
 	    char *str = unmetafy(
 		promptexpand(metafy(args[n], len[n], META_NOALLOC),
-			     0, NULL, NULL, NULL),
+			     0, NULL, NULL),
 		&len[n]);
 	    args[n] = dupstrpfx(str, len[n]);
 	    free(str);
@@ -4752,7 +4913,7 @@ bin_print(char *name, char **args, Options ops, int func)
 		     */
 		    if (*aptr == '\033' || *aptr == '\233') {
 			for (aptr++, l--;
-			     l && !isalpha(STOUC(*aptr));
+			     l && !isalpha((unsigned char) (*aptr));
 			     aptr++, l--)
 			    ;
 			aptr++;
@@ -5114,7 +5275,8 @@ bin_print(char *name, char **args, Options ops, int func)
 		    }
 		}
 		if (*argp) {
-		    width = (int)mathevali(*argp++);
+		    width = (int)mathevali(metafy(*argp, len[argp - args], META_NOALLOC));
+		    argp++;
 		    if (errflag) {
 			errflag &= ~ERRFLAG_ERROR;
 			ret = 1;
@@ -5148,7 +5310,8 @@ bin_print(char *name, char **args, Options ops, int func)
 		    }
 
 		    if (*argp) {
-			prec = (int)mathevali(*argp++);
+			prec = (int)mathevali(metafy(*argp, len[argp - args], META_NOALLOC));
+			argp++;
 			if (errflag) {
 			    errflag &= ~ERRFLAG_ERROR;
 			    ret = 1;
@@ -5222,20 +5385,21 @@ bin_print(char *name, char **args, Options ops, int func)
 #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 <= 0 means one of
+			     *
+			     * 0: NUL, handle as real character
+			     *
+			     * -1: MB_INVALID: Assume this is
+			     *     a single character as we do
+			     *     elsewhere in the code.
+			     *
+			     * -2: MB_INCOMPLETE: We're not waiting
+			     *     for input on this occasion, so
+			     *     just treat this as invalid.
+			     */
+			    if (chars <= 0)
 				chars = 1;
-			    }
 			}
 			else	/* use the non-multibyte code below */
 #endif
@@ -5259,7 +5423,7 @@ bin_print(char *name, char **args, Options ops, int func)
 		break;
 	    case 'q':
 		stringval = curarg ?
-		    quotestring(metafy(curarg, curlen, META_USEHEAP),
+		    quotestring(metafy(curarg, curlen, META_NOALLOC),
 				QT_BACKSLASH_SHOWNULL) : &nullstr;
 		*d = 's';
 		print_val(unmetafy(stringval, &curlen));
@@ -5313,9 +5477,9 @@ bin_print(char *name, char **args, Options ops, int func)
 		    else
 			cc = WEOF;
 		    if (cc == WEOF)
-			cc = (curlen > 1) ? STOUC(curarg[1]) : 0;
+			cc = (curlen > 1) ? (unsigned char) (curarg[1]) : 0;
 #else
-		    cc = (curlen > 1) ? STOUC(curarg[1]) : 0;
+		    cc = (curlen > 1) ? (unsigned char) (curarg[1]) : 0;
 #endif
 		    if (type == 2) {
 			doubleval = cc;
@@ -5331,7 +5495,7 @@ bin_print(char *name, char **args, Options ops, int func)
  		    	*d++ = 'l';
 #endif
 		    	*d++ = 'l', *d++ = *c, *d = '\0';
-			zlongval = (curarg) ? mathevali(curarg) : 0;
+			zlongval = (curarg) ? mathevali(metafy(curarg, curlen, META_NOALLOC)) : 0;
 			if (errflag) {
 			    zlongval = 0;
 			    errflag &= ~ERRFLAG_ERROR;
@@ -5382,7 +5546,7 @@ bin_print(char *name, char **args, Options ops, int func)
 			if (!curarg)
 			    zulongval = (zulong)0;
 			else if (!zstrtoul_underscore(curarg, &zulongval))
-			    zulongval = mathevali(curarg);
+			    zulongval = mathevali(metafy(curarg, curlen, META_NOALLOC));
 			if (errflag) {
 			    zulongval = 0;
 			    errflag &= ~ERRFLAG_ERROR;
@@ -6282,11 +6446,12 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
     long izle_timeout = 0;
 #ifdef MULTIBYTE_SUPPORT
     wchar_t delim = L'\n', wc;
+    int rawbyte = 0;
     mbstate_t mbs;
     char *laststart;
     size_t ret;
 #else
-    char delim = '\n';
+    int delim = '\n';
 #endif
 
     if (OPT_HASARG(ops,c='k')) {
@@ -6373,9 +6538,10 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
     } else
 	readfd = izle = 0;
 
-    if (OPT_ISSET(ops,'s') && SHTTY != -1) {
+    if (OPT_ISSET(ops,'s') && isatty(readfd)) {
 	struct ttyinfo ti;
-	gettyinfo(&ti);
+	memset(&ti, 0, sizeof(struct ttyinfo));
+	fdgettyinfo(readfd, &ti);
 	saveti = ti;
 	resettty = 1;
 #ifdef HAS_TIO
@@ -6383,7 +6549,7 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 #else
 	ti.sgttyb.sg_flags &= ~ECHO;
 #endif
-	settyinfo(&ti);
+	fdsettyinfo(readfd, &ti);
     }
 
     /* handle prompt */
@@ -6412,15 +6578,18 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 	    wi = WEOF;
 	if (wi != WEOF)
 	    delim = (wchar_t)wi;
-	else
-	    delim = (wchar_t)((delimstr[0] == Meta) ?
+	else {
+	    delim = (wchar_t) (unsigned char) ((delimstr[0] == Meta) ?
 			      delimstr[1] ^ 32 : delimstr[0]);
+	    rawbyte = 1;
+	}
 #else
-        delim = (delimstr[0] == Meta) ? delimstr[1] ^ 32 : delimstr[0];
+        delim = (unsigned char) ((delimstr[0] == Meta) ?
+			delimstr[1] ^ 32 : delimstr[0]);
 #endif
-	if (SHTTY != -1) {
+	if (isatty(readfd)) {
 	    struct ttyinfo ti;
-	    gettyinfo(&ti);
+	    fdgettyinfo(readfd, &ti);
 	    if (! resettty) {
 	      saveti = ti;
 	      resettty = 1;
@@ -6432,7 +6601,7 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 #else
 	    ti.sgttyb.sg_flags |= CBREAK;
 #endif
-	    settyinfo(&ti);
+	    fdsettyinfo(readfd, &ti);
 	}
     }
     if (OPT_ISSET(ops,'t')) {
@@ -6467,10 +6636,11 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 			   timeout)) {
 		if (keys && !zleactive && !isem)
 		    settyinfo(&shttyinfo);
-		else if (resettty && SHTTY != -1)
-		    settyinfo(&saveti);
+		else if (resettty)
+		    fdsettyinfo(readfd, &saveti);
 		if (haso) {
-		    fclose(shout);
+		    if (shout)
+			fclose(shout);
 		    shout = oshout;
 		    SHTTY = -1;
 		}
@@ -6578,8 +6748,8 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 	    /* dispose of result appropriately, etc. */
 	    if (isem)
 		while (val > 0 && read(SHTTY, &d, 1) == 1 && d != '\n');
-	    else {
-		settyinfo(&shttyinfo);
+	    else if (resettty) {
+		fdsettyinfo(readfd, &saveti);
 		resettty = 0;
 	    }
 	    if (haso) {
@@ -6608,8 +6778,8 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 	    setsparam(reply, metafy(buf, bptr - buf, META_REALLOC));
 	else
 	    zfree(buf, bptr - buf + 1);
-	if (resettty && SHTTY != -1)
-	    settyinfo(&saveti);
+	if (resettty)
+	    fdsettyinfo(readfd, &saveti);
 	return eof;
     }
 
@@ -6685,7 +6855,7 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 		    continue;
 		first = 0;
 	    }
-	    if (imeta(STOUC(*bptr))) {
+	    if (imeta((unsigned char) *bptr)) {
 		bptr[1] = bptr[0] ^ 32;
 		bptr[0] = Meta;
 		bptr += 2;
@@ -6819,8 +6989,8 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 	    *pp++ = NULL;
 	    setaparam(reply, p);
 	}
-	if (resettty && SHTTY != -1)
-	    settyinfo(&saveti);
+	if (resettty)
+	    fdsettyinfo(readfd, &saveti);
 	return c == EOF;
     }
     buf = bptr = (char *)zalloc(bsiz = 64);
@@ -6841,7 +7011,7 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 		break;
 	    }
 	    *bptr = (char)c;
-	    if (isset(MULTIBYTE)) {
+	    if (isset(MULTIBYTE) && !rawbyte) {
 		ret = mbrtowc(&wc, bptr, 1, &mbs);
 		if (!ret)	/* NULL */
 		    ret = 1;
@@ -6878,7 +7048,7 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 		if (bslash)
 		    continue;
 	    }
-	    if (imeta(STOUC(*bptr))) {
+	    if (imeta((unsigned char) *bptr)) {
 		bptr[1] = bptr[0] ^ 32;
 		bptr[0] = Meta;
 		bptr += 2;
@@ -6948,8 +7118,8 @@ bin_read(char *name, char **args, Options ops, UNUSED(int func))
 	    break;
     }
     *bptr = '\0';
-    if (resettty && SHTTY != -1)
-	settyinfo(&saveti);
+    if (resettty)
+	fdsettyinfo(readfd, &saveti);
     /* final assignment of reply, etc. */
     if (OPT_ISSET(ops,'e') || OPT_ISSET(ops,'E')) {
 	zputs(buf, stdout);
@@ -7000,14 +7170,14 @@ zread(int izle, int *readchar, long izle_timeout)
 	   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);
+	    return zbuf++, (unsigned char) (*zbuf++ ^ 32);
 	else
-	    return (*zbuf) ? STOUC(*zbuf++) : EOF;
+	    return (*zbuf) ? (unsigned char) *zbuf++ : EOF;
     }
     if (*readchar >= 0) {
 	cc = *readchar;
 	*readchar = -1;
-	return STOUC(cc);
+	return (unsigned char) cc;
     }
     for (;;) {
 	/* read a character from readfd */
@@ -7015,7 +7185,7 @@ zread(int izle, int *readchar, long izle_timeout)
 	switch (ret) {
 	case 1:
 	    /* return the character read */
-	    return STOUC(cc);
+	    return (unsigned char) cc;
 	case -1:
 #if defined(EAGAIN) || defined(EWOULDBLOCK)
 	    if (!retry && readfd == 0 && (
@@ -7204,7 +7374,7 @@ bin_trap(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))
     /* If given no arguments, list all currently-set traps */
     if (!*argv) {
 	queue_signals();
-	for (sig = 0; sig < VSIGCOUNT; sig++) {
+	for (sig = 0; sig < TRAPCOUNT; sig++) {
 	    if (sigtrapped[sig] & ZSIG_FUNC) {
 		HashNode hn;
 
@@ -7230,13 +7400,13 @@ bin_trap(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))
 
     /* If we have a signal number, unset the specified *
      * signals.  With only -, remove all traps.        */
-    if ((getsignum(*argv) != -1) || (!strcmp(*argv, "-") && argv++)) {
+    if ((getsigidx(*argv) != -1) || (!strcmp(*argv, "-") && argv++)) {
 	if (!*argv) {
-	    for (sig = 0; sig < VSIGCOUNT; sig++)
+	    for (sig = 0; sig < TRAPCOUNT; sig++)
 		unsettrap(sig);
 	} else {
 	    for (; *argv; argv++) {
-		sig = getsignum(*argv);
+		sig = getsigidx(*argv);
 		if (sig == -1) {
 		    zwarnnam(name, "undefined signal: %s", *argv);
 		    break;
@@ -7261,12 +7431,12 @@ bin_trap(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))
 	Eprog t;
 	int flags;
 
-	sig = getsignum(*argv);
+	sig = getsigidx(*argv);
 	if (sig == -1) {
 	    zwarnnam(name, "undefined signal: %s", *argv);
 	    break;
 	}
-	if (idigit(**argv) ||
+	if (idigit(**argv) || (sig >= VSIGCOUNT) ||
 	    !strcmp(sigs[sig], *argv) ||
 	    (!strncmp("SIG", *argv, 3) && !strcmp(sigs[sig], *argv+3))) {
 	    /* The signal was specified by number or by canonical name (with
diff --git a/Src/compat.c b/Src/compat.c
index 817bb4aaf..8b31ad9f4 100644
--- a/Src/compat.c
+++ b/Src/compat.c
@@ -342,36 +342,69 @@ zopenmax(void)
 mod_export char *
 zgetdir(struct dirsav *d)
 {
-    char nbuf[PATH_MAX+3];
     char *buf;
+#if defined(HAVE_GETCWD) || defined(__CYGWIN__)
+    char *cwdbuf;
+#endif
+#if defined(USE_GETCWD) || defined(__CYGWIN__)
+#ifdef GETCWD_CALLS_MALLOC
+    if ((cwdbuf = getcwd(NULL, 0))) {
+	buf = dupstring(cwdbuf);
+	free(cwdbuf);
+    } else
+	buf = NULL;
+#else
+    cwdbuf = zalloc(PATH_MAX+1);
+    if ((buf = getcwd(cwdbuf, PATH_MAX)))
+	buf = dupstring(buf);
+    zfree(cwdbuf, PATH_MAX+1);
+#endif /* GETCWD_CALLS_MALLOC */
+    if (d && buf)
+	return d->dirname = ztrdup(buf);
+    else
+	return buf;
+#else /* !USE_GETCWD && !__CYGWIN__ */
     int bufsiz, pos;
-    struct stat sbuf;
-    ino_t pino;
-    dev_t pdev;
-#if !defined(__CYGWIN__) && !defined(USE_GETCWD)
+    char nbuf[PATH_MAX+3];
     struct dirent *de;
     DIR *dir;
-    dev_t dev;
-    ino_t ino;
+    struct stat sbuf;
+    ino_t pino, ino;
+    dev_t pdev, dev;
     int len;
-#endif
 
+    strcpy(nbuf, "../");
+    if (stat(".", &sbuf) == 0) {
+	/* Record the initial inode and device */
+	pino = sbuf.st_ino;
+	pdev = sbuf.st_dev;
+	if (d)
+	    d->ino = pino, d->dev = pdev;
+    }
+#ifdef HAVE_GETCWD
+    else {
+#ifdef GETCWD_CALLS_MALLOC
+	if ((cwdbuf = getcwd(NULL, 0))) {
+	    buf = dupstring(cwdbuf);
+	    free(cwdbuf);
+	} else
+	    buf = NULL;
+#else
+	cwdbuf = zalloc(PATH_MAX+1);
+	if ((buf = getcwd(cwdbuf, PATH_MAX)))
+	    buf = dupstring(buf);
+	zfree(cwdbuf, PATH_MAX+1);
+#endif /* GETCWD_CALLS_MALLOC */
+	return buf;    /* NULL when stat() and getcwd() both failed */
+    }
+#endif
+    /* stat() succeeded */
     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
+    if (!d)
 #endif
 	holdintr();
 
@@ -487,18 +520,6 @@ zgetdir(struct dirsav *d)
 	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
 
     /*
@@ -526,23 +547,6 @@ mod_export 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 == '\0')
diff --git a/Src/exec.c b/Src/exec.c
index f2911807c..e955e85df 100644
--- a/Src/exec.c
+++ b/Src/exec.c
@@ -56,14 +56,56 @@ struct funcsave {
 typedef struct funcsave *Funcsave;
 
 /*
- * used to suppress ERREXIT and trapping of SIGZERR, SIGEXIT.
+ * Used to suppress ERREXIT and trapping of SIGZERR, SIGEXIT in the
+ * evaluation of sub-commands of the command under evaluation. The
+ * variable must be updated before the evaluation of the sub-commands
+ * starts and restored to its previous state right after that
+ * evaluation ends. The variable is read and acted upon in execlist.
+ *
+ * A good usage example can be found in execwhile in loop.c, which
+ * evaluates while statements. The variable is updated to disable
+ * ERREXIT just before evaluating the while's condition and restored
+ * to its previous state right after the evaluation of the condition.
+ *
  * Bits from noerrexit_bits.
  */
 
 /**/
 int noerrexit;
 
-/* used to suppress ERREXIT or ERRRETURN for one occurrence: 0 or 1 */
+/*
+ * Used to suppress ERREXIT and ERRRETURN for the command under
+ * evaluation.  The variable must be enabled (set to 1) at the very
+ * end of the evaluation of the command. It must come after the
+ * evaluation of any sub-commands of the command under evaluation. The
+ * variable is read and acted upon in execlist, which also takes care
+ * of initialising and resetting it to 0.
+ *
+ * Unlike the variable noerrexit, whose state applies to the
+ * evaluation of whole sub-commands (and their direct and indirect
+ * sub-commands), the scope of the variable this_noerrexit is much
+ * more localized. ERREXIT and ERRRETURN are triggered at the end of
+ * the function execlist after the evaluation of some or all of the
+ * list's sub-commands. The role of the variable this_noerrexit is to
+ * give to the functions evaluating the list's sub-commands the
+ * possibility to tell the calling execlist not to trigger ERREXIT and
+ * ERRRETURN. In other words, the variable acts as an additional
+ * return value between the called evaluation functions and the
+ * calling execlist. For that reason the variable must always be set
+ * as late as possible and in particular after any sub-command
+ * evaluation. If the variable is set before the evaluation of a
+ * sub-command, if may affect the wrong execlist, if the sub-command
+ * evaluation involves another execlist call, and/or the variable may
+ * get modified by the sub-command evaluation and thus wouldn't return
+ * the desired value to the calling execlist.
+ *
+ * Good usage examples can be found in the exec functions in loop.c,
+ * which evaluate compound commands. The variable is enabled right
+ * before returning from the functions, after all the sub-commands of
+ * the compound commands have already been evaluated.
+ *
+ * 0 or 1
+ */
 
 /**/
 int this_noerrexit;
@@ -225,7 +267,7 @@ static char *blank_env[] = { NULL };
 
 /* Execution functions. */
 
-static int (*execfuncs[WC_COUNT-WC_CURSH]) _((Estate, int)) = {
+static int (*execfuncs[WC_COUNT-WC_CURSH]) (Estate, int) = {
     execcursh, exectime, NULL /* execfuncdef handled specially */,
     execfor, execselect,
     execwhile, execrepeat, execcase, execif, execcond,
@@ -477,7 +519,7 @@ zexecve(char *pth, char **argv, char **newenvp)
     if (*pth == '/')
 	strcpy(buf + 2, pth);
     else
-	sprintf(buf + 2, "%s/%s", pwd, pth);
+	sprintf(buf + 2, "%s/%s", unmeta(pwd), pth);
     zputenv(buf);
 #ifndef FD_CLOEXEC
     closedumps();
@@ -509,7 +551,7 @@ zexecve(char *pth, char **argv, char **newenvp)
 			    break;
 		    if (t0 == ct)
 			zerr("%s: bad interpreter: %s: %e", pth,
-			     execvebuf + 2, eno);
+			     metafy(execvebuf + 2, -1, META_STATIC), eno);
 		    else {
 			while (inblank(execvebuf[t0]))
 			    execvebuf[t0--] = '\0';
@@ -532,8 +574,8 @@ zexecve(char *pth, char **argv, char **newenvp)
 				    execve(pprog, argv - 2, newenvp);
 				}
 			    }
-			    zerr("%s: bad interpreter: %s: %e", pth, ptr2,
-				 eno);
+			    zerr("%s: bad interpreter: %s: %e", pth,
+				 metafy(ptr2, -1, META_STATIC), eno);
 			} else if (*ptr) {
 			    *ptr = '\0';
 			    argv[-2] = ptr2;
@@ -561,7 +603,7 @@ zexecve(char *pth, char **argv, char **newenvp)
                         isbinary = 1;
                         hasletter = 0;
                         for (ptr = execvebuf; ptr < ptr2; ptr++) {
-                            if (islower(STOUC(*ptr)) || *ptr == '$' || *ptr == '`')
+			    if (islower((unsigned char) *ptr) || *ptr == '$' || *ptr == '`')
                                 hasletter = 1;
                             if (hasletter && *ptr == '\n') {
                                 isbinary = 0;
@@ -570,9 +612,22 @@ zexecve(char *pth, char **argv, char **newenvp)
                         }
                     }
 		    if (!isbinary) {
-			argv[-1] = "sh";
+		        char** args = argv;
+			if (argv[0][0] == '-' || argv[0][0] == '+') {
+			    /*
+			     * guard against +foo or -bar script paths being
+			     * taken as options. POSIX says the script path
+			     * must be passed as an *operand*. "--" would also
+			     * make sure the next argument is treated as an
+			     * operand with POSIX compliant sh implementations
+			     * but "-" is more portable (to the Bourne shell in
+			     * particular) and shorter.
+			     */
+			    *--args = "-";
+			}
+			*--args = "sh";
 			winch_unblock();
-			execve("/bin/sh", argv - 1, newenvp);
+			execve("/bin/sh", args, newenvp);
 		    }
 		}
 	    } else
@@ -1373,7 +1428,7 @@ execlist(Estate state, int dont_change_job, int exiting)
 	    int oerrexit_opt = opts[ERREXIT];
 	    Param pm;
 	    opts[ERREXIT] = 0;
-	    noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
+	    noerrexit |= NOERREXIT_EXIT | NOERREXIT_RETURN;
 	    if (ltype & Z_SIMPLE) /* skip the line number */
 		pc2++;
 	    pm = assignsparam("ZSH_DEBUG_CMD",
@@ -1424,17 +1479,13 @@ execlist(Estate state, int dont_change_job, int exiting)
 	    goto sublist_done;
 	}
 	while (wc_code(code) == WC_SUBLIST) {
-	    int isend = (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END);
+	    this_noerrexit = 0;
+	    int isandor = WC_SUBLIST_TYPE(code) != WC_SUBLIST_END;
+	    int isnot = WC_SUBLIST_FLAGS(code) & WC_SUBLIST_NOT;
 	    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 ! <list-of-shell-commands> */
-		noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
-	    }
+	    /* suppress errexit for commands before && and || and after ! */
+	    if (isandor || isnot)
+		noerrexit |= NOERREXIT_EXIT | NOERREXIT_RETURN;
 	    switch (WC_SUBLIST_TYPE(code)) {
 	    case WC_SUBLIST_END:
 		/* End of sublist; just execute, ignoring status. */
@@ -1443,6 +1494,9 @@ execlist(Estate state, int dont_change_job, int exiting)
 		else
 		    execpline(state, code, ltype, (ltype & Z_END) && exiting);
 		state->pc = next;
+		/* suppress errexit for the command "! ..." */
+		if (isnot)
+		  this_noerrexit = 1;
 		goto sublist_done;
 		break;
 	    case WC_SUBLIST_AND:
@@ -1450,7 +1504,7 @@ execlist(Estate state, int dont_change_job, int exiting)
 		 * we find a sublist followed by ORNEXT.                   */
 		if ((ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ?
 			    execsimple(state) :
-			    execpline(state, code, Z_SYNC, 0)))) {
+			    execpline(state, code, Z_SYNC, 0))) || breaks) {
 		    state->pc = next;
 		    code = *state->pc++;
 		    next = state->pc + WC_SUBLIST_SKIP(code);
@@ -1483,7 +1537,7 @@ execlist(Estate state, int dont_change_job, int exiting)
 		 * we find a sublist followed by ANDNEXT.              */
 		if (!(ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ?
 			     execsimple(state) :
-			     execpline(state, code, Z_SYNC, 0)))) {
+			     execpline(state, code, Z_SYNC, 0))) || breaks) {
 		    state->pc = next;
 		    code = *state->pc++;
 		    next = state->pc + WC_SUBLIST_SKIP(code);
@@ -1518,14 +1572,7 @@ execlist(Estate state, int dont_change_job, int exiting)
 	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;
+	noerrexit = oldnoerrexit;
 
 	if (sigtrapped[SIGDEBUG] && !isset(DEBUGBEFORECMD) && !donedebug) {
 	    /*
@@ -1534,7 +1581,7 @@ sublist_done:
 	     */
 	    int oerrexit_opt = opts[ERREXIT];
 	    opts[ERREXIT] = 0;
-	    noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
+	    noerrexit |= NOERREXIT_EXIT | NOERREXIT_RETURN;
 	    exiting = donetrap;
 	    ret = lastval;
 	    dotrap(SIGDEBUG);
@@ -1564,6 +1611,7 @@ sublist_done:
 			       (isset(ERRRETURN) && !errreturn)) &&
 		    !(noerrexit & NOERREXIT_EXIT);
 		if (errexit) {
+		    errflag = 0;
 		    if (sigtrapped[SIGEXIT])
 			dotrap(SIGEXIT);
 		    if (mypid != getpid())
@@ -1581,6 +1629,7 @@ sublist_done:
 	    break;
 	code = *state->pc++;
     }
+    this_noerrexit = 0;
     pline_level = old_pline_level;
     list_pipe = old_list_pipe;
     list_pipe_job = old_list_pipe_job;
@@ -1595,9 +1644,12 @@ sublist_done:
 	thisjob = cj;
 
     if (exiting && sigtrapped[SIGEXIT]) {
+	int eflag = errflag;
+	errflag = 0;	/* Clear the context for trap */
 	dotrap(SIGEXIT);
 	/* Make sure this doesn't get executed again. */
 	sigtrapped[SIGEXIT] = 0;
+	errflag = eflag;
     }
 
     unqueue_signals();
@@ -1899,8 +1951,12 @@ execpline(Estate state, wordcode slcode, int how, int last1)
 			break;
 		    }
 		}
-		else if (subsh && jn->stat & STAT_STOPPED)
-		    thisjob = newjob;
+		else if (subsh && jn->stat & STAT_STOPPED) {
+		    if (thisjob == newjob)
+			makerunning(jn);
+		    else
+			thisjob = newjob;
+		}
 		else
 		    break;
 	    }
@@ -1922,7 +1978,7 @@ execpline(Estate state, wordcode slcode, int how, int last1)
 	}
 	else
 	    unqueue_signals();
-	if ((slflags & WC_SUBLIST_NOT) && !errflag)
+	if ((slflags & WC_SUBLIST_NOT) && !errflag && !retflag)
 	    lastval = !lastval;
     }
     if (!pline_level)
@@ -2247,6 +2303,8 @@ closemn(struct multio **mfds, int fd, int type)
 	    return;
 	}
 	/* pid == 0 */
+	opts[INTERACTIVE] = 0;
+	dont_queue_signals();
 	child_unblock();
 	closeallelse(mn);
 	if (mn->rflag) {
@@ -2259,19 +2317,21 @@ closemn(struct multio **mfds, int fd, int type)
 			break;
 		}
 		for (i = 0; i < mn->ct; i++)
-		    write_loop(mn->fds[i], buf, len);
+		    if (write_loop(mn->fds[i], buf, len) < 0)
+			break;
 	    }
 	} 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)
+			if (errno == EINTR && !isatty(mn->fds[i]))
 			    continue;
 			else
 			    break;
 		    }
-		    write_loop(mn->pipe, buf, len);
+		    if (write_loop(mn->pipe, buf, len) < 0)
+			break;
 		}
 	}
 	_exit(0);
@@ -2345,7 +2405,7 @@ addfd(int forked, int *save, struct multio **mfds, int fd1, int fd2, int rflag,
 	/* fd will be over 10, don't touch mfds */
 	fd1 = movefd(fd2);
 	if (fd1 == -1) {
-	    zerr("cannot moved fd %d: %e", fd2, errno);
+	    zerr("cannot move fd %d: %e", fd2, errno);
 	    return;
 	} else {
 	    fdtable[fd1] = FDT_EXTERNAL;
@@ -2544,6 +2604,17 @@ addvars(Estate state, Wordcode pc, int addflags)
 		opts[ALLEXPORT] = allexp;
 	    } else
 	    	pm = assignsparam(name, val, myflags);
+	    if (!pm) {
+		lastval = 1;
+		/*
+		 * This is cheating but some exec functions propagate
+		 * assignment status only from command substitution
+		 *
+		 * zerr("%s: assignment failed", name);
+		 */
+		if (!cmdoutval)
+		    cmdoutval = 1;
+	    }
 	    if (errflag) {
 		state->pc = opc;
 		return;
@@ -2568,7 +2639,16 @@ addvars(Estate state, Wordcode pc, int addflags)
 	    }
 	    fprintf(xtrerr, ") ");
 	}
-	assignaparam(name, arr, myflags);
+	if (!assignaparam(name, arr, myflags)) {
+	    lastval = 1;
+	    /*
+	     * See above RE "cheating"
+	     *
+	     * zerr("%s: array assignment failed", name);
+	     */
+	    if (!cmdoutval)
+		cmdoutval = 1;
+	}
 	if (errflag) {
 	    state->pc = opc;
 	    return;
@@ -3200,10 +3280,6 @@ execcmd_exec(Estate state, Execcmd_params eparams,
     } 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
@@ -3712,7 +3788,7 @@ execcmd_exec(Estate state, Execcmd_params eparams,
 		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 &&
+		if (nullexec == 1 && fn->fd1 == 0 && !fn->varid &&
 		    isset(SHINSTDIN) && interact && !zleactive)
 		    init_io(NULL);
 		break;
@@ -4301,10 +4377,13 @@ execcmd_exec(Estate state, Execcmd_params eparams,
 	}
     }
     if (newxtrerr) {
+	int eno = errno;
 	fil = fileno(newxtrerr);
 	fclose(newxtrerr);
 	xtrerr = oxtrerr;
+	/* Call zclose() to clean up internal tables, ignore EBADF */
 	zclose(fil);
+	errno = eno;
     }
 
     zsfree(STTYval);
@@ -4636,6 +4715,9 @@ getoutput(char *cmd, int qt)
     if (!prog)
 	return NULL;
 
+    if (!isset(EXECOPT))
+	return newlinklist();
+
     if ((s = simple_redir_name(prog, REDIR_READ))) {
 	/* $(< word) */
 	int stream;
@@ -4852,7 +4934,6 @@ getoutputfile(char *cmd, char **eptr)
 
     if ((fd = open(nam, O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0600)) < 0) {
 	zerr("process substitution failed: %e", errno);
-	free(nam);
 	if (!s)
 	    child_unblock();
 	return NULL;
@@ -5052,7 +5133,7 @@ getpipe(char *cmd, int nullexec)
 	procsubstpid = pid;
 	return pipes[!out];
     }
-    entersubsh(ESUB_ASYNC|ESUB_PGRP, NULL);
+    entersubsh(ESUB_ASYNC|ESUB_PGRP|ESUB_NOMONITOR, NULL);
     redup(pipes[out], out);
     closem(FDT_UNUSED, 0);	/* this closes pipes[!out] as well */
     cmdpush(CS_CMDSUBST);
@@ -5366,7 +5447,7 @@ execfuncdef(Estate state, Eprog redir_prog)
 	} else {
 	    /* is this shell function a signal trap? */
 	    if (!strncmp(s, "TRAP", 4) &&
-		(signum = getsignum(s + 4)) != -1) {
+		(signum = getsigidx(s + 4)) != -1) {
 		if (settrap(signum, NULL, ZSIG_FUNC)) {
 		    freeeprog(shf->funcdef);
 		    dircache_set(&shf->filename, NULL);
@@ -5734,12 +5815,25 @@ doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
     char *name = shfunc->node.nam;
     int flags = shfunc->node.flags;
     char *fname = dupstring(name);
-    Eprog prog;
+    Eprog prog, marked_prog;
     static int oflags;
     static int funcdepth;
     Heap funcheap;
 
     queue_signals();	/* Lots of memory and global state changes coming */
+    /*
+     * In case this is a special function such as a trap, mark it
+     * as in use right now, so it doesn't get freed early.  The
+     * worst that can happen is this hangs around in memory a little
+     * longer than strictly needed.
+     *
+     * Classic example of this happening is running TRAPEXIT directly.
+     *
+     * Because the shell function's contents may change, we'll ensure
+     * we use a consistent structure for use / free.
+     */
+    marked_prog = shfunc->funcdef;
+    useeprog(marked_prog);
 
     NEWHEAPS(funcheap) {
 	/*
@@ -5773,6 +5867,22 @@ doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
 	    memcpy(funcsave->pipestats, pipestats, bytes);
 	}
 
+	if (!strcmp(fname, "TRAPEXIT")) {
+	    /*
+	     * If we are executing TRAPEXIT directly, starttrapscope()
+	     * will pull the rug out from under us to ensure the
+	     * exit trap isn't run inside the function.  We just need
+	     * the information locally here, so copy it on the heap.
+	     *
+	     * The funcdef is separately handled by reference counting.
+	     */
+	    Shfunc shcopy = (Shfunc)zhalloc(sizeof(struct shfunc));
+	    memcpy(shcopy, shfunc, sizeof(struct shfunc));
+	    shcopy->node.nam = dupstring(shfunc->node.nam);
+	    shfunc = shcopy;
+	    name = shfunc->node.nam;
+	}
+
 	starttrapscope();
 	startpatternscope();
 
@@ -5897,6 +6007,8 @@ doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
 	funcsave->fstack.filename = getshfuncfile(shfunc);
 
 	prog = shfunc->funcdef;
+	DPUTS1(!prog->nref, "function definition %s has zero reference count",
+	       (fname && *fname) ? fname : "<anon>");
 	if (prog->flags & EF_RUN) {
 	    Shfunc shf;
 
@@ -5925,15 +6037,6 @@ doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
 	     * 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);
@@ -5961,11 +6064,23 @@ doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
 	    emulation = funcsave->emulation;
 	    sticky = funcsave->sticky;
 	} else if (isset(LOCALOPTIONS)) {
+	    /* we need to call inittyptab() if these options change */
+	    int init_typtab =
+#ifdef MULTIBYTE_SUPPORT
+			funcsave->opts[MULTIBYTE] != opts[MULTIBYTE] ||
+#endif
+			funcsave->opts[BANGHIST] != opts[BANGHIST] ||
+			funcsave->opts[SHINSTDIN] != opts[SHINSTDIN];
+	    /* take care of SUNKEYBOARDHACK but not of EMACS/VI */
+	    if (funcsave->opts[SUNKEYBOARDHACK] != opts[SUNKEYBOARDHACK])
+		keyboardhackchar = funcsave->opts[SUNKEYBOARDHACK] ? '`' : '\0';
 	    /* 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;
+	    if (init_typtab)
+		inittyptab();
 	} else {
 	    /* just restore a couple. */
 	    opts[XTRACE] = funcsave->opts[XTRACE];
@@ -5998,6 +6113,7 @@ doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
 	}
     } OLDHEAPS;
 
+    freeeprog(marked_prog);
     unqueue_signals();
 
     /*
diff --git a/Src/glob.c b/Src/glob.c
index 400be12d5..3e34f708e 100644
--- a/Src/glob.c
+++ b/Src/glob.c
@@ -133,7 +133,7 @@ typedef struct stat *Statptr;	 /* This makes the Ultrix compiler happy.  Go figu
 #define TT_TERABYTES 5
 
 
-typedef int (*TestMatchFunc) _((char *, struct stat *, off_t, char *));
+typedef int (*TestMatchFunc) (char *, struct stat *, off_t, char *);
 
 struct qual {
     struct qual *next;		/* Next qualifier, must match                */
@@ -1264,7 +1264,7 @@ zglob(LinkList list, LinkNode np, int nountok)
 	int sense, qualsfound;
 	off_t data;
 	char *sdata, *newcolonmod, *ptr;
-	int (*func) _((char *, Statptr, off_t, char *));
+	int (*func) (char *, Statptr, off_t, char *);
 
 	/*
 	 * Initialise state variables for current file pattern.
@@ -1310,14 +1310,15 @@ zglob(LinkList list, LinkNode np, int nountok)
 	    if (*ptr == Dash)
 		*ptr = '-';
 	while (*s && !newcolonmod) {
-	    func = (int (*) _((char *, Statptr, off_t, char *)))0;
+	    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;
+		    if (qo)
+			qo->or = qn;
 		    qo = qn;
 		    qualorct++;
 		    qualct = 0;
@@ -1481,7 +1482,7 @@ zglob(LinkList list, LinkNode np, int nountok)
 			    sav = *tt;
 			    *tt = '\0';
 
-			    if ((pw = getpwnam(s + arglen)))
+			    if ((pw = getpwnam(unmeta(s + arglen))))
 				data = pw->pw_uid;
 			    else {
 				zerr("unknown username '%s'", s + arglen);
@@ -1960,7 +1961,7 @@ zglob(LinkList list, LinkNode np, int nountok)
 	/* 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);
+	      (int (*) (const void *, const void *)) gmatchcmp);
     }
 
     if (first < 0) {
@@ -2418,11 +2419,11 @@ xpandbraces(LinkList list, LinkNode *np)
 	memset(ccl, 0, sizeof(ccl) / sizeof(ccl[0]));
 	for (p = str + 1; p < str2;) {
 	    if (itok(c1 = *p++))
-		c1 = ztokens[c1 - STOUC(Pound)];
+		c1 = ztokens[c1 - (unsigned char) Pound];
 	    if ((char) c1 == Meta)
 		c1 = 32 ^ *p++;
 	    if (itok(c2 = *p))
-		c2 = ztokens[c2 - STOUC(Pound)];
+		c2 = ztokens[c2 - (unsigned char) Pound];
 	    if ((char) c2 == Meta)
 		c2 = 32 ^ p[1];
 	    if (IS_DASH((char)c1) && lastch >= 0 &&
diff --git a/Src/hashtable.c b/Src/hashtable.c
index bb165505e..96675a393 100644
--- a/Src/hashtable.c
+++ b/Src/hashtable.c
@@ -836,10 +836,10 @@ static HashNode
 removeshfuncnode(UNUSED(HashTable ht), const char *nam)
 {
     HashNode hn;
-    int signum;
+    int sigidx;
 
-    if (!strncmp(nam, "TRAP", 4) && (signum = getsignum(nam + 4)) != -1)
-	hn = removetrap(signum);
+    if (!strncmp(nam, "TRAP", 4) && (sigidx = getsigidx(nam + 4)) != -1)
+	hn = removetrap(sigidx);
     else
 	hn = removehashnode(shfunctab, nam);
 
@@ -856,10 +856,10 @@ 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);
+	int sigidx = getsigidx(hn->nam + 4);
+	if (sigidx != -1) {
+	    sigtrapped[sigidx] &= ~ZSIG_FUNC;
+	    unsettrap(sigidx);
 	}
     }
 }
@@ -876,9 +876,9 @@ enableshfuncnode(HashNode hn, UNUSED(int flags))
 
     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);
+	int sigidx = getsigidx(shf->node.nam + 4);
+	if (sigidx != -1) {
+	    settrap(sigidx, NULL, ZSIG_FUNC);
 	}
     }
 }
@@ -1397,6 +1397,14 @@ histstrcmp(const char *str1, const char *str2)
 {
     while (inblank(*str1)) str1++;
     while (inblank(*str2)) str2++;
+
+    /* If insignificant whitespace has already been eliminated,
+     * there is no reason to expend similar effort here.  Also,
+     * this is more accurate in cases of quoted whitespace.
+     */
+    if (isset(HISTREDUCEBLANKS))
+	return strcmp(str1, str2);
+
     while (*str1 && *str2) {
 	if (inblank(*str1)) {
 	    if (!inblank(*str2))
diff --git a/Src/hist.c b/Src/hist.c
index bff0abe61..1a00c30ed 100644
--- a/Src/hist.c
+++ b/Src/hist.c
@@ -34,25 +34,25 @@
  * word control. */
 
 /**/
-mod_export int (*hgetc) _((void));
+mod_export int (*hgetc) (void);
 
 /**/
-void (*hungetc) _((int));
+void (*hungetc) (int);
 
 /**/
-void (*hwaddc) _((int));
+void (*hwaddc) (int);
 
 /**/
-void (*hwbegin) _((int));
+void (*hwbegin) (int);
 
 /**/
-void (*hwabort) _((void));
+void (*hwabort) (void);
 
 /**/
-void (*hwend) _((void));
+void (*hwend) (void);
 
 /**/
-void (*addtoline) _((int));
+void (*addtoline) (int);
 
 /* != 0 means history substitution is turned off */
  
@@ -163,6 +163,11 @@ char *hsubl;
 /**/
 char *hsubr;
  
+/* state of histsubstpattern at last substitution */
+
+/**/
+int hsubpatopt;
+
 /* pointer into the history line */
  
 /**/
@@ -624,7 +629,7 @@ histsubchar(int c)
 	    return substfailed();
 	if (!hsubl)
 	    return -1;
-	if (subst(&sline, hsubl, hsubr, gbal))
+	if (subst(&sline, hsubl, hsubr, gbal, 0))
 	    return substfailed();
     } else {
 	/* Line doesn't begin ^foo^bar */
@@ -831,7 +836,7 @@ histsubchar(int c)
 	    if ((c = ingetc()) == 'g') {
 		gbal = 1;
 		c = ingetc();
-		if (c != 's' && c != '&') {
+		if (c != 's' && c != 'S' && c != '&') {
 		    zerr("'s' or '&' modifier expected after 'g'");
 		    return -1;
 		}
@@ -891,11 +896,13 @@ histsubchar(int c)
 		}
 		break;
 	    case 's':
+	    case 'S':
+		hsubpatopt = (c == 'S');
 		if (getsubsargs(sline, &gbal, &cflag))
 		    return -1; /* fall through */
 	    case '&':
 		if (hsubl && hsubr) {
-		    if (subst(&sline, hsubl, hsubr, gbal))
+		    if (subst(&sline, hsubl, hsubr, gbal, hsubpatopt))
 			return substfailed();
 		} else {
 		    herrflush();
@@ -1352,7 +1359,8 @@ putoldhistentryontop(short keep_going)
 	do {
 	    if (max_unique_ct-- <= 0 || he == hist_ring) {
 		max_unique_ct = 0;
-		he = hist_ring->down;
+		if (hist_ring)
+		    he = hist_ring->down;
 		next = hist_ring;
 		break;
 	    }
@@ -1360,12 +1368,16 @@ putoldhistentryontop(short keep_going)
 	    next = he->down;
 	} while (!(he->node.flags & HIST_DUP));
     }
-    if (he != hist_ring->down) {
+    /* Is it really possible for hist_ring to be NULL here? */
+    if (he && (!hist_ring || he != hist_ring->down)) {
 	he->up->down = he->down;
 	he->down->up = he->up;
 	he->up = hist_ring;
-	he->down = hist_ring->down;
-	hist_ring->down = he->down->up = he;
+	if (hist_ring) {
+	    he->down = hist_ring->down;
+	    hist_ring->down = he;
+	}
+	he->down->up = he;
     }
     hist_ring = he;
 }
@@ -1461,7 +1473,7 @@ should_ignore_line(Eprog prog)
 mod_export int
 hend(Eprog prog)
 {
-    int flag, hookret, stack_pos = histsave_stack_pos;
+    int flag, hookret = 0, stack_pos = histsave_stack_pos;
     /*
      * save:
      * 0: don't save
@@ -1643,12 +1655,17 @@ hend(Eprog prog)
 void
 ihwbegin(int offset)
 {
+    int pos = hptr - chline + offset;
     if (stophist == 2 || (histactive & HA_INWORD) ||
 	(inbufflags & (INP_ALIAS|INP_HIST)) == INP_ALIAS)
 	return;
     if (chwordpos%2)
 	chwordpos--;	/* make sure we're on a word start, not end */
-    chwords[chwordpos++] = hptr - chline + offset;
+    DPUTS1(pos < 0, "History word position < 0 in %s",
+	   dupstrpfx(chline, hptr-chline));
+    if (pos < 0)
+	pos = 0;
+    chwords[chwordpos++] = pos;
 }
 
 /* Abort current history word, not needed */
@@ -2235,7 +2252,7 @@ casemodify(char *str, int how)
 		char *mbptr;
 
 		for (mbptr = mbstr; mbptr < mbstr + len2; mbptr++) {
-		    if (imeta(STOUC(*mbptr))) {
+		    if (imeta((unsigned char) *mbptr)) {
 			*ptr2++ = Meta;
 			*ptr2++ = *mbptr ^ 32;
 		    } else
@@ -2254,10 +2271,10 @@ casemodify(char *str, int how)
 	    int c;
 	    int mod = 0;
 	    if (*str == Meta) {
-		c = STOUC(str[1] ^ 32);
+		c = (unsigned char) (str[1] ^ 32);
 		str += 2;
 	    } else
-		c = STOUC(*str++);
+		c = (unsigned char) *str++;
 	    switch (how) {
 	    case CASMOD_LOWER:
 		if (isupper(c)) {
@@ -2310,7 +2327,7 @@ casemodify(char *str, int how)
 
 /**/
 int
-subst(char **strptr, char *in, char *out, int gbal)
+subst(char **strptr, char *in, char *out, int gbal, int forcepat)
 {
     char *str = *strptr, *substcut, *sptr;
     int off, inlen, outlen;
@@ -2318,7 +2335,7 @@ subst(char **strptr, char *in, char *out, int gbal)
     if (!*in)
 	in = str, gbal = 0;
 
-    if (isset(HISTSUBSTPATTERN)) {
+    if (isset(HISTSUBSTPATTERN) || forcepat) {
 	int fl = SUB_LONG|SUB_REST|SUB_RETFAIL;
 	char *oldin = in;
 	if (gbal)
@@ -3791,8 +3808,14 @@ histsplitwords(char *lineptr, short **wordsp, int *nwordsp, int *nwordposp,
 			zrealloc(words, nwords*sizeof(*words));
 		}
 		words[nwordpos++] = lineptr - start;
-		while (*lineptr && !inblank(*lineptr))
-		    lineptr++;
+		while (*lineptr) {
+		    if (*lineptr == Meta && lineptr[1])
+			lineptr += 2;
+		    else if (!inblank(*lineptr))
+			lineptr++;
+		    else
+			break;
+		}
 		words[nwordpos++] = lineptr - start;
 	    }
 	} while (*lineptr);
diff --git a/Src/init.c b/Src/init.c
index 871d46b12..ec21521b1 100644
--- a/Src/init.c
+++ b/Src/init.c
@@ -246,6 +246,9 @@ loop(int toplevel, int justonce)
 
 static int restricted;
 
+/* original argv[0]. This is already metafied */
+static char *argv0;
+
 /**/
 static void
 parseargs(char *zsh_name, char **argv, char **runscript, char **cmdptr,
@@ -257,7 +260,7 @@ parseargs(char *zsh_name, char **argv, char **runscript, char **cmdptr,
     if (**argv == '-')
 	flags |= PARSEARGS_LOGIN;
 
-    argzero = posixzero = *argv++;
+    argv0 = argzero = posixzero = *argv++;
     SHIN = 0;
 
     /*
@@ -500,10 +503,10 @@ parseopts(char *nam, char ***argvp, char *new_opts, char **cmdp,
 		    }
 		}
               break;
-	    } else if (isspace(STOUC(**argv))) {
+	    } else if (isspace((unsigned char) **argv)) {
 		/* zsh's typtab not yet set, have to use ctype */
 		while (*++*argv)
-		    if (!isspace(STOUC(**argv))) {
+		    if (!isspace((unsigned char) **argv)) {
 		     badoptionstring:
 			WARN_OPTION("bad option string: '%s'", args);
 			return 1;
@@ -697,11 +700,14 @@ init_io(char *cmd)
      * process group leader.
      */
     mypid = (zlong)getpid();
-    if (opts[MONITOR] && (SHTTY != -1)) {
-	origpgrp = GETPGRP();
-        acquire_pgrp(); /* might also clear opts[MONITOR] */
-    } else
-	opts[MONITOR] = 0;
+    if (opts[MONITOR]) {
+	if (SHTTY == -1)
+	    opts[MONITOR] = 0;
+	else if (!origpgrp) {
+	    origpgrp = GETPGRP();
+	    acquire_pgrp(); /* might also clear opts[MONITOR] */
+	}
+    }
 #else
     opts[MONITOR] = 0;
 #endif
@@ -747,7 +753,7 @@ init_shout(void)
 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",
+    "md", "mh", "so", "us", "ZH", "me", "se", "ue", "ZR", "ch",
     "ku", "kd", "kl", "kr", "sc", "rc", "bc", "AF", "AB"
 };
 
@@ -872,10 +878,127 @@ init_term(void)
 	/* The following is an attempt at a heuristic,
 	 * but it fails in some cases */
 	/* rprompt_indent = ((hasam && !hasbw) || hasye || !tccan(TCLEFT)); */
+
+	/* if there's no termcap entry for italics, use CSI 3 m */
+	if (!tccan(TCITALICSBEG)) {
+	    zsfree(tcstr[TCITALICSBEG]);
+	    tcstr[TCITALICSBEG] = ztrdup("\033[3m");
+	    tclen[TCITALICSBEG] = 4;
+	}
+	if (!tccan(TCITALICSEND)) {
+	    zsfree(tcstr[TCITALICSEND]);
+	    tcstr[TCITALICSEND] = ztrdup("\033[23m");
+	    tclen[TCITALICSEND] = 5;
+	}
+	if (!tccan(TCFAINTBEG)) {
+	    zsfree(tcstr[TCFAINTBEG]);
+	    tcstr[TCFAINTBEG] = ztrdup("\033[2m");
+	    tclen[TCFAINTBEG] = 4;
+	}
     }
     return 1;
 }
 
+/*
+ * Get (or guess) the absolute pathname of the current zsh exeutable.
+ * Try OS-specific method, and if it fails, guess the absolute pathname
+ * from argv0, pwd, and PATH. 'name' and 'cwd' are unmetefied versions of
+ * argv0 and pwd.
+ * Returns a zalloc()ed string (not metafied), or NULL if failed.
+ */
+#ifdef __APPLE__
+#include <mach-o/dyld.h>
+#endif
+
+/**/
+static char *
+getmypath(const char *name, const char *cwd)
+{
+    char *buf;
+    int namelen;
+
+    if (!name)
+	return NULL;
+    if (*name == '-')
+	++name;
+    if ((namelen = strlen(name)) == 0)
+	return NULL;
+#if defined(__APPLE__)
+    {
+	uint32_t n = PATH_MAX;
+	int ret;
+	buf = (char *)zalloc(PATH_MAX);
+	if ((ret = _NSGetExecutablePath(buf, &n)) < 0) {
+	    /* try again with increased buffer size */
+	    buf = (char *)zrealloc(buf, n);
+	    ret = _NSGetExecutablePath(buf, &n);
+	}
+	if (ret == 0 && strlen(buf) > 0)
+	    return buf;
+	else
+	    free(buf);
+    }
+#elif defined(PROC_SELF_EXE)
+    {
+	ssize_t n;
+	buf = (char *)zalloc(PATH_MAX);
+	n = readlink(PROC_SELF_EXE, buf, PATH_MAX);
+	if (n > 0 && n < PATH_MAX) {
+	    buf[n] = '\0';
+	    return buf;
+	}
+	else
+	    free(buf);
+    }
+#endif
+    /* guess the absolute pathname of 'name' */
+    if (name[namelen-1] == '/')    /* name should not end with '/' */
+	return NULL;
+    else if (name[0] == '/') {
+	/* name is already an absolute pathname */
+	return ztrdup(name);
+    }
+    else if (strchr(name, '/')) {
+	/* relative path */
+	if (!cwd)
+	    return NULL;
+	buf = (char *)zalloc(strlen(cwd) + namelen + 2);
+	sprintf(buf, "%s/%s", cwd, name);
+	return buf;
+    }
+#ifdef HAVE_REALPATH
+    else {
+	/* search each dir in PARH */
+	const char *path, *sep;
+	char *real, *try;
+	int pathlen, dirlen;
+
+	path = getenv("PATH");
+	if (!path || (pathlen = strlen(path)) == 0)
+	    return NULL;
+	/* for simplicity, allocate buf even if REALPATH_ACCEPTS_NULL is on */
+	buf = (char *)zalloc(PATH_MAX);
+	try = (char *)zalloc(pathlen + namelen + 2);
+	do {
+	    sep = strchr(path, ':');
+	    dirlen = sep ? sep - path : strlen(path);
+	    strncpy(try, path, dirlen);
+	    try[dirlen] = '/';
+	    try[dirlen+1] = '\0';
+	    strcat(try, name);
+	    real = realpath(try, buf);
+	    if (sep)
+		path = sep + 1;
+	} while (!real && sep);
+	free(try);
+	if (!real)
+	    free(buf);
+	return real;	/* this may be NULL */
+    }
+#endif
+    return NULL;
+}
+
 /* Initialize lots of global variables and hash tables */
 
 /**/
@@ -1067,9 +1190,12 @@ setupvals(char *cmd, char *runscript, char *zsh_name)
 	ztrdup(DEFAULT_IFS_SH) : ztrdup(DEFAULT_IFS);
     wordchars   = ztrdup(DEFAULT_WORDCHARS);
     postedit    = ztrdup("");
-    zunderscore  = (char *) zalloc(underscorelen = 32);
-    underscoreused = 1;
-    *zunderscore = '\0';
+    /* If _ is set in environment then initialize our $_ by copying it */
+    zunderscore = getenv("_");
+    zunderscore = zunderscore ? metafy(zunderscore, -1, META_DUP) : ztrdup("");
+    underscoreused = strlen(zunderscore) + 1;
+    underscorelen = (underscoreused + 31) & ~31;
+    zunderscore = (char *)zrealloc(zunderscore, underscorelen);
 
     zoptarg = ztrdup("");
     zoptind = 1;
@@ -1089,8 +1215,8 @@ setupvals(char *cmd, char *runscript, char *zsh_name)
 #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);
+	    home = ztrdup_metafy(pswd->pw_dir);
+	cached_username = ztrdup_metafy(pswd->pw_name);
     }
     else
 #endif /* USE_GETPWUID */
@@ -1175,6 +1301,18 @@ setupvals(char *cmd, char *runscript, char *zsh_name)
     /* Colour sequences for outputting colours in prompts and zle */
     set_default_colour_sequences();
 
+    /* ZSH_EXEPATH */
+    {
+	char *mypath, *exename, *cwd;
+	exename = unmetafy(ztrdup(argv0), NULL);
+	cwd = pwd ? unmetafy(ztrdup(pwd), NULL) : NULL;
+	mypath = getmypath(exename, cwd);
+	free(exename);
+	free(cwd);
+	if (mypath) {
+	    setsparam("ZSH_EXEPATH", metafy(mypath, -1, META_REALLOC));
+	}
+    }
     if (cmd)
 	setsparam("ZSH_EXECUTION_STRING", ztrdup(cmd));
     if (runscript)
@@ -1244,6 +1382,9 @@ setupshin(char *runscript)
 void
 init_signals(void)
 {
+    sigtrapped = (int *) hcalloc(TRAPCOUNT * sizeof(int));
+    siglists = (Eprog *) hcalloc(TRAPCOUNT * sizeof(Eprog));
+
     if (interact) {
 	int i;
 	signal_setmask(signal_mask(0));
@@ -1654,8 +1795,7 @@ VA_DCL
 
 	lp = va_arg(ap, char **);
 
-	pptbuf = unmetafy(promptexpand(lp ? *lp : NULL, 0, NULL, NULL,
-				       NULL),
+	pptbuf = unmetafy(promptexpand(lp ? *lp : NULL, 0, NULL, NULL),
 			  &pptlen);
 	write_loop(2, pptbuf, pptlen);
 	free(pptbuf);
@@ -1724,9 +1864,9 @@ zsh_main(UNUSED(int argc), char **argv)
      * interactive
      */
     typtab['\0'] |= IMETA;
-    typtab[STOUC(Meta)  ] |= IMETA;
-    typtab[STOUC(Marker)] |= IMETA;
-    for (t0 = (int)STOUC(Pound); t0 <= (int)STOUC(Nularg); t0++)
+    typtab[(unsigned char) Meta  ] |= IMETA;
+    typtab[(unsigned char) Marker] |= IMETA;
+    for (t0 = (int) (unsigned char) Pound; t0 <= (int) (unsigned char) Nularg; t0++)
 	typtab[t0] |= ITOK | IMETA;
 
     for (t = argv; *t; *t = metafy(*t, -1, META_ALLOC), t++);
diff --git a/Src/input.c b/Src/input.c
index 9898a7177..d8ac2c0e7 100644
--- a/Src/input.c
+++ b/Src/input.c
@@ -220,7 +220,7 @@ shingetchar(void)
     int nread, rsize = isset(SHINSTDIN) ? 1 : SHINBUFSIZE;
 
     if (shinbufptr < shinbufendptr)
-	return STOUC(*shinbufptr++);
+	return (unsigned char) *shinbufptr++;
 
     shinbufreset();
 #ifdef USE_LSEEK
@@ -242,7 +242,7 @@ shingetchar(void)
 		zerr("lseek(%d, %d): %e", SHIN, -(nread - rsize), errno);
 	} else
 	    shinbufendptr = shinbuffer + nread;
-	return STOUC(*shinbufptr++);
+	return (unsigned char) *shinbufptr++;
     }
 #endif
     for (;;) {
@@ -259,7 +259,7 @@ shingetchar(void)
     }
     if (shinbufendptr == shinbuffer)
         return -1;
-    return STOUC(*shinbufptr++);
+    return (unsigned char) *shinbufptr++;
 }
 
 /* Read a line from SHIN.  Convert tokens and   *
@@ -328,7 +328,7 @@ ingetc(void)
 	if (inbufleft) {
 	    inbufleft--;
 	    inbufct--;
-	    if (itok(lastc = STOUC(*inbufptr++)))
+	    if (itok(lastc = (unsigned char) *inbufptr++))
 		continue;
 	    if (((inbufflags & INP_LINENO) || !strin) && lastc == '\n')
 		lineno++;
@@ -402,7 +402,7 @@ inputline(void)
 	    char *pptbuf;
 	    int pptlen;
 	    pptbuf = unmetafy(promptexpand(ingetcpmptl ? *ingetcpmptl : NULL,
-					   0, NULL, NULL, NULL), &pptlen);
+					   0, NULL, NULL), &pptlen);
 	    write_loop(2, pptbuf, pptlen);
 	    free(pptbuf);
 	}
@@ -610,11 +610,11 @@ inungetc(int c)
     }
 }
 
-/* stuff a whole file into the input queue and print it */
+/* stuff a whole file into memory and return it */
 
 /**/
-int
-stuff(char *fn)
+off_t
+zstuff(char **out, const char *fn)
 {
     FILE *in;
     char *buf;
@@ -622,20 +622,39 @@ stuff(char *fn)
 
     if (!(in = fopen(unmeta(fn), "r"))) {
 	zerr("can't open %s", fn);
-	return 1;
+	return -1;
     }
+    queue_signals();
     fseek(in, 0, SEEK_END);
     len = ftell(in);
     fseek(in, 0, SEEK_SET);
     buf = (char *)zalloc(len + 1);
-    if (!(fread(buf, len, 1, in))) {
+    if (len && !(fread(buf, len, 1, in))) {
 	zerr("read error on %s", fn);
 	fclose(in);
 	zfree(buf, len + 1);
-	return 1;
+	unqueue_signals();
+	return -1;
     }
     fclose(in);
     buf[len] = '\0';
+    *out = buf;
+    unqueue_signals();
+    return len;
+}
+
+/* stuff a whole file into the input queue and print it */
+
+/**/
+int
+stuff(char *fn)
+{
+    char *buf;
+    off_t len = zstuff(&buf, fn);
+
+    if (len < 0)
+	return 1;
+    
     fwrite(buf, len, 1, stderr);
     fflush(stderr);
     inputsetline(metafy(buf, len, META_REALLOC), INP_FREE);
@@ -816,6 +835,7 @@ char *input_hasalias(void)
 {
     int flags = inbufflags;
     struct instacks *instackptr = instacktop;
+    char *alias_nam = NULL;
 
     for (;;)
     {
@@ -824,9 +844,9 @@ char *input_hasalias(void)
 	DPUTS(instackptr == instack, "BUG: continuation at bottom of instack");
 	instackptr--;
 	if (instackptr->alias)
-	    return instackptr->alias->node.nam;
+	    alias_nam = instackptr->alias->node.nam;
 	flags = instackptr->flags;
     }
 
-    return NULL;
+    return alias_nam;
 }
diff --git a/Src/jobs.c b/Src/jobs.c
index e0e453ed8..07facc60b 100644
--- a/Src/jobs.c
+++ b/Src/jobs.c
@@ -427,11 +427,17 @@ storepipestats(Job jn, int inforeground, int fixlastval)
     }
 
     if (fixlastval) {
-      if (jn->stat & STAT_CURSH) {
-	if (!lastval && isset(PIPEFAIL))
-	  lastval = pipefail;
-      } else if (isset(PIPEFAIL))
-	lastval = pipefail;
+	if (jn->stat & STAT_CURSH) {
+	    if (!lastval && isset(PIPEFAIL)) {
+		if (inforeground)
+		    this_noerrexit = 0;
+		lastval = pipefail;
+	    }
+	} else if (isset(PIPEFAIL)) {
+	    if (inforeground)
+		this_noerrexit = 0;
+	    lastval = pipefail;
+	}
     }
 }
 
@@ -544,16 +550,14 @@ update_job(Job jn)
 
     if (isset(MONITOR)) {
 	pid_t pgrp = gettygrp();           /* get process group of tty      */
+	int deadpgrp = (mypgrp != pgrp && inforeground && pgrp > 1 &&
+			kill(-pgrp, 0) == -1 && errno == ESRCH);
 
 	/* is this job in the foreground of an interactive shell? */
 	if (mypgrp != pgrp && inforeground &&
-	    (jn->gleader == pgrp ||
-	     (pgrp > 1 &&
-	      (kill(-pgrp, 0) == -1 && errno == ESRCH)))) {
+	    ((jn->gleader == pgrp && signalled) || deadpgrp)) {
 	    if (list_pipe) {
-		if (somestopped || (pgrp > 1 &&
-				    kill(-pgrp, 0) == -1 &&
-				    errno == ESRCH)) {
+		if (somestopped || deadpgrp) {
 		    attachtty(mypgrp);
 		    /* check window size and adjust if necessary */
 		    adjustwinsize(0);
@@ -656,6 +660,25 @@ update_job(Job jn)
     }
 }
 
+/**/
+void
+update_bg_job(Job jn, pid_t pid, int status)
+{
+    /*
+     * 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) {
+	if (WIFEXITED(status))
+	    addbgstatus(pid, WEXITSTATUS(status));
+	else if (WIFSIGNALED(status))
+	    addbgstatus(pid, 0200 | WTERMSIG(status));
+    }
+}
+
 /* set the previous job to something reasonable */
 
 /**/
@@ -890,8 +913,13 @@ printtime(struct timeval *real, child_times_t *ti, char *desc)
 		break;
 #endif
 #ifdef HAVE_STRUCT_RUSAGE_RU_MAXRSS
+#ifdef RU_MAXRSS_IS_IN_BYTES
+# define MAXRSS_IN_KB(x) ((x)/1024)
+#else
+# define MAXRSS_IN_KB(x) (x)
+#endif
 	    case 'M':
-		fprintf(stderr, "%ld", ti->ru_maxrss / 1024);
+		fprintf(stderr, "%ld", MAXRSS_IN_KB(ti->ru_maxrss));
 		break;
 #endif
 #ifdef HAVE_STRUCT_RUSAGE_RU_MAJFLT
@@ -1029,7 +1057,7 @@ should_report_time(Job j)
 	    return 1;
 #else
 	{
-	    clktck = get_clktck();
+	    long clktck = get_clktck();
 	    if ((j->procs->ti.ut + j->procs->ti.st) / clktck >= reporttime)
 		return 1;
 	}
@@ -1038,13 +1066,28 @@ should_report_time(Job j)
 
 #ifdef HAVE_GETRUSAGE
     if (reportmemory >= 0 &&
-	j->procs->ti.ru_maxrss / 1024 > reportmemory)
+	MAXRSS_IN_KB(j->procs->ti.ru_maxrss) > reportmemory)
 	return 1;
 #endif
 
     return 0;
 }
 
+/**/
+char *
+sigmsg(int sig)
+{
+    static char *unknown = "unknown signal";
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    static char rtmsg[] = "real-time event XXX";
+    if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
+	sprintf(rtmsg + sizeof(rtmsg) - 4, "%u", sig - SIGRTMIN + 1);
+	return rtmsg;
+    }
+#endif
+    return sig <= SIGCOUNT ? sig_msg[sig] : unknown;
+}
+
 /* !(lng & 3) means jobs    *
  *  (lng & 1) means jobs -l *
  *  (lng & 2) means jobs -p
@@ -1374,8 +1417,10 @@ cleanfilelists(void)
 
     DPUTS(shell_exiting >= 0, "BUG: cleanfilelists() before exit");
  
-    for (i = 1; i <= maxjob; i++)
+    for (i = 1; i <= maxjob; i++) {
 	deletefilelist(jobtab[i].filelist, 0);
+	jobtab[i].filelist = 0;
+    }
 }
 
 /**/
@@ -1488,10 +1533,7 @@ addproc(pid_t pid, char *text, int aux, struct timeval *bgtime,
 	 * set it for that, too.
 	 */
 	if (gleader != -1) {
-	    if (jobtab[thisjob].stat & STAT_CURSH)
-		jobtab[thisjob].gleader = gleader;
-	    else
-		jobtab[thisjob].gleader = pid;
+	    jobtab[thisjob].gleader = gleader;
 	    if (list_pipe_job_used != -1)
 		jobtab[list_pipe_job_used].gleader = gleader;
 	    /*
@@ -1500,7 +1542,7 @@ addproc(pid_t pid, char *text, int aux, struct timeval *bgtime,
 	     */
 	    last_attached_pgrp = gleader;
 	} else if (!jobtab[thisjob].gleader)
-		jobtab[thisjob].gleader = pid;
+	    jobtab[thisjob].gleader = pid;
 	/* attach this process to end of process list of current job */
 	pnlist = &jobtab[thisjob].procs;
     }
@@ -1536,8 +1578,10 @@ havefiles(void)
     int i;
 
     for (i = 1; i <= maxjob; i++)
-	if (jobtab[i].stat && jobtab[i].filelist)
+	if (jobtab[i].stat && jobtab[i].filelist &&
+	    peekfirst(jobtab[i].filelist)) {
 	    return 1;
+	}
     return 0;
 
 }
@@ -2402,7 +2446,7 @@ bin_fg(char *name, char **argv, Options ops, int func)
 	    int curmaxjob, ignorejob;
 	    if (unset(MONITOR) && oldmaxjob) {
 		jobptr = oldjobtab;
-		curmaxjob = oldmaxjob ? oldmaxjob - 1 : 0;
+		curmaxjob = oldmaxjob;
 		ignorejob = 0;
 	    } else {
 		jobptr = jobtab;
@@ -2506,6 +2550,7 @@ bin_fg(char *name, char **argv, Options ops, int func)
 		jobtab[job].stat &= ~STAT_CURSH;
 	    }
 	    if ((stopped = (jobtab[job].stat & STAT_STOPPED))) {
+		/* WIFCONTINUED will makerunning() again at killjb() */
 		makerunning(jobtab + job);
 		if (func == BIN_BG) {
 		    /* Set $! to indicate this was backgrounded */
@@ -2664,11 +2709,37 @@ static const struct {
 int
 bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 {
-    int sig = SIGTERM;
+    int status, sig = SIGTERM;
     int returnval = 0;
+#ifdef HAVE_SIGQUEUE
+    union sigval sigqueue_info;
+#endif
+    int use_sigqueue = 0, got_sig = 0;
+
+    while (*argv && **argv == '-') {
+	if (!use_sigqueue && (*argv)[1] == 'q' && (*argv)[2] == '\0') {
+	    char *endp;
+
+	    if (!*++argv) {
+		zwarnnam(nam, "-q: argument expected");
+		return 1;
+	    }
+#ifdef HAVE_SIGQUEUE
+	    sigqueue_info.sival_int =
+#endif
+		    zstrtol(*argv, &endp, 10);
+	    if (*endp) {
+		zwarnnam(nam, "invalid number: %s", *argv);
+		return 1;
+	    }
+	    use_sigqueue = 1;
+	    argv++;
+	    continue;
+	}
+	if (got_sig)
+	    break;
 
     /* check for, and interpret, a signal specifier */
-    if (*argv && **argv == '-') {
 	if (idigit((*argv)[1])) {
 	    char *endp;
 	    /* signal specified by number */
@@ -2684,23 +2755,29 @@ bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 	    if ((*argv)[1] == 'l' && (*argv)[2] == '\0') {
 		if (argv[1]) {
 		    while (*++argv) {
-			sig = zstrtol(*argv, &signame, 10);
+			status = zstrtol(*argv, &signame, 10);
 			if (signame == *argv) {
+			    signame = casemodify(signame, CASMOD_UPPER);
 			    if (!strncmp(signame, "SIG", 3))
 				signame += 3;
 			    for (sig = 1; sig <= SIGCOUNT; sig++)
-				if (!strcasecmp(sigs[sig], signame))
+				if (!strcmp(sigs[sig], signame))
 				    break;
 			    if (sig > SIGCOUNT) {
 				int i;
 
 				for (i = 0; alt_sigs[i].name; i++)
-				    if (!strcasecmp(alt_sigs[i].name, signame))
+				    if (!strcmp(alt_sigs[i].name, signame))
 				    {
 					sig = alt_sigs[i].num;
 					break;
 				    }
 			    }
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+			    if (sig > SIGCOUNT && (sig = rtsigno(signame))) {
+				printf("%d\n", sig);
+			    } else
+#endif
 			    if (sig > SIGCOUNT) {
 				zwarnnam(nam, "unknown signal: SIG%s",
 					 signame);
@@ -2713,14 +2790,15 @@ bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 					 signame);
 				returnval++;
 			    } else {
-				if (WIFSIGNALED(sig))
-				    sig = WTERMSIG(sig);
-				else if (WIFSTOPPED(sig))
-				    sig = WSTOPSIG(sig);
+				sig = status & ~0200;
 				if (1 <= sig && sig <= SIGCOUNT)
 				    printf("%s\n", sigs[sig]);
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+				else if ((signame = rtsigname(sig, 0)))
+				    printf("%s\n", signame);
+#endif
 				else
-				    printf("%d\n", sig);
+				    printf("%d\n", status);
 			    }
 			}
 		    }
@@ -2729,10 +2807,45 @@ bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 		printf("%s", sigs[1]);
 		for (sig = 2; sig <= SIGCOUNT; sig++)
 		    printf(" %s", sigs[sig]);
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+		for (sig = SIGRTMIN; sig <= SIGRTMAX; sig++)
+		    printf(" %s", rtsigname(sig, 0));
+#endif
 		putchar('\n');
 		return 0;
 	    }
 
+	    /* with argument "-L" list signals with their numbers in a table */
+	    if ((*argv)[1] == 'L' && (*argv)[2] == '\0') {
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+		const int width = SIGRTMAX >= 100 ? 3 : 2;
+#else
+		const int width = SIGCOUNT >= 100 ? 3 : 2;
+#endif
+		const int cols = zterm_columns >= 30 ?
+		    (zterm_columns < 90 ? zterm_columns / 15 : 6) : 1;
+
+		for (sig = 1; sig < SIGCOUNT
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+			+ 1
+#endif
+			; sig++)
+		{
+		    printf("%*d %-10s%c", width, sig, sigs[sig],
+			    sig % cols ? ' ' : '\n');
+		}
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+		for (sig = SIGRTMIN; sig < SIGRTMAX; sig++) {
+		    printf("%*d %-10s%c", width, sig, rtsigname(sig, 0),
+			    (sig - SIGRTMIN + SIGCOUNT + 1) % cols ? ' ' : '\n');
+		}
+		printf("%*d RTMAX\n", width, sig);
+#else
+		printf("%*d %s\n", width, sig, sigs[sig]);
+#endif
+		return 0;
+	    }
+
     	    if ((*argv)[1] == 'n' && (*argv)[2] == '\0') {
 	    	char *endp;
 
@@ -2777,14 +2890,19 @@ bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 			    break;
 			}
 		}
-		if (sig > SIGCOUNT) {
+		if (sig > SIGCOUNT
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+			&& !(sig = rtsigno(signame))
+#endif
+			) {
 		    zwarnnam(nam, "unknown signal: SIG%s", signame);
-		    zwarnnam(nam, "type kill -l for a list of signals");
+		    zwarnnam(nam, "type kill -L for a list of signals");
 		    return 1;
 		}
 	    }
 	}
 	argv++;
+	got_sig = 1;
     }
 
     /* Discard the standard "-" and "--" option breaks */
@@ -2833,7 +2951,12 @@ bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 	    returnval++;
 	} else {
 	    int pid = atoi(*argv);
-	    if (kill(pid, sig) == -1) {
+	    if (
+#ifdef HAVE_SIGQUEUE
+		use_sigqueue ? sigqueue(pid, sig, sigqueue_info) :
+#endif
+		kill(pid, sig) == -1)
+	    {
 		zwarnnam("kill", "kill %s failed: %e", *argv, errno);
 		returnval++;
 	    } 
@@ -2854,18 +2977,19 @@ bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func))
 
     return returnval < 126 ? returnval : 1;
 }
-/* Get a signal number from a string */
+
+/* Get index into table of traps from a string describing a signal */
 
 /**/
 mod_export int
-getsignum(const char *s)
+getsigidx(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;
+    if (idigit(*s) && x >= 0)
+	return SIGIDX(x);
 
     /* search for signal by name */
     if (!strncmp(s, "SIG", 3))
@@ -2881,11 +3005,16 @@ getsignum(const char *s)
 	    return alt_sigs[i].num;
     }
 
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    if ((x = rtsigno(s)))
+	return SIGIDX(x);
+#endif
+
     /* no matching signal */
     return -1;
 }
 
-/* Get the name for a signal. */
+/* Get the name for a signal given the index into the traps table. */
 
 /**/
 mod_export const char *
@@ -2899,6 +3028,11 @@ getsigname(int sig)
 		return alt_sigs[i].name;
     }
     else
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    if (sig >= VSIGCOUNT)
+	return rtsigname(SIGNUM(sig), 0);
+    else
+#endif
 	return sigs[sig];
 
     /* shouldn't reach here */
@@ -2923,10 +3057,22 @@ gettrapnode(int sig, int ignoredisable)
     else
 	getptr = shfunctab->getnode;
 
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    if (sig >= VSIGCOUNT)
+	sprintf(fname, "TRAP%s", rtsigname(SIGNUM(sig), 0));
+    else
+#endif
     sprintf(fname, "TRAP%s", sigs[sig]);
     if ((hn = getptr(shfunctab, fname)))
 	return hn;
 
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    if (sig >= VSIGCOUNT) {
+	sprintf(fname, "TRAP%s", rtsigname(SIGNUM(sig), 1));
+	return getptr(shfunctab, fname);
+    }
+#endif
+
     for (i = 0; alt_sigs[i].name; i++) {
 	if (alt_sigs[i].num == sig) {
 	    sprintf(fname, "TRAP%s", alt_sigs[i].name);
diff --git a/Src/lex.c b/Src/lex.c
index ece02659e..700af2da1 100644
--- a/Src/lex.c
+++ b/Src/lex.c
@@ -423,7 +423,7 @@ initlextabs(void)
     for (t0 = 0; lx2[t0]; t0++)
 	lexact2[(int)lx2[t0]] = t0;
     lexact2['&'] = LX2_BREAK;
-    lexact2[STOUC(Meta)] = LX2_META;
+    lexact2[(unsigned char) Meta] = LX2_META;
     lextok2['*'] = Star;
     lextok2['?'] = Quest;
     lextok2['{'] = Inbrace;
@@ -722,7 +722,7 @@ gettok(void)
 	}
 	return peek;
     }
-    switch (lexact1[STOUC(c)]) {
+    switch (lexact1[(unsigned char) c]) {
     case LX1_BKSLASH:
 	d = hgetc();
 	if (d == '\n')
@@ -937,8 +937,8 @@ 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;
+    int intpos = 1, in_brace_param = 0, cmdsubst = 0;
+    int inquote, unmatched = 0, in_pattern = 0;
     enum lextok peek;
 #ifdef DEBUG
     int ocmdsp = cmdsp;
@@ -960,8 +960,8 @@ gettokstr(int c, int sub)
 	if (inbl && !in_brace_param && !pct)
 	    act = LX2_BREAK;
 	else {
-	    act = lexact2[STOUC(c)];
-	    c = lextok2[STOUC(c)];
+	    act = lexact2[(unsigned char) c];
+	    c = lextok2[(unsigned char) c];
 	}
 	switch (act) {
 	case LX2_BREAK:
@@ -1135,7 +1135,7 @@ gettokstr(int c, int sub)
 	    c = Inpar;
 	    break;
 	case LX2_INBRACE:
-	    if (isset(IGNOREBRACES) || sub)
+	    if ((isset(IGNOREBRACES) && !cmdsubst) || sub)
 		c = '{';
 	    else {
 		if (!lexbuf.len && incmdpos) {
@@ -1157,8 +1157,11 @@ gettokstr(int c, int sub)
 	    if (in_brace_param) {
 		cmdpop();
 	    }
-	    if (bct-- == in_brace_param)
-		in_brace_param = 0;
+	    if (bct-- == in_brace_param) {
+		if (cmdsubst)
+		    cmdpop();
+		in_brace_param = cmdsubst = in_pattern = 0;
+	    }
 	    c = Outbrace;
 	    break;
 	case LX2_COMMA:
@@ -1230,7 +1233,7 @@ gettokstr(int c, int sub)
 		    else {
 			int sav = *lexbuf.ptr;
 			*lexbuf.ptr = '\0';
-			t = itype_end(t, IIDENT, 0);
+			t = itype_end(t, INAMESPC, 0);
 			if (t < lexbuf.ptr) {
 			    skipparens(Inbrack, Outbrack, &t);
 			} else {
@@ -1263,7 +1266,7 @@ gettokstr(int c, int sub)
 		    continue;
 	    } else {
 		add(Bnull);
-		if (c == STOUC(Meta)) {
+		if (c == (unsigned char) Meta) {
 		    c = hgetc();
 #ifdef DEBUG
 		    if (lexstop) {
@@ -1306,7 +1309,8 @@ gettokstr(int c, int sub)
 			    lexbuf.ptr--, lexbuf.len--;
 			else
 			    break;
-		    }
+		    } else if (in_pattern && c == '/')
+			add(Bnull);
 		    add(c);
 		}
 		ALLOWHIST
@@ -1394,27 +1398,45 @@ gettokstr(int c, int sub)
 	     */
 	    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();
+	case LX2_BANG:
+	    /*
+	     * Same logic as Dash, for ! to perform negation in range.
+	     */
+	    if (seen_brct)
+		c = Bang;
+	    else
+		c = '!';
+	case LX2_OTHER:
+	    if (in_brace_param) {
+		if (c == '/') {
+		    if (in_pattern == 0)
+			in_pattern = 2;
+		    else
+			--in_pattern;
+		}
+	    }
+	}
+	add(c);
+	c = hgetc();
 	if (intpos)
 	    intpos--;
 	if (lexstop)
 	    break;
+	if (!cmdsubst && in_brace_param && act == LX2_STRING &&
+	    (c == '|' || c == Bar || c == '{' || c == Inbrace || inblank(c))) {
+	    cmdsubst = in_brace_param;
+	    cmdpush(CS_CURSH);
+	} else if (in_pattern == 2 && c != '/')
+	    in_pattern = 1;
     }
   brk:
     if (errflag) {
 	if (in_brace_param) {
-	    while(bct-- >= in_brace_param)
+	    while(bct >= in_brace_param) {
+		if (bct-- == cmdsubst)
+		    cmdpop();
 		cmdpop();
+	    }
 	}
 	return LEXERR;
     }
@@ -1422,17 +1444,28 @@ gettokstr(int c, int sub)
     if (unmatched && !(lexflags & LEXFLAGS_ACTIVE))
 	zerr("unmatched %c", unmatched);
     if (in_brace_param) {
-	while(bct-- >= in_brace_param)
+	while(bct >= in_brace_param) {
+	    if (bct-- == cmdsubst)
+		cmdpop();
 	    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 */
+	/*
+	 * Alias expansion when parsing command substitution means that
+	 * the case for raw lexical analysis may not be the same.
+	 * (Just go with it, OK?)
+	 */
+	int lar = lex_add_raw;
+	lex_add_raw = lexbuf_raw.len > 0 && lexbuf_raw.ptr[-1] == '}';
 	lexbuf.ptr--;
 	lexbuf.len--;
 	lexstop = 0;
 	hungetc('}');
+	lex_add_raw = lar;
     }
     *lexbuf.ptr = '\0';
     DPUTS(cmdsp != ocmdsp, "BUG: gettok: cmdstack changed.");
@@ -1451,8 +1484,8 @@ gettokstr(int c, int sub)
 static int
 dquote_parse(char endchar, int sub)
 {
-    int pct = 0, brct = 0, bct = 0, intick = 0, err = 0;
-    int c;
+    int pct = 0, brct = 0, bct = 0, intick = 0, err = 0, cmdsubst = 0;
+    int c, bskip = 0;
     int math = endchar == ')' || endchar == ']' || infor;
     int zlemath = math && zlemetacs > zlemetall + addedx - inbufct;
 
@@ -1521,11 +1554,25 @@ dquote_parse(char endchar, int sub)
 		c = Qstring;
 	    }
 	    break;
+	case '{':
+	    if (cmdsubst && !intick) {
+		/* In nofork substitution, tokenize as if unquoted */
+		c = Inbrace;
+		bskip++;
+	    }
+	    break;
 	case '}':
 	    if (intick || !bct)
 		break;
 	    c = Outbrace;
-	    bct--;
+	    if (bskip) {
+		bskip--;
+		break;
+	    }
+	    if (bct-- == cmdsubst) {
+		cmdsubst = 0;
+		cmdpop();
+	    }
 	    cmdpop();
 	    break;
 	case '`':
@@ -1580,14 +1627,34 @@ dquote_parse(char endchar, int sub)
 	if (err || lexstop)
 	    break;
 	add(c);
+	if (!cmdsubst && c == Inbrace) {
+	    /* Check for ${|...} nofork command substitution */
+	    if ((c = hgetc()) && !lexstop) {
+		if (c == '|' || inblank(c)) {
+		    cmdsubst = bct;
+		    cmdpush(CS_CURSH);
+		}
+		hungetc(c);
+	    }
+	}
     }
     if (intick == 2)
 	ALLOWHIST
     if (intick) {
 	cmdpop();
     }
-    while (bct--)
+    while (bct) {
+	if (bct-- == cmdsubst) {
+	    /*
+	     * You would think this is an error, but if we call it one,
+	     * parsestrnoerr() returns nonzero to subst_parse_str() and
+	     * subsequently "bad substitution" is not reported
+	     */
+	    /* err = 1 */
+	    cmdpop();
+	}
 	cmdpop();
+    }
     if (lexstop)
 	err = intick || endchar || err;
     else if (err == 1) {
diff --git a/Src/loop.c b/Src/loop.c
index db5b3e097..0f3847541 100644
--- a/Src/loop.c
+++ b/Src/loop.c
@@ -53,7 +53,7 @@ execfor(Estate state, int do_exec)
     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;
+    char *str, *cond = NULL, *advance = NULL;
     zlong val = 0;
     LinkList vars = NULL, args = NULL;
     int old_simple_pline = simple_pline;
@@ -151,7 +151,7 @@ execfor(Estate state, int do_exec)
 	    int count = 0;
 	    for (node = firstnode(vars); node; incnode(node))
 	    {
-		name = (char *)getdata(node);
+		char *name = (char *)getdata(node);
 		if (!args || !(str = (char *) ugetnode(args)))
 		{
 		    if (count) { 
@@ -165,7 +165,7 @@ execfor(Estate state, int do_exec)
 		    fprintf(xtrerr, "%s=%s\n", name, str);
 		    fflush(xtrerr);
 		}
-		setsparam(name, ztrdup(str));
+		setloopvar(name, ztrdup(str));
 		count++;
 	    }
 	    if (!count)
@@ -282,7 +282,7 @@ execselect(Estate state, UNUSED(int do_exec))
 		    /* Keep any user interrupt error status */
 		    errflag = oef | (errflag & ERRFLAG_INT);
 	    	} else {
-		    str = promptexpand(prompt3, 0, NULL, NULL, NULL);
+		    str = promptexpand(prompt3, 0, NULL, NULL);
 		    zputs(str, stderr);
 		    free(str);
 		    fflush(stderr);
@@ -428,7 +428,7 @@ execwhile(Estate state, UNUSED(int do_exec))
     } else {
         for (;;) {
             state->pc = loop;
-            noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
+            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. */
@@ -569,23 +569,14 @@ execif(Estate state, int do_exec)
 	s = 1;
 	state->pc = next;
     }
+    noerrexit = olderrexit;
 
     if (run) {
-	/* we need to ignore lastval until we reach execcmd() */
-	if (olderrexit || run == 2)
-	    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 && !errflag)
-	    lastval = 0;
-    }
+    } else if (!retflag && !errflag)
+	lastval = 0;
     state->pc = end;
     this_noerrexit = 1;
 
@@ -793,6 +784,7 @@ exectry(Estate state, int do_exec)
     cmdpop();
     popheap();
     state->pc = end;
+    this_noerrexit = 1;
 
     return endval;
 }
diff --git a/Src/makepro.awk b/Src/makepro.awk
index f69660531..56c4f4595 100644
--- a/Src/makepro.awk
+++ b/Src/makepro.awk
@@ -121,7 +121,7 @@ BEGIN {
 		# initialiser.
 		dcltor = substr(line, 1, RLENGTH-1)
 		line = substr(line, RLENGTH+1)
-		sub(/=.*$/, "", dcltor)
+		sub(/\075.*$/, "", dcltor)
 		match(dcltor, /^([^_0-9A-Za-z]| const )*/)
 		dcltor = substr(dcltor, 1, RLENGTH) "@+" substr(dcltor, RLENGTH+1)
 		match(dcltor, /^.*@\+[_0-9A-Za-z]+/)
@@ -131,8 +131,8 @@ BEGIN {
 		sub(/@-.*$/, "", dnam)
 
 		# Put parens etc. back
-		gsub(/@[{]/, " _((", dcltor)
-		gsub(/@}/, "))", dcltor)
+		gsub(/@[{]/, " (", dcltor)
+		gsub(/@}/, ")", dcltor)
 		gsub(/@</, "(", dcltor)
 		gsub(/@>/, ")", dcltor)
 		gsub(/@!/, ",", dcltor)
diff --git a/Src/math.c b/Src/math.c
index 777ad9c31..d97dae238 100644
--- a/Src/math.c
+++ b/Src/math.c
@@ -352,6 +352,8 @@ getmathparam(struct mathvalue *mptr)
 	    }
 	    return zero_mnumber;
 	}
+	if (errflag)
+	    return zero_mnumber;
     }
     result = getnumvalue(mptr->pval);
     if (isset(FORCEFLOAT) && result.type == MN_INTEGER) {
@@ -641,7 +643,9 @@ zzlex(void)
 		return MINUSEQ;
 	    }
 	    if (unary) {
-		if (idigit(*ptr) || *ptr == '.') {
+		if (idigit(*ptr) ||
+		    (*ptr == '.' &&
+		     (idigit(ptr[1]) || !itype_end(ptr, INAMESPC, 0)))) {
 		    int ctype = lexconstant();
 		    if (ctype == NUM)
 		    {
@@ -835,7 +839,9 @@ zzlex(void)
 	case Dnull:
 	    break;
 	default:
-	    if (idigit(*--ptr) || *ptr == '.')
+	    if (idigit(*--ptr) ||
+		(*ptr == '.' &&
+		 (idigit(ptr[1]) || !itype_end(ptr, INAMESPC, 0))))
 		return lexconstant();
 	    if (*ptr == '#') {
 		if (*++ptr == '\\' || *ptr == '#') {
@@ -857,7 +863,7 @@ zzlex(void)
 		}
 		cct = 1;
 	    }
-	    if ((ie = itype_end(ptr, IIDENT, 0)) != ptr) {
+	    if ((ie = itype_end(ptr, INAMESPC, 0)) != ptr) {
 		int func = 0;
 		char *p;
 
@@ -955,7 +961,7 @@ getcvar(char *s)
 	    }
 	}
 #endif
-	mn.u.l = STOUC(*t == Meta ? t[1] ^ 32 : *t);
+	mn.u.l = (unsigned char) (*t == Meta ? t[1] ^ 32 : *t);
     }
     unqueue_signals();
     return mn;
@@ -1363,8 +1369,11 @@ op(int what)
     }
 
     spval = &stack[sp].val;
-    if (stack[sp].val.type == MN_UNSET)
+    if (stack[sp].val.type == MN_UNSET) {
 	*spval = getmathparam(stack + sp);
+	if (errflag)
+	    return;
+    }
     switch (what) {
     case NOT:
 	if (spval->type & MN_FLOAT) {
@@ -1548,21 +1557,32 @@ checkunary(int mtokc, char *mptr)
 	    errmsg = 2;
     }
     if (errmsg) {
-	int len, over = 0;
+	int len = 0, over = 0;
 	char *errtype = errmsg == 2 ? "operator" : "operand";
 	while (inblank(*mptr))
 	    mptr++;
-	len = ztrlen(mptr);
-	if (len > 10) {
-	    len = 10;
-	    over = 1;
+	if (isset(MULTIBYTE))
+	    MB_CHARINIT();
+	while (over < 10 && mptr[len]) {
+	    if (isset(MULTIBYTE))
+		len += MB_METACHARLEN(mptr+len);
+	    else
+		len += (mptr[len] == Meta ? 2 : 1);
+	    ++over;
+	}
+	if ((over = mptr[len])) {
+	    mptr = dupstring(mptr);
+	    if (mptr[len] == Meta)
+		mptr[len+1] = 0;
+	    else
+		mptr[len] = 0;
 	}
 	if (!*mptr)
 	    zerr("bad math expression: %s expected at end of string",
 		errtype);
 	else
-	    zerr("bad math expression: %s expected at `%l%s'",
-		 errtype, mptr, len, over ? "..." : "");
+	    zerr("bad math expression: %s expected at `%s%s'",
+		 errtype, mptr, over ? "..." : "");
     }
     unary = !(tp & OP_OPF);
 }
diff --git a/Src/mem.c b/Src/mem.c
index fb4be47bf..0b6f76e46 100644
--- a/Src/mem.c
+++ b/Src/mem.c
@@ -1057,17 +1057,17 @@ zrealloc(void *ptr, size_t size)
 #if !defined(__hpux) && !defined(DGUX) && !defined(__osf__)
 # if defined(_BSD)
 #  ifndef HAVE_BRK_PROTO
-   extern int brk _((caddr_t));
+   extern int brk (caddr_t);
 #  endif
 #  ifndef HAVE_SBRK_PROTO
-   extern caddr_t sbrk _((int));
+   extern caddr_t sbrk (int);
 #  endif
 # else
 #  ifndef HAVE_BRK_PROTO
-   extern int brk _((void *));
+   extern int brk (void *);
 #  endif
 #  ifndef HAVE_SBRK_PROTO
-   extern void *sbrk _((int));
+   extern void *sbrk (int);
 #  endif
 # endif
 #endif
diff --git a/Src/mkbltnmlst.sh b/Src/mkbltnmlst.sh
index c4611d8b3..1994ace60 100644
--- a/Src/mkbltnmlst.sh
+++ b/Src/mkbltnmlst.sh
@@ -76,6 +76,30 @@ for x_mod in $x_mods; do
     test "x$linked" = xno && echo "#endif"
 done
 
+# if dynamic module 'mod' with load=no has moddeps in its .mdd,
+# then output add_dep(mod, dep) for each 'dep' in moddeps.
+dyn_mods="`grep ' link=dynamic .* load=no ' $CFMOD | \
+          sed -e '/^#/d' -e 's/ .*/ /' -e 's/^name=/ /'`"
+
+for mod in $dyn_mods; do
+    modfile="`grep '^name='$mod' ' $CFMOD | \
+              sed -e 's/^.* modfile=//' -e 's/ .*//'`"
+    if test "x$modfile" = x; then
+	echo >&2 "WARNING: no name for \`$mod' in $CFMOD (ignored)"
+	continue
+    fi
+    unset moddeps
+    . $srcdir/../$modfile
+    if test -n "$moddeps"; then
+        echo '#ifdef DYNAMIC'
+        echo "/* non-linked-in known module \`$mod' */"
+        for dep in $moddeps; do
+          echo "  add_dep(\"$mod\", \"$dep\");"
+        done
+        echo '#endif'
+    fi
+done
+
 echo
 done_mods=" "
 for bin_mod in $bin_mods; do
@@ -98,12 +122,12 @@ for bin_mod in $bin_mods; do
 	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 "        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},"
diff --git a/Src/modentry.c b/Src/modentry.c
index 4d8217f43..23c499d94 100644
--- a/Src/modentry.c
+++ b/Src/modentry.c
@@ -1,10 +1,10 @@
 #include "zsh.mdh"
 
-int setup_ _((Module));
-int boot_ _((Module));
-int cleanup_ _((Module));
-int finish_ _((Module));
-int modentry _((int boot, Module m, void *ptr));
+int setup_ (Module);
+int boot_ (Module);
+int cleanup_ (Module);
+int finish_ (Module);
+int modentry (int boot, Module m, void *ptr);
 
 /**/
 int
diff --git a/Src/module.c b/Src/module.c
index bab4d8d73..b4b5d0a2c 100644
--- a/Src/module.c
+++ b/Src/module.c
@@ -356,7 +356,7 @@ finish_(UNUSED(Module m))
 
 /**/
 void
-register_module(char *n, Module_void_func setup,
+register_module(const char *n, Module_void_func setup,
 		Module_features_func features,
 		Module_enables_func enables,
 		Module_void_func boot,
@@ -846,7 +846,7 @@ Hookdef hooktab;
 
 /**/
 Hookdef
-gethookdef(char *n)
+gethookdef(const char *n)
 {
     Hookdef p;
 
@@ -974,7 +974,7 @@ deletehookdeffunc(Hookdef h, Hookfn f)
 
 /**/
 mod_export int
-deletehookfunc(char *n, Hookfn f)
+deletehookfunc(const char *n, Hookfn f)
 {
     Hookdef h = gethookdef(n);
 
@@ -1198,6 +1198,7 @@ add_autoparam(const char *module, const char *pnam, int flags)
 {
     Param pm;
     int ret;
+    int ne = noerrs;
 
     queue_signals();
     if ((ret = checkaddparam(pnam, (flags & FEAT_IGNORE)))) {
@@ -1212,14 +1213,18 @@ add_autoparam(const char *module, const char *pnam, int flags)
 	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;
+    noerrs = 2;
+    if ((pm = setsparam(dupstring(pnam), ztrdup(module)))) {
+	pm->node.flags |= PM_AUTOLOAD;
+	if (flags & FEAT_AUTOALL)
+	    pm->node.flags |= PM_AUTOALL;
+	ret = 0;
+    } else
+	ret = -1;
+    noerrs = ne;
     unqueue_signals();
 
-    return 0;
+    return ret;
 }
 
 /* Remove a parameter added with add_autoparam() */
@@ -1761,7 +1766,7 @@ dyn_finish_module(Module m)
 #else
 
 static Module_generic_func
-module_func(Module m, char *name)
+module_func(Module m, const char *name)
 {
 #ifdef DYNAMIC_NAME_CLASH_OK
     return (Module_generic_func) dlsym(m->u.handle, name);
@@ -2438,7 +2443,7 @@ bin_zmodload(char *nam, char **args, Options ops, UNUSED(int func))
     int ops_au = OPT_ISSET(ops,'a') || OPT_ISSET(ops,'u');
     int ret = 1, autoopts;
     /* options only allowed with -F */
-    char *fonly = "lP", *fp;
+    const char *fonly = "lP", *fp;
 
     if (ops_bcpf && !ops_au) {
 	zwarnnam(nam, "-b, -c, -f, and -p must be combined with -a or -u");
@@ -2474,7 +2479,7 @@ bin_zmodload(char *nam, char **args, Options ops, UNUSED(int func))
 	return 1;
     }
     for (fp = fonly; *fp; fp++) {
-	if (OPT_ISSET(ops,STOUC(*fp)) && !OPT_ISSET(ops,'F')) {
+	if (OPT_ISSET(ops,(unsigned char) *fp) && !OPT_ISSET(ops,'F')) {
 	    zwarnnam(nam, "-%c is only allowed with -F", *fp);
 	    return 1;
 	}
@@ -3177,7 +3182,7 @@ bin_zmodload_features(const char *nam, char **args, Options ops)
 	} else if (OPT_ISSET(ops, 'L'))
 	    printf("zmodload -F %s ", m->node.nam);
 	for (fp = features, ep = enables; *fp; fp++, ep++) {
-	    char *onoff;
+	    const char *onoff;
 	    int term;
 	    if (*args) {
 		char **argp;
@@ -3447,7 +3452,8 @@ autofeatures(const char *cmdnam, const char *module, char **features,
 	defm = NULL;
 
     for (; *features; features++) {
-	char *fnam, *typnam, *feature;
+	char *fnam, *feature;
+	const char *typnam;
 	int add, fchar, flags = defflags;
 	autofeaturefn_t fn;
 
diff --git a/Src/options.c b/Src/options.c
index a1fe918fc..a0e1aa024 100644
--- a/Src/options.c
+++ b/Src/options.c
@@ -881,11 +881,12 @@ dosetopt(int optno, int value, int force, char *new_opts)
     } else if (!force && optno == MONITOR && value) {
 	if (new_opts[optno] == value)
 	    return 0;
-	if (SHTTY != -1) {
+	if (SHTTY == -1)
+	    return -1;
+	if (!origpgrp) {
 	    origpgrp = GETPGRP();
 	    acquire_pgrp();
-	} else
-	    return -1;
+	}
 #else
     } else if(optno == MONITOR && value) {
 	    return -1;
@@ -904,7 +905,11 @@ dosetopt(int optno, int value, int force, char *new_opts)
 	keyboardhackchar = (value ? '`' : '\0');
     }
     new_opts[optno] = value;
-    if (optno == BANGHIST || optno == SHINSTDIN)
+    if (
+#ifdef MULTIBYTE_SUPPORT
+	optno == MULTIBYTE ||
+#endif
+	optno == BANGHIST || optno == SHINSTDIN)
 	inittyptab();
     return 0;
 }
diff --git a/Src/params.c b/Src/params.c
index 27ea82298..f65aa1e80 100644
--- a/Src/params.c
+++ b/Src/params.c
@@ -475,6 +475,15 @@ static initparam argvparam_pm = IPDEF9("", &pparams, NULL, \
 	((V) && (!(V)->pm || ((V)->pm->node.flags & PM_UNSET) || \
 		 !(V)->pm->node.nam || !*(V)->pm->node.nam))
 
+/*
+ * For named references.  Simple named references are just like scalars
+ * for efficiency, but special named references need get/set functions.
+ */
+#define GETREFNAME(PM) (((PM)->node.flags & PM_SPECIAL) ?	\
+			(PM)->gsu.s->getfn(PM) : (PM)->u.str)
+#define SETREFNAME(PM,S) (((PM)->node.flags & PM_SPECIAL) ?		\
+			  (PM)->gsu.s->setfn(PM,(S)) : ((PM)->u.str = (S)))
+
 static Param argvparam;
 
 /* "parameter table" - hash table containing the parameters
@@ -520,7 +529,7 @@ 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)) {
+    if (pm && (pm->node.flags & PM_AUTOLOAD) && pm->u.str) {
 	char *mn = dupstring(pm->u.str);
 
 	(void)ensurefeature(mn, "p:", (pm->node.flags & PM_AUTOALL) ? NULL :
@@ -536,6 +545,9 @@ getparamnode(HashTable ht, const char *nam)
 		 nam);
 	}
     }
+
+    if (hn && ht == realparamtab && !(hn->flags & PM_UNSET))
+	hn = resolve_nameref((Param)hn, NULL);
     return hn;
 }
 
@@ -732,7 +744,7 @@ split_env_string(char *env, char **name, char **value)
 
     tenv = strcpy(zhalloc(strlen(env) + 1), env);
     for (str = tenv; *str && *str != '='; str++) {
-	if (STOUC(*str) >= 128) {
+	if ((unsigned char) *str >= 128) {
 	    /*
 	     * We'll ignore environment variables with names not
 	     * from the portable character set since we don't
@@ -838,12 +850,11 @@ createparamtable(void)
     setsparam("HOST", ztrdup_metafy(hostnam));
     zfree(hostnam, 256);
 
-    setsparam("LOGNAME", ztrdup_metafy(
+    setsparam("LOGNAME",
 #ifndef DISABLE_DYNAMIC_NSS
-			(str = getlogin()) && *str ?  str :
+	      (str = getlogin()) && *str ? ztrdup_metafy(str) :
 #endif
-				cached_username
-			));
+	      ztrdup(cached_username));
 
 #if !defined(HAVE_PUTENV) && !defined(USE_SET_UNSET_ENV)
     /* Copy the environment variables we are inheriting to dynamic *
@@ -935,8 +946,18 @@ createparamtable(void)
     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++)); );
+    setaparam("signals", sigptr = zalloc((TRAPCOUNT + 1) * sizeof(char *)));
+    t = sigs;
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    while (t - sigs <= SIGCOUNT)
+	*sigptr++ = ztrdup_metafy(*t++);
+    {
+	int sig;
+	for (sig = SIGRTMIN; sig <= SIGRTMAX; sig++)
+	    *sigptr++ = ztrdup_metafy(rtsigname(sig, 0));
+    }
+#endif
+    while ((*sigptr++ = ztrdup_metafy(*t++))) /* empty */ ;
 
     noerrs = 0;
 }
@@ -993,6 +1014,62 @@ createparam(char *name, int flags)
 			 gethashnode2(paramtab, name) :
 			 paramtab->getnode(paramtab, name));
 
+	if (oldpm && (oldpm->node.flags & PM_RO_BY_DESIGN)) {
+	    if (!(flags & PM_LOCAL)) {
+		/* Must call the API for namerefs and specials to work */
+		pm = (Param) paramtab->getnode2(paramtab, oldpm->node.nam);
+		if (!pm || ((pm->node.flags & PM_NAMEREF) &&
+			    pm->level != locallevel)) {
+		    zerr("%s: can't modify read-only parameter", name);
+		    return NULL;
+		}
+	    }
+	    /**
+	     * Implementation note: In the case of a readonly nameref,
+	     * the right thing might be to insert a new global into
+	     * the paramtab and point the local pm->old at it, rather
+	     * than error.  That is why gethashnode2() is called
+	     * first, to avoid skipping up the stack prematurely.
+	     **/
+	}
+
+	if (oldpm && !(flags & PM_NAMEREF) &&
+	    (oldpm->level == locallevel ?
+	     !(oldpm->node.flags & PM_RO_BY_DESIGN) : !(flags & PM_LOCAL)) &&
+	    (oldpm->node.flags & PM_NAMEREF) &&
+	    (oldpm = upscope(oldpm, oldpm->base))) {
+	    Param lastpm;
+	    struct asgment stop;
+	    stop.flags = PM_NAMEREF | (flags & PM_LOCAL);
+	    stop.name = oldpm->node.nam;
+	    stop.value.scalar = GETREFNAME(oldpm);
+	    lastpm = (Param)resolve_nameref(oldpm, &stop);
+	    if (lastpm) {
+		if (lastpm->node.flags & PM_NAMEREF) {
+		    char *refname = GETREFNAME(lastpm);
+		    if (refname && *refname) {
+			name = refname;
+			oldpm = NULL;
+		    } else {
+			if (!(lastpm->node.flags & PM_READONLY)) {
+			    if (flags) {
+				/* Only plain scalar assignment allowed */
+				zerr("%s: can't change type of named reference",
+				     name);	/* Differs from ksh93u+ */
+				return NULL;
+			    }
+			}
+			return lastpm;
+		    }
+		} else {
+		    /* nameref pointing to an unset local */
+		    DPUTS(!(lastpm->node.flags & PM_UNSET),
+			  "BUG: local parameter is not unset");
+		    oldpm = lastpm;
+		}
+	    }
+	}
+
 	DPUTS(oldpm && oldpm->level > locallevel,
 	      "BUG: old local parameter not deleted");
 	if (oldpm && (oldpm->level == locallevel || !(flags & PM_LOCAL))) {
@@ -1009,7 +1086,7 @@ createparam(char *name, int flags)
 		/* POSIXBUILTINS horror: we need to retain 'export' flags */
 		(isset(POSIXBUILTINS) && (oldpm->node.flags & PM_EXPORTED))) {
 		if (oldpm->node.flags & PM_RO_BY_DESIGN) {
-		    zerr("%s: can't change parameter attribute",
+		    zerr("%s: can't modify read-only parameter",
 			 name);
 		    return NULL;
 		}
@@ -1185,6 +1262,26 @@ isident(char *s)
     if (!*s)			/* empty string is definitely not valid */
 	return 0;
 
+    /* This partly duplicates code in itype_end(), but we need to
+     * distinguish the leading namespace at this point to check the
+     * correctness of the identifier that follows
+     */
+    if (*s == '.') {
+	if (idigit(s[1]))
+	    return 0;	/* Namespace must not start with a digit */
+	/* Reject identifiers beginning with a digit in namespaces.
+	 * Move this out below this block to also reject v.1x form.
+	 */
+	if ((ss = itype_end(s + (*s == '.'), IIDENT, 0))) {
+	    if (*ss == '.') {
+		if (!ss[1])
+		    return 0;
+		if (idigit(ss[1]))
+		    s = ss + 1;
+	    }
+	}
+    }
+
     if (idigit(*s)) {
 	/* If the first character is `s' is a digit, then all must be */
 	for (ss = ++s; *ss; ss++)
@@ -1192,7 +1289,7 @@ isident(char *s)
 		break;
     } else {
 	/* Find the first character in `s' not in the iident type table */
-	ss = itype_end(s, IIDENT, 0);
+	ss = itype_end(s, INAMESPC, 0);
     }
 
     /* If the next character is not [, then it is *
@@ -1262,7 +1359,6 @@ getarg(char **str, int *inv, Value v, int a2, zlong *w,
     /* 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':
@@ -1339,8 +1435,13 @@ getarg(char **str, int *inv, Value v, int a2, zlong *w,
 		sav = *t;
 		*t = '\0';
 		s += arglen;
-		sep = escapes ? getkeystring(s, &waste, GETKEYS_SEP, NULL)
-		    : dupstring(s);
+		if (escapes) {
+		    int len;
+		    sep = getkeystring(s, &len, GETKEYS_SEP, NULL);
+		    sep = metafy(sep, len, META_HREALLOC);
+		}
+		else
+		    sep = dupstring(s);
 		*t = sav;
 		s = t + arglen - 1;
 		break;
@@ -1432,10 +1533,14 @@ getarg(char **str, int *inv, Value v, int a2, zlong *w,
     if (ishash && (keymatch || !rev))
 	remnulargs(s);
     if (needtok) {
+	char exe = opts[EXECOPT];
 	s = dupstring(s);
 	if (parsestr(&s))
 	    return 0;
+	if (flags & SCANPM_NOEXEC)
+	    opts[EXECOPT] = 0;
 	singsub(&s);
+	opts[EXECOPT] = exe;
     } else if (rev)
 	remnulargs(s);	/* This is probably always a no-op, but ... */
     if (!rev) {
@@ -1665,7 +1770,7 @@ getarg(char **str, int *inv, Value v, int a2, zlong *w,
 	    /* Searching characters */
 	    int slen;
 	    d = getstrvalue(v);
-	    if (!d || !*d)
+	    if (!d)
 		return 0;
 	    /*
 	     * beg and len are character counts, not raw offsets.
@@ -2047,6 +2152,7 @@ fetchvalue(Value v, char **pptr, int bracks, int flags)
     char *s, *t, *ie;
     char sav, c;
     int ppar = 0;
+    int itype = (flags & SCANPM_NONAMESPC) ? IIDENT : INAMESPC;
 
     s = t = *pptr;
 
@@ -2056,7 +2162,7 @@ fetchvalue(Value v, char **pptr, int bracks, int flags)
 	else
 	    ppar = *s++ - '0';
     }
-    else if ((ie = itype_end(s, IIDENT, 0)) != s)
+    else if ((ie = itype_end(s, itype, 0)) != s)
 	s = ie;
     else if (c == Quest)
 	*s++ = '?';
@@ -2094,8 +2200,16 @@ fetchvalue(Value v, char **pptr, int bracks, int flags)
 	int isvarat;
 
         isvarat = (t[0] == '@' && !t[1]);
-	pm = (Param) paramtab->getnode(paramtab, *t == '0' ? "0" : t);
-	if (sav)
+	if (flags & SCANPM_NONAMEREF)
+	    pm = (Param) paramtab->getnode2(paramtab, *t == '0' ? "0" : t);
+	else
+	    pm = (Param) paramtab->getnode(paramtab, *t == '0' ? "0" : t);
+	if (!pm && *t == '.' && !isident(t)) {
+	    /* badly formed namespace reference */
+	    if (sav)
+		*s = sav;
+	    return NULL;
+	} else if (sav)
 	    *s = sav;
 	*pptr = s;
 	if (!pm || ((pm->node.flags & PM_UNSET) &&
@@ -2105,6 +2219,29 @@ fetchvalue(Value v, char **pptr, int bracks, int flags)
 	    memset(v, 0, sizeof(*v));
 	else
 	    v = (Value) hcalloc(sizeof *v);
+	if ((pm->node.flags & PM_NAMEREF) && !(flags & SCANPM_NONAMEREF)) {
+	    char *refname = GETREFNAME(pm);
+	    if (refname && *refname) {
+		/* only happens for namerefs pointing to array elements */
+		char *ref = dupstring(refname);
+		char *ss = pm->width ? ref + pm->width : NULL;
+		if (ss) {
+		    sav = *ss;
+		    *ss = 0;
+		}
+		Param p1 = (Param)gethashnode2(paramtab, ref);
+		if (!(p1 && (pm = upscope(p1, pm->base))) ||
+		    ((pm->node.flags & PM_UNSET) &&
+		     !(pm->node.flags & PM_DECLARED)))
+		    return NULL;
+		if (ss) {
+		    flags |= SCANPM_NOEXEC;
+		    *ss = sav;
+		    s = dyncat(ss,*pptr);
+		} else
+		    s = *pptr;
+	    }
+	}
 	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);
@@ -2124,7 +2261,7 @@ fetchvalue(Value v, char **pptr, int bracks, int flags)
 		return v;
 	    }
 	} else if (!(flags & SCANPM_ASSIGNING) && v->isarr &&
-		   itype_end(t, IIDENT, 1) != t && isset(KSHARRAYS))
+		   itype_end(t, INAMESPC, 1) != t && isset(KSHARRAYS))
 	    v->end = 1, v->isarr = 0;
     }
     if (!bracks && *s)
@@ -2673,6 +2810,7 @@ assignstrvalue(Value v, char *val, int flags)
         }
 	break;
     }
+    setscope(v->pm);
     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)
@@ -3008,7 +3146,7 @@ check_warn_pm(Param pm, const char *pmtype, int created,
     } else
 	return;
 
-    if (pm->node.flags & PM_SPECIAL)
+    if (pm->node.flags & (PM_SPECIAL|PM_NAMEREF))
 	return;
 
     for (i = funcstack; i; i = i->prev) {
@@ -3080,11 +3218,20 @@ assignsparam(char *s, char *val, int flags)
 	}
     }
     if (!v && !(v = getvalue(&vbuf, &t, 1))) {
-	unqueue_signals();
 	zsfree(val);
+	unqueue_signals();
 	/* errflag |= ERRFLAG_ERROR; */
 	return NULL;
     }
+    if (*val && (v->pm->node.flags & PM_NAMEREF)) {
+	if (!valid_refname(val)) {
+	    zerr("invalid variable name: %s", val);
+	    zsfree(val);
+	    unqueue_signals();
+	    errflag |= ERRFLAG_ERROR;
+	    return NULL;
+	}
+    }
     if (flags & ASSPM_WARN)
 	check_warn_pm(v->pm, "scalar", created, 1);
     v->pm->node.flags &= ~PM_DEFAULTED;
@@ -3111,8 +3258,8 @@ assignsparam(char *s, char *val, int flags)
 			lhs.u.l = lhs.u.l + (zlong)rhs.u.d;
 		}
 		setnumvalue(v, lhs);
-    	    	unqueue_signals();
 		zsfree(val);
+    	    	unqueue_signals();
 		return v->pm; /* avoid later setstrvalue() call */
 	    case PM_ARRAY:
 	    	if (unset(KSHARRAYS)) {
@@ -3137,9 +3284,9 @@ assignsparam(char *s, char *val, int flags)
 	    case PM_INTEGER:
 	    case PM_EFLOAT:
 	    case PM_FFLOAT:
+		zsfree(val);
 		unqueue_signals();
 		zerr("attempt to add to slice of a numeric variable");
-		zsfree(val);
 		return NULL;
 	    case PM_ARRAY:
 	      kshappend:
@@ -3214,7 +3361,7 @@ assignaparam(char *s, char **val, int flags)
 	} 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) {
+	    if ((flags & ASSPM_AUGMENT) && !(v->pm->node.flags & PM_UNSET)) {
 	    	/* insert old value at the beginning of the val array */
 		char **new;
 		int lv = arrlen(val);
@@ -3505,9 +3652,18 @@ assignnparam(char *s, mnumber val, int flags)
 	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 (errflag) {
+	    /* assume error message already output */
+	    unqueue_signals();
+	    return NULL;
+	}
+	if (!pm && !(pm = (Param) paramtab->getnode(paramtab, t))) {
+	    DPUTS(!pm, "BUG: parameter not created");
+	    if (!errflag)
+		zerr("%s: parameter not found", t);
+	    unqueue_signals();
+	    return NULL;
+	}
 	if (ss) {
 	    *ss = '[';
 	} else if (val.type & MN_INTEGER) {
@@ -3578,7 +3734,7 @@ mod_export Param
 setiparam_no_convert(char *s, zlong val)
 {
     /*
-     * If the target is already an integer, thisgets converted
+     * If the target is already an integer, this gets converted
      * back.  Low technology rules.
      */
     char buf[BDIGBUFSIZE];
@@ -3598,7 +3754,8 @@ unsetparam(char *s)
     if ((pm = (Param) (paramtab == realparamtab ?
 		       /* getnode2() to avoid autoloading */
 		       paramtab->getnode2(paramtab, s) :
-		       paramtab->getnode(paramtab, s))))
+		       paramtab->getnode(paramtab, s))) &&
+	!(pm->node.flags & PM_NAMEREF))
 	unsetparam_pm(pm, 0, 1);
     unqueue_signals();
 }
@@ -3617,7 +3774,9 @@ unsetparam_pm(Param pm, int altflag, int exp)
     char *altremove;
 
     if ((pm->node.flags & PM_READONLY) && pm->level <= locallevel) {
-	zerr("read-only variable: %s", pm->node.nam);
+	zerr("read-only %s: %s",
+	     (pm->node.flags & PM_NAMEREF) ? "reference" : "variable",
+	     pm->node.nam);
 	return 1;
     }
     if ((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) {
@@ -3660,12 +3819,15 @@ unsetparam_pm(Param pm, int altflag, int exp)
 		/* fudge things so removenode isn't called */
 		altpm->level = 1;
 	    }
-	    unsetparam_pm(altpm, 1, exp);
+	    unsetparam_pm(altpm, 1, exp); /* This resets pm to empty */
+	    pm->node.flags |= PM_UNSET;   /* so we must repeat this */
 	}
 
 	zsfree(altremove);
-	if (!(pm->node.flags & PM_SPECIAL))
+	if (!(pm->node.flags & PM_SPECIAL)) {
 	    pm->gsu.s = &stdscalar_gsu;
+	    pm->node.flags &= ~PM_ARRAY;
+	}
     }
 
     /*
@@ -4119,7 +4281,8 @@ char *
 tiedarrgetfn(Param pm)
 {
     struct tieddata *dptr = (struct tieddata *)pm->u.data;
-    return *dptr->arrptr ? zjoin(*dptr->arrptr, STOUC(dptr->joinchar), 1) : "";
+    return *dptr->arrptr ?
+	    zjoin(*dptr->arrptr, (unsigned char) dptr->joinchar, 1) : "";
 }
 
 /**/
@@ -4446,7 +4609,7 @@ usernamesetfn(UNUSED(Param pm), char *x)
 	    zwarn("failed to change user ID: %e", errno);
 	else {
 	    zsfree(cached_username);
-	    cached_username = ztrdup(pswd->pw_name);
+	    cached_username = ztrdup_metafy(pswd->pw_name);
 	    cached_uid = pswd->pw_uid;
 	}
     }
@@ -4635,6 +4798,7 @@ setlang(char *x)
 	if ((x = getsparam_u(ln->name)) && *x)
 	    setlocale(ln->category, x);
     unqueue_signals();
+    inittyptab();
 }
 
 /**/
@@ -4658,6 +4822,7 @@ lc_allsetfn(Param pm, char *x)
     else {
 	setlocale(LC_ALL, unmeta(x));
 	clear_mbstate();
+	inittyptab();
     }
 }
 
@@ -4696,6 +4861,7 @@ lcsetfn(Param pm, char *x)
     }
     unqueue_signals();
     clear_mbstate();	/* LC_CTYPE may have changed */
+    inittyptab();
 }
 #endif /* USE_LOCALE */
 
@@ -4815,12 +4981,12 @@ keyboardhacksetfn(UNUSED(Param pm), char *x)
 	    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]))) {
+	    if (!isascii((unsigned char) x[i])) {
 		zwarn("KEYBOARD_HACK can only contain ASCII characters");
 		return;
 	    }
 	}
-	keyboardhackchar = len ? STOUC(x[0]) : '\0';
+	keyboardhackchar = len ? (unsigned char) x[0] : '\0';
 	free(x);
     } else
 	keyboardhackchar = '\0';
@@ -4854,14 +5020,14 @@ histcharssetfn(UNUSED(Param pm), char *x)
 	if (len > 3)
 	    len = 3;
 	for (i = 0; i < len; i++) {
-	    if (!isascii(STOUC(x[i]))) {
+	    if (!isascii((unsigned char) 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';
+	bangchar = len ? (unsigned char) x[0] : '\0';
+	hatchar =  len > 1 ? (unsigned char) x[1] : '\0';
+	hashchar = len > 2 ? (unsigned char) x[2] : '\0';
 	free(x);
     } else {
 	bangchar = '!';
@@ -5083,7 +5249,7 @@ arrfixenv(char *s, char **t)
     if (pm->node.flags & PM_SPECIAL)
 	joinchar = ':';
     else
-	joinchar = STOUC(((struct tieddata *)pm->u.data)->joinchar);
+	joinchar = (unsigned char) ((struct tieddata *)pm->u.data)->joinchar;
 
     addenv(pm, t ? zjoin(t, joinchar, 1) : "");
 }
@@ -5105,9 +5271,9 @@ zputenv(char *str)
     char *ptr;
     int ret;
 
-    for (ptr = str; *ptr && STOUC(*ptr) < 128 && *ptr != '='; ptr++)
+    for (ptr = str; *ptr && (unsigned char) *ptr < 128 && *ptr != '='; ptr++)
 	;
-    if (STOUC(*ptr) >= 128) {
+    if ((unsigned char) *ptr >= 128) {
 	/*
 	 * Environment variables not in the portable character
 	 * set are non-standard and we don't really know of
@@ -5718,7 +5884,8 @@ scanendscope(HashNode hn, UNUSED(int flags))
 		export_param(pm);
 	} else
 	    unsetparam_pm(pm, 0, 0);
-    }
+    } else if ((pm->node.flags & PM_NAMEREF) && pm->base > pm->level)
+	pm->base = locallevel;
 }
 
 
@@ -5769,6 +5936,7 @@ static const struct paramtypes pmtypes[] = {
     { PM_ARRAY, "array", 'a', 0},
     { PM_HASHED, "association", 'A', 0},
     { 0, "local", 0, PMTF_TEST_LEVEL},
+    { PM_HIDE, "hide", 'h', 0 },
     { 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},
@@ -5778,7 +5946,8 @@ static const struct paramtypes pmtypes[] = {
     { PM_TAGGED, "tagged", 't', 0},
     { PM_EXPORTED, "exported", 'x', 0},
     { PM_UNIQUE, "unique", 'U', 0},
-    { PM_TIED, "tied", 'T', 0}
+    { PM_TIED, "tied", 'T', 0},
+    { PM_NAMEREF, "nameref", 'n', 0}
 };
 
 #define PMTYPES_SIZE ((int)(sizeof(pmtypes)/sizeof(struct paramtypes)))
@@ -5875,7 +6044,12 @@ printparamnode(HashNode hn, int printflags)
 {
     Param p = (Param) hn;
     Param peer = NULL;
+    int altname = 0;
 
+    if (!(p->node.flags & PM_HASHELEM) &&
+	!(printflags & PRINT_WITH_NAMESPACE) && *(p->node.nam) == '.')
+	return;
+    
     if (p->node.flags & PM_UNSET) {
 	if ((printflags & (PRINT_POSIX_READONLY|PRINT_POSIX_EXPORT) &&
 	     p->node.flags & (PM_READONLY|PM_EXPORTED)) ||
@@ -5893,13 +6067,21 @@ printparamnode(HashNode hn, int printflags)
 	printflags |= PRINT_NAMEONLY;
 
     if (printflags & (PRINT_TYPESET|PRINT_POSIX_READONLY|PRINT_POSIX_EXPORT)) {
-	if (p->node.flags & (PM_RO_BY_DESIGN|PM_AUTOLOAD)) {
+	if (p->node.flags & PM_AUTOLOAD) {
 	    /*
 	     * It's not possible to restore the state of
 	     * these, so don't output.
 	     */
 	    return;
 	}
+	if (p->node.flags & PM_RO_BY_DESIGN) {
+	    /*
+	     * Compromise: cannot be restored out of context,
+	     * but show anyway if printed in scope of declaration
+	     */
+	    if (p->level != locallevel || p->level == 0)
+		return;
+	}
 	/*
 	 * The zsh variants of export -p/readonly -p also report other
 	 * flags to indicate other attributes or scope. The POSIX variants
@@ -5908,16 +6090,26 @@ printparamnode(HashNode hn, int printflags)
 	if (printflags & PRINT_POSIX_EXPORT) {
 	    if (!(p->node.flags & PM_EXPORTED))
 		return;
+	    altname = 'x';
 	    printf("export ");
 	} else if (printflags & PRINT_POSIX_READONLY) {
 	    if (!(p->node.flags & PM_READONLY))
 		return;
+	    altname = 'r';
 	    printf("readonly ");
-	} else 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 ");
+	  if (p->level && p->level >= locallevel)
+		printf("local ");
+	    else {
+		altname = 'x';
+		printf("export ");
+	    }
+	} else if (locallevel && p->level >= locallevel) {
+	    if (p->node.flags & PM_EXPORTED)
+		printf("local ");
+	    else
+		printf("typeset ");	    /* printf("local "); */
 	} else if (locallevel) {
 	    printf("typeset -g ");
 	} else
@@ -5931,9 +6123,24 @@ printparamnode(HashNode hn, int printflags)
 
 	for (pmptr = pmtypes, i = 0; i < PMTYPES_SIZE; i++, pmptr++) {
 	    int doprint = 0;
+
+	    if (altname && altname == pmptr->typeflag)
+		continue;
+
 	    if (pmptr->flags & PMTF_TEST_LEVEL) {
-		if (p->level)
+		if (p->level) {
+		    /*
+		    if ((p->node.flags & PM_SPECIAL) &&
+			(p->node.flags & PM_LOCAL) &&
+			!(p->node.flags & PM_HIDE)) {
+			if (doneminus)
+			    putchar(' ');
+			printf("+h ");
+			doneminus = 0;
+		    }
+		    */
 		    doprint = 1;
+		}
 	    } else if ((pmptr->binflag != PM_EXPORTED || p->level ||
 			(p->node.flags & (PM_LOCAL|PM_ARRAY|PM_HASHED))) &&
 		       (p->node.flags & pmptr->binflag))
@@ -6018,7 +6225,7 @@ printparamnode(HashNode hn, int printflags)
 	 * append the join char for tied parameters if different from colon
 	 * for typeset -p output.
 	 */
-	unsigned char joinchar = STOUC(((struct tieddata *)peer->u.data)->joinchar);
+	unsigned char joinchar = (unsigned char) ((struct tieddata *)peer->u.data)->joinchar;
 	if (joinchar != ':') {
 	    char buf[2];
 	    buf[0] = joinchar;
@@ -6032,3 +6239,220 @@ printparamnode(HashNode hn, int printflags)
     else if (!(printflags & PRINT_KV_PAIR))
 	putchar('\n');
 }
+
+/**/
+mod_export HashNode
+resolve_nameref(Param pm, const Asgment stop)
+{
+    HashNode hn = (HashNode)pm;
+    const char *seek = stop ? stop->value.scalar : NULL;
+
+    if (pm && (pm->node.flags & PM_NAMEREF)) {
+	char *refname = GETREFNAME(pm);
+	if (pm->node.flags & (PM_UNSET|PM_TAGGED)) {
+	    /* Semaphore with createparam() */
+	    pm->node.flags &= ~PM_UNSET;
+	    if (pm->node.flags & PM_NEWREF)	/* See setloopvar() */
+		return NULL;
+	    if (refname && *refname && (pm->node.flags & PM_TAGGED))
+		pm->node.flags |= PM_SELFREF;	/* See setscope() */
+	    return (HashNode) pm;
+	} else if (refname) {
+	    if ((pm->node.flags & PM_TAGGED) ||
+		(stop && strcmp(refname, stop->name) == 0)) {
+		/* zwarnnam(refname, "invalid self reference"); */
+		return stop ? (HashNode)pm : NULL;
+	    }
+	    if (*refname)
+		seek = refname;
+	}
+    }
+    else if (pm) {
+	if (!(stop && (stop->flags & PM_NAMEREF)))
+	    return (HashNode)pm;
+	if (!(pm->node.flags & PM_NAMEREF))
+	    return (pm->level < locallevel ? NULL : (HashNode)pm);
+    }
+    if (seek) {
+	queue_signals();
+	/* pm->width is the offset of any subscript */
+	if (pm && (pm->node.flags & PM_NAMEREF) && pm->width) {
+	    if (stop) {
+		if (stop->flags & PM_NAMEREF)
+		    hn = (HashNode)pm;
+		else
+		    hn = NULL;
+	    } else {
+		/* this has to be the end of any chain */
+		hn = (HashNode)pm;	/* see fetchvalue() */
+	    }
+	} else if ((hn = gethashnode2(realparamtab, seek))) {
+	    if (pm) {
+		if (!(stop && (stop->flags & (PM_LOCAL)))) {
+		    int scope = ((pm->node.flags & PM_NAMEREF) ?
+				 ((pm->node.flags & PM_UPPER) ? -1 :
+				  pm->base) : ((Param)hn)->level);
+		    hn = (HashNode)upscope((Param)hn, scope);
+		}
+		/* user can't tag a nameref, safe for loop detection */
+		pm->node.flags |= PM_TAGGED;
+	    }
+	    if (hn) {
+		if (hn->flags & PM_AUTOLOAD)
+		    hn = getparamnode(realparamtab, seek);
+		if (!(hn->flags & PM_UNSET))
+		    hn = resolve_nameref((Param)hn, stop);
+	    }
+	    if (pm)
+		pm->node.flags &= ~PM_TAGGED;
+	} else if (stop && (stop->flags & PM_NAMEREF))
+	    hn = (pm && (pm->node.flags & PM_NEWREF)) ? NULL : (HashNode)pm;
+	unqueue_signals();
+    }
+
+    return hn;
+}
+
+/**/
+mod_export void
+setloopvar(char *name, char *value)
+{
+  Param pm = (Param) gethashnode2(realparamtab, name);
+
+  if (pm && (pm->node.flags & PM_NAMEREF)) {
+      if (pm->node.flags & PM_READONLY) {
+	  /* Bash error is: "%s: readonly variable" */
+	  zerr("read-only reference: %s", pm->node.nam);
+	  return;
+      }
+      pm->base = pm->width = 0;
+      SETREFNAME(pm, ztrdup(value));
+      pm->node.flags &= ~PM_UNSET;
+      pm->node.flags |= PM_NEWREF;
+      setscope(pm);
+      pm->node.flags &= ~PM_NEWREF;
+  } else
+      setsparam(name, value);
+}
+
+/**/
+static void
+setscope(Param pm)
+{
+    queue_signals();
+    if (pm->node.flags & PM_NAMEREF) do {
+	Param basepm;
+	struct asgment stop;
+	char *refname = GETREFNAME(pm);
+	char *t = refname ? itype_end(refname, INAMESPC, 0) : NULL;
+	int q = queue_signal_level();
+
+	/* Temporarily change nameref to array parameter itself */
+	if (t && *t == '[')
+	    *t = 0;
+	else
+	    t = 0;
+	stop.name = "";
+	stop.value.scalar = NULL;
+	stop.flags = PM_NAMEREF;
+	if (locallevel && !(pm->node.flags & PM_UPPER))
+	    stop.flags |= PM_LOCAL;
+	dont_queue_signals();	/* Prevent unkillable loops */
+	basepm = (Param)resolve_nameref(pm, &stop);
+	restore_queue_signals(q);
+	if (t) {
+	    pm->width = t - refname;
+	    *t = '[';
+	}
+	if (basepm) {
+	    if (basepm->node.flags & PM_NAMEREF) {
+		if (pm == basepm) {
+		    if (pm->node.flags & PM_SELFREF) {
+			/* Loop signalled by resolve_nameref() */
+			if (upscope(pm, pm->base) == pm) {
+			    zerr("%s: invalid self reference", refname);
+			    unsetparam_pm(pm, 0, 1);
+			    break;
+			}
+			pm->node.flags &= ~PM_SELFREF;
+		    } else if (pm->base == pm->level) {
+			if (refname && *refname &&
+			    strcmp(pm->node.nam, refname) == 0) {
+			    zerr("%s: invalid self reference", refname);
+			    unsetparam_pm(pm, 0, 1);
+			    break;
+			}
+		    }
+		} else if ((t = GETREFNAME(basepm))) {
+		    if (basepm->base <= basepm->level &&
+			strcmp(pm->node.nam, t) == 0) {
+			zerr("%s: invalid self reference", refname);
+			unsetparam_pm(pm, 0, 1);
+			break;
+		    }
+		}
+	    } else
+		pm->base = basepm->level;
+	}
+	if (pm->base > pm->level) {
+	    if (EMULATION(EMULATE_KSH)) {
+		zerr("%s: global reference cannot refer to local variable",
+		      pm->node.nam);
+		unsetparam_pm(pm, 0, 1);
+	    } else if (isset(WARNNESTEDVAR))
+		zwarn("reference %s in enclosing scope set to local variable %s",
+		      pm->node.nam, refname);
+	}
+	if (refname && upscope(pm, pm->base) == pm &&
+	    strcmp(pm->node.nam, refname) == 0) {
+	    zerr("%s: invalid self reference", refname);
+	    unsetparam_pm(pm, 0, 1);
+	}
+    } while (0);
+    unqueue_signals();
+}
+
+/**/
+mod_export Param
+upscope(Param pm, int reflevel)
+{
+    Param up = pm->old;
+    while (up && up->level >= reflevel) {
+	pm = up;
+	up = up->old;
+    }
+    if (reflevel < 0 && locallevel > 0)
+	return pm->level == locallevel ? up : pm;
+    return pm;
+}
+
+/**/
+mod_export int
+valid_refname(char *val)
+{
+    char *t = itype_end(val, INAMESPC, 0);
+
+    if (idigit(*val))
+	return 0;
+    if (*t != 0) {
+	if (*t == '[') {
+	    tokenize(t = dupstring(t+1));
+	    while ((t = parse_subscript(t, 0, ']')) && *t++ == Outbrack) {
+		if (*t == Inbrack)
+		    ++t;
+		else
+		    break;
+	    }
+	    if (t && *t) {
+		/* zwarn("%s: stuff after subscript: %s", val, t); */
+		t = NULL;
+	    }
+	} else if (t[1] || !(*t == '!' || *t == '?' ||
+			     *t == '$' || *t == '-' ||
+			     *t == '0' || *t == '_')) {
+	    /* Skipping * @ # because of doshfunc() implementation */
+	    t = NULL;
+	}
+    }
+    return !!t;
+}
diff --git a/Src/parse.c b/Src/parse.c
index 5054e59d5..334365649 100644
--- a/Src/parse.c
+++ b/Src/parse.c
@@ -120,7 +120,7 @@ struct heredocs *hdocs;
  *     - if not (type & Z_END), followed by next WC_LIST
  *
  *   WC_SUBLIST
- *     - data contains type (&&, ||, END) and flags (coprog, not)
+ *     - data contains type (&&, ||, END) and flags (coproc, not)
  *     - followed by code for sublist
  *     - if not (type == END), followed by next WC_SUBLIST
  *
@@ -433,9 +433,9 @@ ecstrcode(char *s)
 	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 4: c |= ((wordcode) (unsigned char) s[2]) << 19;
+	case 3: c |= ((wordcode) (unsigned char) s[1]) << 11;
+	case 2: c |= ((wordcode) (unsigned char) s[0]) <<  3; break;
 	case 1: c = (t ? 7 : 6); break;
 	}
 	return c;
@@ -601,7 +601,7 @@ clear_hdocs(void)
  *			| sublist [ SEPER | AMPER | AMPERBANG ]
  *
  * cmdsubst indicates our event is part of a command-style
- * substitution terminated by the token indicationg, usual closing
+ * substitution terminated by the token indicated, usually closing
  * parenthesis.  In other cases endtok is ENDINPUT.
  */
 
@@ -1935,6 +1935,8 @@ par_simple(int *cmplx, int nr)
 
 		if (*ptr == Outbrace && ptr > tokstr + 1)
 		{
+		    /* Should we allow namespace FDs, {.foo.bar}>&file ? *
+		     * If so, change IIDENT to INAMESPC here             */
 		    if (itype_end(tokstr+1, IIDENT, 0) >= ptr)
 		    {
 			char *toksave = tokstr;
@@ -2055,6 +2057,9 @@ par_simple(int *cmplx, int nr)
 	    if (isset(EXECOPT) && hasalias && !isset(ALIASFUNCDEF) && argc &&
 		hasalias != input_hasalias()) {
 		zwarn("defining function based on alias `%s'", hasalias);
+		herrflush();
+		if (noerrs != 2)
+		    errflag |= ERRFLAG_ERROR;
 		YYERROR(oecused);
 	    }
 
@@ -2387,7 +2392,7 @@ par_nl_wordlist(void)
  */
 
 /**/
-void (*condlex) _((void)) = zshlex;
+void (*condlex) (void) = zshlex;
 
 /*
  * cond	: cond_1 { SEPER } [ DBAR { SEPER } cond ]
@@ -2725,11 +2730,10 @@ yyerror(int noerr)
 	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
+	if (t0) {
+	    t = metafy(t, t0, META_STATIC);
+	    zwarn("parse error near `%s%s'", t, t0 == 20 ? "..." : "");
+	} else
 	    zwarn("parse error");
     }
     if (!noerr && noerrs != 2)
@@ -3214,12 +3218,14 @@ bin_zcompile(char *nam, char **args, Options ops, UNUSED(int func))
 
     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'),
+	dump = unmetafy(dyncat(*args, FD_EXT), NULL);
+	ret = build_dump(nam, dump, args, OPT_ISSET(ops,'U'),
 			 map, flags);
 	unqueue_signals();
 	return ret;
     }
-    dump = (strsfx(FD_EXT, *args) ? *args : dyncat(*args, FD_EXT));
+    dump = (strsfx(FD_EXT, *args) ? dupstring(*args) : dyncat(*args, FD_EXT));
+    unmetafy(dump, NULL);
 
     queue_signals();
     ret = ((OPT_ISSET(ops,'c') || OPT_ISSET(ops,'a')) ?
@@ -3397,6 +3403,7 @@ build_dump(char *nam, char *dump, char **files, int ali, int map, int flags)
 
     for (hlen = FD_PRELEN, tlen = 0; *files; files++) {
 	struct stat st;
+	char *fnam;
 
 	if (check_cond(*files, "k")) {
 	    flags = (flags & ~(FDHF_KSHLOAD | FDHF_ZSHLOAD)) | FDHF_KSHLOAD;
@@ -3405,7 +3412,8 @@ build_dump(char *nam, char *dump, char **files, int ali, int map, int flags)
 	    flags = (flags & ~(FDHF_KSHLOAD | FDHF_ZSHLOAD)) | FDHF_ZSHLOAD;
 	    continue;
 	}
-	if ((fd = open(*files, O_RDONLY)) < 0 ||
+	fnam = unmeta(*files);
+	if ((fd = open(fnam, O_RDONLY)) < 0 ||
 	    fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) ||
 	    (flen = lseek(fd, 0, 2)) == -1) {
 	    if (fd >= 0)
diff --git a/Src/pattern.c b/Src/pattern.c
index e947d1216..1e0ae88d9 100644
--- a/Src/pattern.c
+++ b/Src/pattern.c
@@ -239,7 +239,7 @@ typedef unsigned long zrange_t;
  * a bit tricky...
  */
 #define WCHAR_INVALID(ch)			\
-    ((wchar_t) (0xDC00 + STOUC(ch)))
+    ((wchar_t) (0xDC00 + (unsigned char) ch))
 #endif /* MULTIBYTE_SUPPORT */
 
 /*
@@ -346,7 +346,7 @@ metacharinc(char **x)
      * 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 (!(patglobflags & GF_MULTIBYTE) || !((unsigned char) *inptr & 0x80))
     {
 	if (itok(*inptr))
 	    inchar = ztokens[*inptr++ - Pound];
@@ -357,7 +357,7 @@ metacharinc(char **x)
 	    inchar = *inptr++;
 	}
 	*x = inptr;
-	return (wchar_t)STOUC(inchar);
+	return (wchar_t)(unsigned char) inchar;
     }
 
     while (*inptr) {
@@ -1181,8 +1181,8 @@ pattern_range_to_string(char *rangestr, char *outstr)
     int len = 0;
 
     while (*rangestr) {
-	if (imeta(STOUC(*rangestr))) {
-	    int swtype = STOUC(*rangestr) - STOUC(Meta);
+	if (imeta((unsigned char) *rangestr)) {
+	    int swtype = (unsigned char) *rangestr - (unsigned char) Meta;
 
 	    if (swtype == 0) {
 		/* Ordindary metafied character */
@@ -1278,17 +1278,17 @@ patcomppiece(int *flagp, int paren)
 	kshchar = '\0';
 	if (*patparse && patparse[1] == Inpar) {
 	    if (*patparse == zpc_special[ZPC_KSH_PLUS])
-		kshchar = STOUC('+');
+		kshchar = (unsigned char) '+';
 	    else if (*patparse == zpc_special[ZPC_KSH_BANG])
-		kshchar = STOUC('!');
+		kshchar = (unsigned char) '!';
 	    else if (*patparse == zpc_special[ZPC_KSH_BANG2])
-		kshchar = STOUC('!');
+		kshchar = (unsigned char) '!';
 	    else if (*patparse == zpc_special[ZPC_KSH_AT])
-		kshchar = STOUC('@');
+		kshchar = (unsigned char) '@';
 	    else if (*patparse == zpc_special[ZPC_KSH_STAR])
-		kshchar = STOUC('*');
+		kshchar = (unsigned char) '*';
 	    else if (*patparse == zpc_special[ZPC_KSH_QUEST])
-		kshchar = STOUC('?');
+		kshchar = (unsigned char) '?';
 	}
 
 	/*
@@ -1468,7 +1468,8 @@ patcomppiece(int *flagp, int paren)
 			ch = range_type(patparse, len);
 			patparse = nptr + 2;
 			if (ch != PP_UNKWN)
-			    patadd(NULL, STOUC(Meta) + ch, 1, PA_NOALIGN);
+			    patadd(NULL, (unsigned char) Meta + ch, 1,
+				PA_NOALIGN);
 			continue;
 		}
 		charstart = patparse;
@@ -1476,10 +1477,10 @@ patcomppiece(int *flagp, int paren)
 
 		if (*patparse == Dash && patparse[1] &&
 		    patparse[1] != Outbrack) {
-		    patadd(NULL, STOUC(Meta)+PP_RANGE, 1, PA_NOALIGN);
+		    patadd(NULL, (unsigned char) Meta+PP_RANGE, 1, PA_NOALIGN);
 		    if (itok(*charstart)) {
-			patadd(0, STOUC(ztokens[*charstart - Pound]), 1,
-			       PA_NOALIGN);
+			patadd(0, (unsigned char) ztokens[*charstart - Pound],
+			       1, PA_NOALIGN);
 		    } else {
 			patadd(charstart, 0, patparse-charstart, PA_NOALIGN);
 		    }
@@ -1487,7 +1488,7 @@ patcomppiece(int *flagp, int paren)
 		    METACHARINC(patparse);
 		}
 		if (itok(*charstart)) {
-		    patadd(0, STOUC(ztokens[*charstart - Pound]), 1,
+		    patadd(0, (unsigned char) ztokens[*charstart - Pound], 1,
 			   PA_NOALIGN);
 		} else {
 		    patadd(charstart, 0, patparse-charstart, PA_NOALIGN);
@@ -1910,8 +1911,8 @@ 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);
+    if (!(patglobflags & GF_MULTIBYTE) || !((unsigned char) *x & 0x80))
+	return (wchar_t) (unsigned char) *x;
 
     ret = mbrtowc(&wc, x, y-x, &shiftstate);
 
@@ -1937,7 +1938,7 @@ charnext(char *x, char *y)
     wchar_t wc;
     size_t ret;
 
-    if (!(patglobflags & GF_MULTIBYTE) || !(STOUC(*x) & 0x80))
+    if (!(patglobflags & GF_MULTIBYTE) || !((unsigned char) *x & 0x80))
 	return x + 1;
 
     ret = mbrtowc(&wc, x, y-x, &shiftstate);
@@ -1965,8 +1966,8 @@ 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)++);
+    if (!(patglobflags & GF_MULTIBYTE) || !((unsigned char) **x & 0x80))
+	return (wchar_t) (unsigned char) *(*x)++;
 
     ret = mbrtowc(&wc, *x, y-*x, &shiftstate);
 
@@ -2025,13 +2026,13 @@ charsub(char *x, char *y)
 #else /* no MULTIBYTE_SUPPORT */
 
 /* Get a character from the start point in a string */
-#define CHARREF(x, y)	(STOUC(*(x)))
+#define CHARREF(x, y)	((unsigned char) (*(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)++))
+#define CHARREFINC(x, y, z)	((unsigned char) (*(x)++))
 /* Counter the number of characters between two pointers, smaller first */
 #define CHARSUB(x,y)	((y) - (x))
 
@@ -2890,7 +2891,7 @@ patmatch(Upat prog)
 		}
 		if (!no && P_OP(next) == P_EXACTLY &&
 		    (!P_LS_LEN(next) ||
-		     !idigit(STOUC(*P_LS_STR(next)))) &&
+		     !idigit((unsigned char) (*P_LS_STR(next)))) &&
 		    !(patglobflags & 0xff))
 		    return 0;
 		patinput = --save;
@@ -2986,14 +2987,15 @@ patmatch(Upat prog)
 	case P_EXCSYNC:
 	    /* See the P_EXCLUDE code below for where syncptr comes from */
 	    {
-		unsigned char *syncptr;
+		unsigned char *syncstart, *syncptr, *ptr;
 		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);
+		syncstart = P_OPERAND(after)->p;
+		syncptr = syncstart + (patinput - patinstart);
 		/*
 		 * If we already matched from here, this time we fail.
 		 * See WBRANCH code for story about error count.
@@ -3008,6 +3010,23 @@ patmatch(Upat prog)
 		 * failed anyway.
 		 */
 		*syncptr = errsfound + 1;
+		/*
+		 * Because of backtracking, any match before this point
+		 * can't apply to the current branch we're on so is now
+		 * a failure --- this can happen if, on a previous
+		 * branch, we initially marked a success before failing
+		 * on a later part of the pattern after marking up the
+		 * P_EXCSYNC (even an end anchor will have this effect).
+		 * To make sure we record the current match point
+		 * correctly, mark those down now.
+		 *
+		 * This might have side effects on the efficiency of
+		 * pathological cases involving nested branches.  To
+		 * fix that we'd probably need to record matches on
+		 * different branches separately.
+		 */
+		for (ptr = syncstart; ptr < syncptr; ++ptr)
+		    *ptr = 0;
 	    }
 	    break;
 	case P_EXCEND:
@@ -3600,8 +3619,8 @@ mb_patmatchrange(char *range, wchar_t ch, int zmb_ind, wint_t *indptr, int *mtp)
      * ranges specially.
      */
     while (*range) {
-	if (imeta(STOUC(*range))) {
-	    int swtype = STOUC(*range++) - STOUC(Meta);
+	if (imeta((unsigned char) *range)) {
+	    int swtype = (unsigned char) *range++ - (unsigned char) Meta;
 	    if (mtp)
 		*mtp = swtype;
 	    switch (swtype) {
@@ -3672,6 +3691,7 @@ mb_patmatchrange(char *range, wchar_t ch, int zmb_ind, wint_t *indptr, int *mtp)
 		    return 1;
 		break;
 	    case PP_IDENT:
+		/* Could use INAMESPC here? */
 		if (wcsitype(ch, IIDENT))
 		    return 1;
 		break;
@@ -3753,8 +3773,8 @@ mb_patmatchindex(char *range, wint_t ind, wint_t *chr, int *mtp)
     *mtp = 0;
 
     while (*range) {
-	if (imeta(STOUC(*range))) {
-	    int swtype = STOUC(*range++) - STOUC(Meta);
+	if (imeta((unsigned char) *range)) {
+	    int swtype = (unsigned char) *range++ - (unsigned char) Meta;
 	    switch (swtype) {
 	    case 0:
 		range--;
@@ -3845,13 +3865,13 @@ patmatchrange(char *range, int ch, int *indptr, int *mtp)
      * ranges specially.
      */
     for (; *range; range++) {
-	if (imeta(STOUC(*range))) {
-	    int swtype = STOUC(*range) - STOUC(Meta);
+	if (imeta((unsigned char) *range)) {
+	    int swtype = (unsigned char) *range - (unsigned char) Meta;
 	    if (mtp)
 		*mtp = swtype;
 	    switch (swtype) {
 	    case 0:
-		if (STOUC(*++range ^ 32) == ch)
+		if ((unsigned char) (*++range ^ 32) == ch)
 		    return 1;
 		break;
 	    case PP_ALPHA:
@@ -3931,9 +3951,9 @@ patmatchrange(char *range, int ch, int *indptr, int *mtp)
 		break;
 	    case PP_RANGE:
 		range++;
-		r1 = STOUC(UNMETA(range));
+		r1 = (unsigned char) UNMETA(range);
 		METACHARINC(range);
-		r2 = STOUC(UNMETA(range));
+		r2 = (unsigned char) UNMETA(range);
 		if (*range == Meta)
 		    range++;
 		if (r1 <= ch && ch <= r2) {
@@ -3955,7 +3975,7 @@ patmatchrange(char *range, int ch, int *indptr, int *mtp)
 		DPUTS(1, "BUG: unknown metacharacter in range.");
 		break;
 	    }
-	} else if (STOUC(*range) == ch) {
+	} else if ((unsigned char) *range == ch) {
 	    if (mtp)
 		*mtp = 0;
 	    return 1;
@@ -3989,12 +4009,12 @@ patmatchindex(char *range, int ind, int *chr, int *mtp)
     *mtp = 0;
 
     for (; *range; range++) {
-	if (imeta(STOUC(*range))) {
-	    int swtype = STOUC(*range) - STOUC(Meta);
+	if (imeta((unsigned char) *range)) {
+	    int swtype = (unsigned char) *range - (unsigned char) Meta;
 	    switch (swtype) {
 	    case 0:
 		/* ordinary metafied character */
-		rchr = STOUC(*++range) ^ 32;
+		rchr = (unsigned char) *++range ^ 32;
 		if (!ind) {
 		    *chr = rchr;
 		    return 1;
@@ -4028,9 +4048,9 @@ patmatchindex(char *range, int ind, int *chr, int *mtp)
 
 	    case PP_RANGE:
 		range++;
-		r1 = STOUC(UNMETA(range));
+		r1 = (unsigned char) UNMETA(range);
 		METACHARINC(range);
-		r2 = STOUC(UNMETA(range));
+		r2 = (unsigned char) UNMETA(range);
 		if (*range == Meta)
 		    range++;
 		rdiff = r2 - r1; 
@@ -4050,7 +4070,7 @@ patmatchindex(char *range, int ind, int *chr, int *mtp)
 	    }
 	} else {
 	    if (!ind) {
-		*chr = STOUC(*range);
+		*chr = (unsigned char) *range;
 		return 1;
 	    }
 	}
diff --git a/Src/prompt.c b/Src/prompt.c
index 092de63a4..e10b05215 100644
--- a/Src/prompt.c
+++ b/Src/prompt.c
@@ -30,10 +30,20 @@
 #include "zsh.mdh"
 #include "prompt.pro"
 
-/* text attribute mask */
+/* current text attributes */
 
 /**/
-mod_export zattr txtattrmask;
+mod_export zattr txtcurrentattrs;
+
+/* pending changes for attributes */
+
+/**/
+mod_export zattr txtpendingattrs;
+
+/* mask of attributes with an unknown state */
+
+/**/
+mod_export zattr txtunknownattrs;
 
 /* the command stack for use with %_ in prompts */
 
@@ -160,15 +170,11 @@ promptpath(char *p, int npath, int tilde)
  * 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
- * consistently.  Other parts of the shell should not need to use it.
  */
 
 /**/
 mod_export char *
-promptexpand(char *s, int ns, char *rs, char *Rs, zattr *txtchangep)
+promptexpand(char *s, int ns, char *rs, char *Rs)
 {
     struct buf_vars new_vars;
 
@@ -212,7 +218,7 @@ promptexpand(char *s, int ns, char *rs, char *Rs, zattr *txtchangep)
     new_vars.bp1 = NULL;
     new_vars.truncwidth = 0;
 
-    putpromptchar(1, '\0', txtchangep);
+    putpromptchar(1, '\0');
     addbufspc(2);
     if (new_vars.dontcount)
 	*new_vars.bp++ = Outpar;
@@ -235,6 +241,68 @@ promptexpand(char *s, int ns, char *rs, char *Rs, zattr *txtchangep)
     return new_vars.buf;
 }
 
+/* Get the escape sequence for a given attribute. */
+/**/
+mod_export char *
+zattrescape(zattr atr, int *len)
+{
+    struct buf_vars new_vars;
+    zattr savecurrent = txtcurrentattrs;
+    zattr saveunknown = txtunknownattrs;
+
+    memset(&new_vars, 0, sizeof(new_vars));
+    new_vars.last = bv;
+    bv = &new_vars;
+    new_vars.bufspc = 256;
+    new_vars.bp = new_vars.bufline = new_vars.buf = zshcalloc(new_vars.bufspc);
+    new_vars.dontcount = 1;
+
+    txtunknownattrs = 0;
+    treplaceattrs(atr);
+    applytextattributes(TSC_PROMPT);
+
+    bv = new_vars.last;
+
+    txtpendingattrs = txtcurrentattrs = savecurrent;
+    txtunknownattrs = saveunknown;
+
+    return unmetafy(new_vars.buf, len);
+}
+
+/* Parse the argument for %H */
+/**/
+mod_export char *
+parsehighlight(char *arg, char endchar, zattr *atr)
+{
+    static int entered = 0;
+    char *var = ".zle.hlgroups";
+    struct value vbuf;
+    Value v;
+    char *ep, *attrs;
+    if ((ep = strchr(arg, endchar)))
+	*ep = '\0';
+    if (!entered && (v = getvalue(&vbuf, &var, 0)) &&
+	    PM_TYPE(v->pm->node.flags) == PM_HASHED)
+    {
+	Param node;
+	HashTable ht = v->pm->gsu.h->getfn(v->pm);
+	if (ht && (node = (Param) ht->getnode(ht, arg))) {
+	    attrs = node->gsu.s->getfn(node);
+	    entered = 1;
+	    if (match_highlight(attrs, atr, 0) == attrs)
+		*atr = TXT_ERROR;
+	} else
+	    *atr = TXT_ERROR;
+    } else
+	*atr = TXT_ERROR;
+    if (ep)
+	*ep++ = endchar;
+    else
+	ep = strchr(arg, '\0');
+    entered = 0;
+    return ep;
+}
+
 /* Parse the argument for %F and %K */
 static zattr
 parsecolorchar(zattr arg, int is_fg)
@@ -253,7 +321,7 @@ parsecolorchar(zattr arg, int is_fg)
 	    *ep = '\0';
 	    /* expand the contents of the argument so you can use
 	     * %v for example */
-	    coll = col = promptexpand(bv->fm, 0, NULL, NULL, NULL);
+	    coll = col = promptexpand(bv->fm, 0, NULL, NULL);
 	    *ep = oc;
 	    arg = match_colour((const char **)&coll, is_fg, 0);
 	    free(col);
@@ -278,7 +346,7 @@ parsecolorchar(zattr arg, int is_fg)
 
 /**/
 static int
-putpromptchar(int doprint, int endchar, zattr *txtchangep)
+putpromptchar(int doprint, int endchar)
 {
     char *ss, *hostnam;
     int t0, arg, test, sep, j, numjobs, len;
@@ -430,10 +498,9 @@ putpromptchar(int doprint, int endchar, zattr *txtchangep)
 		/* 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)) {
+		if (!putpromptchar(test == 1 && doprint, sep) ||
+				   !*++bv->fm ||
+		    !putpromptchar(test == 0 && doprint, ')')) {
 		    bv->truncwidth = otruncwidth;
 		    return 0;
 		}
@@ -519,71 +586,67 @@ putpromptchar(int doprint, int endchar, zattr *txtchangep)
 		unqueue_signals();
 		break;
 	    case 'S':
-		txtchangeset(txtchangep, TXTSTANDOUT, TXTNOSTANDOUT);
-		txtset(TXTSTANDOUT);
-		tsetcap(TCSTANDOUTBEG, TSC_PROMPT);
+		tsetattrs(TXTSTANDOUT);
+	        applytextattributes(TSC_PROMPT);
 		break;
 	    case 's':
-		txtchangeset(txtchangep, TXTNOSTANDOUT, TXTSTANDOUT);
-		txtunset(TXTSTANDOUT);
-		tsetcap(TCSTANDOUTEND, TSC_PROMPT|TSC_DIRTY);
+		tunsetattrs(TXTSTANDOUT);
+	        applytextattributes(TSC_PROMPT);
 		break;
 	    case 'B':
-		txtchangeset(txtchangep, TXTBOLDFACE, TXTNOBOLDFACE);
-		txtset(TXTBOLDFACE);
-		tsetcap(TCBOLDFACEBEG, TSC_PROMPT|TSC_DIRTY);
+		tsetattrs(TXTBOLDFACE);
+	        applytextattributes(TSC_PROMPT);
 		break;
 	    case 'b':
-		txtchangeset(txtchangep, TXTNOBOLDFACE, TXTBOLDFACE);
-		txtunset(TXTBOLDFACE);
-		tsetcap(TCALLATTRSOFF, TSC_PROMPT|TSC_DIRTY);
+		tunsetattrs(TXTBOLDFACE);
+	        applytextattributes(TSC_PROMPT);
 		break;
 	    case 'U':
-		txtchangeset(txtchangep, TXTUNDERLINE, TXTNOUNDERLINE);
-		txtset(TXTUNDERLINE);
-		tsetcap(TCUNDERLINEBEG, TSC_PROMPT);
+		tsetattrs(TXTUNDERLINE);
+	        applytextattributes(TSC_PROMPT);
 		break;
 	    case 'u':
-		txtchangeset(txtchangep, TXTNOUNDERLINE, TXTUNDERLINE);
-		txtunset(TXTUNDERLINE);
-		tsetcap(TCUNDERLINEEND, TSC_PROMPT|TSC_DIRTY);
+		tunsetattrs(TXTUNDERLINE);
+	        applytextattributes(TSC_PROMPT);
 		break;
 	    case 'F':
 		atr = parsecolorchar(arg, 1);
-		if (!(atr & (TXT_ERROR | TXTNOFGCOLOUR))) {
-		    txtchangeset(txtchangep, atr & TXT_ATTR_FG_ON_MASK,
-				 TXTNOFGCOLOUR | TXT_ATTR_FG_COL_MASK);
-		    txtunset(TXT_ATTR_FG_COL_MASK);
-		    txtset(atr & TXT_ATTR_FG_ON_MASK);
-		    set_colour_attribute(atr, COL_SEQ_FG, TSC_PROMPT);
+		if (atr && atr != TXT_ERROR) {
+		    tsetattrs(atr);
+		    applytextattributes(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);
+		tunsetattrs(TXTFGCOLOUR);
+		applytextattributes(TSC_PROMPT);
 		break;
 	    case 'K':
 		atr = parsecolorchar(arg, 0);
-		if (!(atr & (TXT_ERROR | TXTNOBGCOLOUR))) {
-		    txtchangeset(txtchangep, atr & TXT_ATTR_BG_ON_MASK,
-				 TXTNOBGCOLOUR | TXT_ATTR_BG_COL_MASK);
-		    txtunset(TXT_ATTR_BG_COL_MASK);
-		    txtset(atr & TXT_ATTR_BG_ON_MASK);
-		    set_colour_attribute(atr, COL_SEQ_BG, TSC_PROMPT);
+		if (atr && atr != TXT_ERROR) {
+		    tsetattrs(atr);
+		    applytextattributes(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);
+		tunsetattrs(TXTBGCOLOUR);
+	        applytextattributes(TSC_PROMPT);
+		break;
+	    case 'H':
+		if (bv->fm[1] == '{') {
+		    bv->fm = parsehighlight(bv->fm + 2, '}', &atr);
+		    --bv->fm;
+		    if (atr != TXT_ERROR) {
+			treplaceattrs(atr);
+			applytextattributes(TSC_PROMPT);
+		    }
+		}
 		break;
 	    case '[':
 		if (idigit(*++bv->fm))
 		    arg = zstrtol(bv->fm, &bv->fm, 10);
-		if (!prompttrunc(arg, ']', doprint, endchar, txtchangep))
+		if (!prompttrunc(arg, ']', doprint, endchar))
 		    return *bv->fm;
 		break;
 	    case '<':
@@ -596,7 +659,7 @@ putpromptchar(int doprint, int endchar, zattr *txtchangep)
 		    if (arg <= 0)
 			arg = 1;
 		}
-		if (!prompttrunc(arg, *bv->fm, doprint, endchar, txtchangep))
+		if (!prompttrunc(arg, *bv->fm, doprint, endchar))
 		    return *bv->fm;
 		break;
 	    case '{': /*}*/
@@ -1013,9 +1076,8 @@ stradd(char *d)
 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) {
+    if (tccan(cap) && !(termflags & (TERM_NOUP|TERM_BAD|TERM_UNKNOWN))) {
+	switch (flags) {
 	case TSC_RAW:
 	    tputs(tcstr[cap], 1, putraw);
 	    break;
@@ -1045,20 +1107,6 @@ tsetcap(int cap, int flags)
 	    }
 	    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, flags);
-	    if (txtisset(TXTBGCOLOUR))
-		set_colour_attribute(txtattrmask, COL_SEQ_BG, flags);
-	}
     }
 }
 
@@ -1219,8 +1267,7 @@ countprompt(char *str, int *wp, int *hp, int overf)
 
 /**/
 static int
-prompttrunc(int arg, int truncchar, int doprint, int endchar,
-	    zattr *txtchangep)
+prompttrunc(int arg, int truncchar, int doprint, int endchar)
 {
     if (arg > 0) {
 	char ch = *bv->fm, *ptr, *truncstr;
@@ -1267,7 +1314,7 @@ prompttrunc(int arg, int truncchar, int doprint, int endchar,
 	w = bv->bp - bv->buf;
 	bv->fm++;
 	bv->trunccount = bv->dontcount;
-	putpromptchar(doprint, endchar, txtchangep);
+	putpromptchar(doprint, endchar);
 	bv->trunccount = 0;
 	ptr = bv->buf + w;	/* putpromptchar() may have realloc()'d */
 	*bv->bp = '\0';
@@ -1547,7 +1594,7 @@ prompttrunc(int arg, int truncchar, int doprint, int endchar,
 	     * With bv->truncwidth set to zero, we always reach endchar *
 	     * (or the terminating NULL) this time round.         *
 	     */
-	    if (!putpromptchar(doprint, endchar, txtchangep))
+	    if (!putpromptchar(doprint, endchar))
 		return 0;
 	}
 	/* Now we have to trick it into matching endchar again */
@@ -1585,6 +1632,158 @@ cmdpop(void)
 	cmdsp--;
 }
 
+/* functions for handling attributes */
+
+/**/
+mod_export void
+applytextattributes(int flags)
+{
+    zattr change = txtcurrentattrs ^ txtpendingattrs;
+    zattr keepon = ~change & txtpendingattrs & TXT_ATTR_ALL;
+    zattr turnoff = change & ~txtpendingattrs & TXT_ATTR_ALL;
+    int keepcount, turncount = 0;
+
+    /* bail out early if we wouldn't do anything */
+    if (!change)
+	return;
+
+    if (txtunknownattrs) {
+	txtunknownattrs &= ~change; /* changes cease to be unknown */
+	/* can't turn unknown attrs back on so avoid wiping them */
+	keepcount = 1;
+    } else {
+	/* If we want to turn off more attributes than we want to keep on
+	 * then it takes fewer termcap sequences to just turn off all the
+	 * attributes. */
+	for (keepcount = 0; keepon; keepcount++) /* count bits */
+	    keepon &= keepon - 1;
+	for (; turnoff; turncount++)
+	    turnoff &= turnoff - 1;
+    }
+
+    /* enabling bold can be relied upon to disable faint
+     * (the converse not so as that commonly does nothing at all) */
+    if (txtcurrentattrs & TXTFAINT && txtpendingattrs & TXTBOLDFACE) {
+	--turncount;
+	change &= ~TXTFAINT;
+    }
+
+    if (keepcount < turncount ||
+	    (change & ~txtpendingattrs & TXT_ATTR_FONT_WEIGHT)) {
+	tsetcap(TCALLATTRSOFF, flags);
+	/* this cleared all attributes, may need to restore some */
+	change = txtpendingattrs & TXT_ATTR_ALL & ~txtunknownattrs;
+	txtunknownattrs = 0;
+    } else {
+	if (change & ~txtpendingattrs & TXTSTANDOUT) {
+	    tsetcap(TCSTANDOUTEND, flags);
+	    /* in some cases, that clears all attributes */
+	    change = (txtpendingattrs & TXT_ATTR_ALL & ~txtunknownattrs) |
+		    (TXTUNDERLINE & change);
+	}
+	if (change & ~txtpendingattrs & TXTUNDERLINE) {
+	    tsetcap(TCUNDERLINEEND, flags);
+	    /* in some cases, that clears all attributes */
+	    change = txtpendingattrs & TXT_ATTR_ALL & ~txtunknownattrs;
+	}
+	if (change & ~txtpendingattrs & TXTITALIC)
+	    tsetcap(TCITALICSEND, flags);
+    }
+    if (change & txtpendingattrs & TXTBOLDFACE)
+	tsetcap(TCBOLDFACEBEG, flags);
+    if (change & txtpendingattrs & TXTFAINT)
+	tsetcap(TCFAINTBEG, flags);
+    if (change & txtpendingattrs & TXTSTANDOUT)
+	tsetcap(TCSTANDOUTBEG, flags);
+    if (change & txtpendingattrs & TXTUNDERLINE)
+	tsetcap(TCUNDERLINEBEG, flags);
+    if (change & txtpendingattrs & TXTITALIC)
+	tsetcap(TCITALICSBEG, flags);
+
+    if (change & TXT_ATTR_FG_MASK)
+	set_colour_attribute(txtpendingattrs, COL_SEQ_FG, flags);
+    if (change & TXT_ATTR_BG_MASK)
+	set_colour_attribute(txtpendingattrs, COL_SEQ_BG, flags);
+
+    txtcurrentattrs = txtpendingattrs;
+}
+
+/**/
+mod_export void
+cleartextattributes(int flags)
+{
+    treplaceattrs(0);
+    applytextattributes(flags);
+}
+
+/**/
+mod_export void
+treplaceattrs(zattr newattrs)
+{
+    if (newattrs == TXT_ERROR)
+	return;
+
+    if (txtunknownattrs) {
+	/* Set current attributes to the opposite of the new ones
+	 * for any that are unknown so that applytextattributes()
+	 * detects them as changed. */
+	txtcurrentattrs &= ~txtunknownattrs;
+	txtcurrentattrs |= txtunknownattrs & ~newattrs;
+    }
+
+    txtpendingattrs = newattrs;
+}
+
+/**/
+mod_export void
+tsetattrs(zattr newattrs)
+{
+    /* assume any unknown attributes that we're now setting were unset */
+    txtcurrentattrs &= ~(newattrs & txtunknownattrs);
+
+    txtpendingattrs |= newattrs & TXT_ATTR_ALL;
+    if (newattrs & TXTFGCOLOUR) {
+	txtpendingattrs &= ~TXT_ATTR_FG_MASK;
+	txtpendingattrs |= newattrs & TXT_ATTR_FG_MASK;
+    }
+    if (newattrs & TXTBGCOLOUR) {
+	txtpendingattrs &= ~TXT_ATTR_BG_MASK;
+	txtpendingattrs |= newattrs & TXT_ATTR_BG_MASK;
+    }
+}
+
+/**/
+mod_export void
+tunsetattrs(zattr newattrs)
+{
+    /* assume any unknown attributes that we're now unsetting were set */
+    txtcurrentattrs |= newattrs & txtunknownattrs;
+
+    txtpendingattrs &= ~(newattrs & TXT_ATTR_ALL);
+    if (newattrs & TXTFGCOLOUR)
+	txtpendingattrs &= ~TXT_ATTR_FG_MASK;
+    if (newattrs & TXTBGCOLOUR)
+	txtpendingattrs &= ~TXT_ATTR_BG_MASK;
+}
+
+/* Merge two attribute sets. In an case where attributes might conflict
+ * choose those from the first parameter.  Foreground and background
+ * colours are taken together - less likely to end up with unreadable
+ * combinations. */
+
+/**/
+mod_export zattr
+mixattrs(zattr primary, zattr secondary)
+{
+    zattr result = secondary;
+    /* take colours from primary */
+    if (primary & (TXTFGCOLOUR|TXTBGCOLOUR))
+        result &= ~TXT_ATTR_COLOUR_MASK;
+    /* take font weight from primary */
+    if (primary & TXT_ATTR_FONT_WEIGHT)
+        result &= ~TXT_ATTR_FONT_WEIGHT;
+    return result | primary;
+}
 
 /*****************************************************************************
  * Utilities dealing with colour and other forms of highlighting.
@@ -1607,10 +1806,12 @@ struct highlight {
 };
 
 static const struct highlight highlights[] = {
-    { "none", 0, TXT_ATTR_ON_MASK },
-    { "bold", TXTBOLDFACE, 0 },
+    { "none", 0, TXT_ATTR_ALL },
+    { "bold", TXTBOLDFACE, TXTFAINT },
+    { "faint", TXTFAINT, TXTBOLDFACE },
     { "standout", TXTSTANDOUT, 0 },
     { "underline", TXTUNDERLINE, 0 },
+    { "italic", TXTITALIC, 0 },
     { NULL, 0, 0 }
 };
 
@@ -1645,8 +1846,8 @@ match_named_colour(const char **teststrp)
  * 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.
+ * Return TXT_ERROR for out of range.  Does not check the
+ * character following the colour specification.
  */
 
 /**/
@@ -1666,7 +1867,7 @@ match_colour(const char **teststrp, int is_fg, int colour)
 	tc = TCBGCOLOUR;
     }
     if (teststrp) {
-	if (**teststrp == '#' && isxdigit(STOUC((*teststrp)[1]))) {
+	if (**teststrp == '#' && isxdigit((unsigned char) (*teststrp)[1])) {
 	    struct color_rgb color;
 	    char *end;
 	    zlong col = zstrtol(*teststrp+1, &end, 16);
@@ -1693,10 +1894,8 @@ match_colour(const char **teststrp, int is_fg, int colour)
 	    }
 	} else if ((named = ialpha(**teststrp))) {
 	    colour = match_named_colour(teststrp);
-	    if (colour == 8) {
-		/* default */
-		return is_fg ? TXTNOFGCOLOUR : TXTNOBGCOLOUR;
-	    }
+	    if (colour == 8) /* default */
+		return 0;
 	    if (colour < 0)
 		return TXT_ERROR;
 	}
@@ -1717,23 +1916,30 @@ match_colour(const char **teststrp, int is_fg, int colour)
 /*
  * Match a set of highlights in the given teststr.
  * Set *on_var to reflect the values found.
+ * Set *layer to the layer
  * Return a pointer to the first character not consumed.
  */
 
 /**/
 mod_export const char *
-match_highlight(const char *teststr, zattr *on_var)
+match_highlight(const char *teststr, zattr *on_var, int *layer)
 {
     int found = 1;
 
     *on_var = 0;
     while (found && *teststr) {
 	const struct highlight *hl;
+	zattr atr = 0;
 
 	found = 0;
-	if (strpfx("fg=", teststr) || strpfx("bg=", teststr)) {
+	if (strpfx("hl=", teststr)) {
+	    teststr += 3;
+	    teststr = parsehighlight((char *)teststr, ',', &atr);
+	    if (atr != TXT_ERROR)
+		*on_var = atr;
+	    found = 1;
+	} else if (strpfx("fg=", teststr) || strpfx("bg=", teststr)) {
 	    int is_fg = (teststr[0] == 'f');
-	    zattr atr;
 
 	    teststr += 3;
 	    atr = match_colour(&teststr, is_fg, 0);
@@ -1745,6 +1951,14 @@ match_highlight(const char *teststr, zattr *on_var)
 	    /* skip out of range colours but keep scanning attributes */
 	    if (atr != TXT_ERROR)
 		*on_var |= atr;
+	} else if (layer && strpfx("layer=", teststr)) {
+	    teststr += 6;
+	    *layer = (int) zstrtol(teststr, (char **) &teststr, 10);
+	    if (*teststr == ',')
+		teststr++;
+	    else if (*teststr && *teststr != ' ')
+		break;
+	    found = 1;
 	} else {
 	    for (hl = highlights; hl->name; hl++) {
 		if (strpfx(hl->name, teststr)) {
@@ -2024,13 +2238,13 @@ set_colour_attribute(zattr atr, int fg_bg, int flags)
     if (fg_bg == COL_SEQ_FG) {
 	colour = txtchangeget(atr, TXT_ATTR_FG_COL);
 	tc = TCFGCOLOUR;
-	def = txtchangeisset(atr, TXTNOFGCOLOUR);
-	use_truecolor = txtchangeisset(atr, TXT_ATTR_FG_24BIT);
+	def = !(atr & TXTFGCOLOUR);
+	use_truecolor = atr & TXT_ATTR_FG_24BIT;
     } else {
 	colour = txtchangeget(atr, TXT_ATTR_BG_COL);
 	tc = TCBGCOLOUR;
-	def = txtchangeisset(atr, TXTNOBGCOLOUR);
-	use_truecolor = txtchangeisset(atr, TXT_ATTR_BG_24BIT);
+	def = !(atr & TXTBGCOLOUR);
+	use_truecolor = atr & TXT_ATTR_BG_24BIT;
     }
 
     /* Test if current zle_highlight settings are customized, or
diff --git a/Src/prototypes.h b/Src/prototypes.h
index e3db4f5ee..3578482d0 100644
--- a/Src/prototypes.h
+++ b/Src/prototypes.h
@@ -28,9 +28,9 @@
  */
 
 #ifndef HAVE_STDLIB_H
-char *malloc _((size_t));
-char *realloc _((void *, size_t));
-char *calloc _((size_t, size_t));
+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))
@@ -45,11 +45,11 @@ char *calloc _((size_t, size_t));
 #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)));
+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
 
@@ -70,30 +70,30 @@ char *tgoto(const char *cap, int col, int row);
 #endif
 
 #ifdef __osf__
-char *mktemp _((char *));
+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));
+int ioctl (int d, unsigned long request, void *argp);
 # endif
 # ifndef HAVE_MKNOD_PROTO
-int mknod _((const char *pathname, int mode, dev_t device));
+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));
+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));
+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__
@@ -101,34 +101,34 @@ extern pid_t getppid(void);
 #endif
 
 #if defined(__sun__) && !defined(__SVR4)  /* SunOS */
-extern char *strerror _((int errnum));
+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));
+extern char *strstr (const char *s, const char *t);
 #endif
 
 #ifndef HAVE_GETHOSTNAME
-extern int gethostname _((char *name, size_t namelen));
+extern int gethostname (char *name, size_t namelen);
 #endif
 
 #ifndef HAVE_GETTIMEOFDAY
-extern int gettimeofday _((struct timeval *tv, struct timezone *tz));
+extern int gettimeofday (struct timeval *tv, struct timezone *tz);
 #endif
 
 #ifndef HAVE_DIFFTIME
-extern double difftime _((time_t t2, time_t t1));
+extern double difftime (time_t t2, time_t t1);
 #endif
 
 #ifndef HAVE_STRERROR
-extern char *strerror _((int errnum));
+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));
+extern void bcopy (const void *, void *, size_t);
 #endif
diff --git a/Src/signals.c b/Src/signals.c
index a61368554..d28853ea6 100644
--- a/Src/signals.c
+++ b/Src/signals.c
@@ -31,10 +31,12 @@
 #include "signals.pro"
  
 /* Array describing the state of each signal: an element contains *
- * 0 for the default action or some ZSIG_* flags ored together.   */
+ * 0 for the default action or some ZSIG_* flags ored together.   *
+ * Contains TRAPCOUNT elements but can't be allocated statically  *
+ * because that's a dynamic value on Linux                        */
 
 /**/
-mod_export int sigtrapped[VSIGCOUNT];
+mod_export int *sigtrapped;
 
 /*
  * Trap programme lists for each signal.
@@ -48,7 +50,7 @@ mod_export int sigtrapped[VSIGCOUNT];
  */
 
 /**/
-mod_export Eprog siglists[VSIGCOUNT];
+mod_export Eprog *siglists;
 
 /* Total count of trapped signals */
 
@@ -556,9 +558,11 @@ wait_for_processes(void)
 		    jn->gleader = 0;
 		}
 	    }
+	    update_bg_job(jn, pid, status);
 	    update_job(jn);
 	} else if (findproc(pid, &jn, &pn, 1)) {
 	    pn->status = status;
+	    update_bg_job(jn, pid, status);
 	    update_job(jn);
 	} else {
 	    /* If not found, update the shell record of time spent by
@@ -567,19 +571,7 @@ wait_for_processes(void)
 	     * 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) {
-	    if (WIFEXITED(status))
-		addbgstatus(pid, WEXITSTATUS(status));
-	    else if (WIFSIGNALED(status))
-		addbgstatus(pid, 0200 | WTERMSIG(status));
+	    update_bg_job(jn, pid, status);
 	}
 
 	unqueue_signals();
@@ -902,7 +894,7 @@ dosavetrap(int sig, int level)
  * Set a trap:  note this does not handle manipulation of
  * the function table for TRAPNAL functions.
  *
- * sig is the signal number.
+ * sig is index into the table of trapped signals.
  *
  * l is the list to be eval'd for a trap defined with the "trap"
  * builtin and should be NULL for a function trap.
@@ -941,6 +933,10 @@ settrap(int sig, Eprog l, int flags)
 #endif
             sig != SIGCHLD)
             signal_ignore(sig);
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+	else if (sig >= VSIGCOUNT && sig < TRAPCOUNT)
+	    signal_ignore(SIGNUM(sig));
+#endif
     } else {
 	nsigtrapped++;
         sigtrapped[sig] = ZSIG_TRAPPED;
@@ -950,6 +946,10 @@ settrap(int sig, Eprog l, int flags)
 #endif
             sig != SIGCHLD)
             install_handler(sig);
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+	if (sig >= VSIGCOUNT && sig < TRAPCOUNT)
+	    install_handler(SIGNUM(sig));
+#endif
     }
     sigtrapped[sig] |= flags;
     /*
@@ -1029,6 +1029,11 @@ removetrap(int sig)
 #endif
              sig != SIGCHLD)
         signal_default(sig);
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+    else if (sig >= VSIGCOUNT && sig < TRAPCOUNT)
+	    signal_default(SIGNUM(sig));
+#endif
+
     if (sig == SIGEXIT)
 	exit_trap_posix = 0;
 
@@ -1182,7 +1187,7 @@ endtrapscope(void)
 static int
 handletrap(int sig)
 {
-    if (!sigtrapped[sig])
+    if (!sigtrapped[SIGIDX(sig)])
 	return 0;
 
     if (trap_queueing_enabled)
@@ -1199,7 +1204,7 @@ handletrap(int sig)
 	return 1;
     }
 
-    dotrap(sig);
+    dotrap(SIGIDX(sig));
 
     if (sig == SIGALRM)
     {
@@ -1491,3 +1496,60 @@ dotrap(int sig)
 
     restore_queue_signals(q);
 }
+
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+
+/* Realtime signals, these are a contiguous block that can
+ * be separated from the other signals with an unused gap. */
+
+/**/
+int
+rtsigno(const char* signame)
+{
+    const int maxofs = SIGRTMAX - SIGRTMIN;
+    const char *end = signame + 5;
+    int offset;
+    struct rtdir { int sig; int dir; char op; } x = { 0, 0, 0 };
+    if (!strncmp(signame, "RTMIN", 5)) {
+	x = (struct rtdir) { SIGRTMIN, 1, '+' };
+    } else if (!strncmp(signame, "RTMAX", 5)) {
+	x = (struct rtdir) { SIGRTMAX, -1, '-' };
+    } else
+	return 0;
+
+    if (signame[5] == x.op) {
+	if ((offset = strtol(signame + 6, (char **) &end, 10)) > maxofs)
+	    return 0;
+	x.sig += offset * x.dir;
+    }
+    if (*end)
+	return 0;
+
+    return x.sig;
+}
+
+/**/
+char *
+rtsigname(int signo, int alt)
+{
+    char* buf = (char *) zhalloc(10);
+    int minofs = signo - SIGRTMIN;
+    int maxofs = SIGRTMAX - signo;
+    int offset;
+    int form = alt ^ (maxofs < minofs);
+
+    if (signo < SIGRTMIN || signo > SIGRTMAX)
+	return NULL;
+
+    strcpy(buf, "RT");
+    strcpy(buf+2, form ? "MAX-" : "MIN+");
+    offset = form ? maxofs : minofs;
+    if (offset) {
+	snprintf(buf + 6, 4, "%d", offset);
+    } else {
+	buf[5] = '\0';
+    }
+    return buf;
+}
+
+#endif
diff --git a/Src/signals.h b/Src/signals.h
index 41ac88cce..7910f6b79 100644
--- a/Src/signals.h
+++ b/Src/signals.h
@@ -27,7 +27,7 @@
  *
  */
 
-#define SIGNAL_HANDTYPE void (*)_((int))
+#define SIGNAL_HANDTYPE void (*)(int)
 
 #ifndef HAVE_KILLPG
 # define killpg(pgrp,sig) kill(-(pgrp),sig)
@@ -36,6 +36,15 @@
 #define SIGZERR   (SIGCOUNT+1)
 #define SIGDEBUG  (SIGCOUNT+2)
 #define VSIGCOUNT (SIGCOUNT+3)
+#if defined(SIGRTMIN) && defined(SIGRTMAX)
+# define TRAPCOUNT (VSIGCOUNT + SIGRTMAX - SIGRTMIN + 1)
+# define SIGNUM(x) ((x) >= VSIGCOUNT ? (x) - VSIGCOUNT + SIGRTMIN : (x))
+# define SIGIDX(x) ((x) >= SIGRTMIN && (x) <= SIGRTMAX ? (x) - SIGRTMIN + VSIGCOUNT : (x))
+#else
+# define TRAPCOUNT VSIGCOUNT
+# define SIGNUM(x) (x)
+# define SIGIDX(x) (x)
+#endif
 #define SIGEXIT    0
 
 #ifdef SV_BSDSIG
@@ -136,7 +145,7 @@
 #ifdef BSD_SIGNALS
 #define signal_block(S) sigblock(S)
 #else
-extern sigset_t signal_block _((sigset_t));
+extern sigset_t signal_block (sigset_t);
 #endif  /* BSD_SIGNALS   */
 
-extern sigset_t signal_unblock _((sigset_t));
+extern sigset_t signal_unblock (sigset_t);
diff --git a/Src/signames2.awk b/Src/signames2.awk
index 4d15681d5..0b254f751 100644
--- a/Src/signames2.awk
+++ b/Src/signames2.awk
@@ -13,8 +13,9 @@
     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] == "") {
+    if (signam == "POLL" && sig[signum] == "IO")   sig[signum] = ""
+    if (signam == "ABRT" && sig[signum] == "IOT")  sig[signum] = ""
+    if (signam !~ /RTM(IN|AX)/ && sig[signum] == "") {
 	sig[signum] = signam
 	if (0 + max < 0 + signum && signum < 60)
 	    max = signum
@@ -26,6 +27,7 @@
 	if (signam == "CONT")   { msg[signum] = "continued" }
 	if (signam == "EMT")    { msg[signum] = "EMT instruction" }
 	if (signam == "FPE")    { msg[signum] = "floating point exception" }
+        if (signam == "FREEZE") { msg[signum] = "checkpoint freeze" }
 	if (signam == "HUP")    { msg[signum] = "hangup" }
 	if (signam == "ILL")    { msg[signum] = "illegal hardware instruction" }
 	if (signam == "INFO")   { msg[signum] = "status request from keyboard" }
@@ -33,23 +35,25 @@
 	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 == "LOST")   { msg[signum] = "resource lost" }
 	if (signam == "PIPE")   { msg[signum] = "broken pipe" }
-	if (signam == "POLL")	{ msg[signum] = "pollable event occurred" }
+	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 == "THAW")   { msg[signum] = "checkpoint thaw" }
 	if (signam == "TRAP")   { msg[signum] = "trace trap" }
-	if (signam == "URG")	{ msg[signum] = "urgent condition" }
+	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" }
+        if (signam == "XRES")   { msg[signum] = "resource control exceeded" }
     }
 }
 
@@ -65,10 +69,6 @@ END {
     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
 
diff --git a/Src/sort.c b/Src/sort.c
index 26949ad9c..ce2b4bbc3 100644
--- a/Src/sort.c
+++ b/Src/sort.c
@@ -138,7 +138,7 @@ eltpcmp(const void *a, const void *b)
 	int mul = 0;
 	for (; *as == *bs && *as; as++, bs++);
 #ifndef HAVE_STRCOLL
-	cmp = (int)STOUC(*as) - (int)STOUC(*bs);
+	cmp = (int) (unsigned char) *as - (int) (unsigned char) *bs;
 #endif
 	if (sortnumeric < 0) {
 	    if (*as == '-' && idigit(as[1]) && idigit(*bs)) {
@@ -159,7 +159,7 @@ eltpcmp(const void *a, const void *b)
 		    bs++;
 		for (; idigit(*as) && *as == *bs; as++, bs++);
 		if (idigit(*as) || idigit(*bs)) {
-		    cmp = mul * ((int)STOUC(*as) - (int)STOUC(*bs));
+		    cmp = mul * ((int) (unsigned char) *as - (int) (unsigned char) *bs);
 		    while (idigit(*as) && idigit(*bs))
 			as++, bs++;
 		    if (idigit(*as) && !idigit(*bs))
diff --git a/Src/subst.c b/Src/subst.c
index 0f98e6ea3..a079672df 100644
--- a/Src/subst.c
+++ b/Src/subst.c
@@ -556,7 +556,7 @@ multsub(char **s, int pf_flags, char ***a, int *isarr, char *sep,
 	for ( ; *x; x += l) {
 	    char c = (l = *x == Meta) ? x[1] ^ 32 : *x;
 	    l++;
-	    if (!iwsep(STOUC(c)))
+	    if (!iwsep((unsigned char) c))
 		break;
 	    *ms_flags |= MULTSUB_WS_AT_START;
 	}
@@ -573,7 +573,7 @@ multsub(char **s, int pf_flags, char ***a, int *isarr, char *sep,
 	    convchar_t c;
 	    if (*x == Dash)
 		*x = '-';
-	    if (itok(STOUC(*x))) {
+	    if (itok((unsigned char) *x)) {
 		/* token, can't be separator, must be single byte */
 		rawc = *x;
 		l = 1;
@@ -582,7 +582,7 @@ multsub(char **s, int pf_flags, char ***a, int *isarr, char *sep,
 		if (!inq && !inp && WC_ZISTYPE(c, ISEP)) {
 		    *x = '\0';
 		    for (x += l; *x; x += l) {
-			if (itok(STOUC(*x))) {
+			if (itok((unsigned char) *x)) {
 			    /* as above */
 			    rawc = *x;
 			    l = 1;
@@ -1489,21 +1489,27 @@ subst_parse_str(char **sp, int single, int err)
 static char *
 substevalchar(char *ptr)
 {
-    zlong ires = mathevali(ptr);
+    zlong ires;
     int len = 0;
+    int saved_errflag = errflag;
 
-    if (errflag)
-	return NULL;
-#ifdef MULTIBYTE_SUPPORT
-    if (isset(MULTIBYTE) && ires > 127) {
-	/* '\\' + 'U' + 8 bytes of character + '\0' */
-	char buf[11];
+    errflag = 0;
+    ires = mathevali(ptr);
 
-	/* inefficient: should separate out \U handling from getkeystring */
-	sprintf(buf, "\\U%.8x", (unsigned int)ires & 0xFFFFFFFFu);
-	ptr = getkeystring(buf, &len, GETKEYS_BINDKEY, NULL);
+    if (errflag) {  /* not a valid numerical expression */
+	errflag |= saved_errflag;
+	return noerrs ? dupstring(""): NULL;
+    }
+    errflag |= saved_errflag;
+    if (ires < 0) {
+	zerr("character not in range");
+    }
+#ifdef MULTIBYTE_SUPPORT
+    else if (isset(MULTIBYTE) && ires > 127) {
+	ptr = zhalloc(MB_CUR_MAX+1);
+	len = ucs4tomb((unsigned int)ires & 0xffffffff, ptr);
     }
-    if (len == 0)
+    if (len <= 0)
 #endif
     {
 	ptr = zhalloc(2);
@@ -1818,14 +1824,14 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
      * Use for the (k) flag.  Goes down into the parameter code,
      * sometimes.
      */
-    char hkeys = 0;
+    int hkeys = 0;
     /*
      * Used for the (v) flag, ditto.  Not quite sure why they're
      * separate, but the tradition seems to be that things only
      * get combined when that makes the result more obscure rather
      * than less.
      */
-    char hvals = 0;
+    int hvals = 0;
     /*
      * Whether we had to evaluate a subexpression, i.e. an
      * internal ${...} or $(...) or plain $pm.  We almost don't
@@ -1860,6 +1866,11 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
      * joining the array into a string (for compatibility with ksh/bash).
      */
     int quoted_array_with_offset = 0;
+    /*
+     * Nofork substitution controls
+     */
+    char *rplyvar = NULL;    /* Indicates ${|...;} or ${{var} ...;} */
+    char *rplytmp = NULL;    /* Indicates ${ ... ;} */
 
     *s++ = '\0';
     /*
@@ -1870,8 +1881,8 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
      * these later on, too.
      */
     c = *s;
-    if (itype_end(s, IIDENT, 1) == s && *s != '#' && c != Pound &&
-	!IS_DASH(c) &&
+    if (itype_end(s, (c == Inbrace ? INAMESPC : IIDENT), 1) == s &&
+	*s != '#' && c != Pound && !IS_DASH(c) &&
 	c != '!' && c != '$' && c != String && c != Qstring &&
 	c != '?' && c != Quest &&
 	c != '*' && c != Star && c != '@' && c != '{' &&
@@ -1887,19 +1898,235 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
      * flags in parentheses, but also one ksh hack.
      */
     if (c == Inbrace) {
-	inbrace = 1;
-	s++;
+	/* For processing nofork command substitution string */
+	char *cmdarg = NULL, *endvar = NULL, inchar = *++s;
+	char *outbracep = s, sav = *s;
+	Param rplypm = NULL;
+	size_t slen = 0;
+	int trim = (!EMULATION(EMULATE_ZSH)) ? 2 : !qt;
+
+	inbrace = 1;	/* Outer scope boolean, see above */
+
+        /* Handling for nofork command substitution e.g. ${|cmd;}
+	 * See other comments about kludges for why this is here.
+	 *
+         * The command string is extracted and executed, and the
+         * substitution assigned. There's no (...)-flags processing,
+         * i.e. no ${|(U)cmd;}, because it looks quite awful and
+         * should not be part of command substitution in any case.
+         * Use ${(U)${|cmd;}} as you would for ${(U)$(cmd;)}.
+	 */
+	if (inchar == '|' || inchar == Bar || inblank(inchar)) {
+	    *s = Inbrace;
+	    if (skipparens(Inbrace, Outbrace, &outbracep) == 0)
+		slen = outbracep - s - 1;
+	    *s = sav;
+	    if (inchar == '|')
+		inchar = Bar;	/* Simplify later compares */
+	} else if (inchar == '{' || inchar == Inbrace) {
+	    *s = Inbrace;
+	    if ((outbracep = itype_end(s+1, INAMESPC, 0))) {
+		if (*outbracep == Inbrack &&
+		    (outbracep = parse_subscript(++outbracep, 1, ']')))
+		    ++outbracep;
+	    }
+
+	    /* If we reached the first close brace, find the last */
+	    if (outbracep && *outbracep == Outbrace) {
+		char outchar = inchar == Inbrace ? Outbrace : '}';
+		endvar = outbracep++;
+
+		/* Require space to avoid ${{var}} typo for ${${var}} */
+		if (!inblank(*outbracep)) {
+		    zerr("bad substitution");
+		    return NULL;
+		}
+
+		*endvar = '|';	/* Almost anything but braces/brackets */
+		outbracep = s;
+		if (skipparens(Inbrace, outchar, &outbracep) == 0)
+		    *endvar = Outbrace;
+		else {	/* Never happens? */
+		    *endvar = outchar;
+		    outbracep = endvar + 1;
+		}
+		slen = outbracep - s - 1;
+		if (inchar != Inbrace)
+		    outbracep[-1] = Outbrace;
+		*s = sav;
+		inchar = Inbrace;	/* Simplify later compares */
+	    } else {
+		zerr("bad substitution");
+		return NULL;
+	    }
+	}
+	if (slen > 1) {
+	    char *outbracep = s + slen;
+	    if (!itok(*s) || inblank(inchar)) {
+		/* This tokenize() is important */
+		char sav = *outbracep;
+		*outbracep = '\0';
+		tokenize(s);
+		*outbracep = sav;
+	    }
+	    if (*outbracep == Outbrace) {
+		if (endvar == s+1) {
+		    /* For consistency with ${} we allow ${{}...} */
+		    rplyvar = NULL;
+		}
+		if (endvar && *endvar == Outbrace) {
+		    cmdarg = dupstrpfx(endvar+1, outbracep-endvar-1);
+		    rplyvar = dupstrpfx(s+1,endvar-s-1);
+		} else {
+		    cmdarg = dupstrpfx(s+1, outbracep-s-1);
+		    rplyvar = "REPLY";
+		}
+		if (inblank(inchar)) {
+		    /*
+		     * Admittedly a hack.  Take advantage of the added
+		     * parameter scope and the semantics of $(<file) to
+		     * construct a command to write/read a temporary file.
+		     * Then fall through to the regular parameter handling
+		     * to manage word splitting, expansion flags, etc.
+		     */
+		    char *outfmt = ">| %s {\n%s\n;}";	/* 13 */
+		    if ((rplytmp = gettempname(NULL, 1))) {
+			/* Prevent shenanigans with $TMPPREFIX */
+			char *tmpfile = quotestring(rplytmp, QT_BACKSLASH);
+			char *dummy = zhalloc(strlen(cmdarg) +
+					      strlen(tmpfile) +
+					      13);
+			sprintf(dummy, outfmt, tmpfile, cmdarg);
+			cmdarg = dummy;
+		    } else {
+			/* TMPPREFIX not writable? */
+			cmdoutval = lastval;
+			cmdarg = NULL;
+		    }
+		}
+		s = outbracep;
+	    }
+	}
+
+	if (rplyvar) {
+	    /* char *rplyval = getsparam("REPLY");  cf. Future? below */
+	    startparamscope(); /* "local" behaves as if in a function */
+	    if (inchar == Bar) {
+		/* rplyvar should be REPLY at this point, but create
+		 * hardwired name anyway to expose any bugs elsewhere
+		 */
+		rplypm = createparam("REPLY", PM_LOCAL|PM_UNSET|PM_HIDE);
+		if (rplypm)	/* Shouldn't createparam() do this? */
+		    rplypm->level = locallevel;
+		/* Future?  Expose global value of $REPLY if any? */
+		/* if (rplyval) setsparam("REPLY", ztrdup(rplyval)); */
+	    } else if (inblank(inchar)) {
+		rplypm = createparam(".zsh.cmdsubst",
+				     PM_LOCAL|PM_UNSET|PM_HIDE|
+				     PM_READONLY_SPECIAL);
+		if (rplypm)
+		    rplypm->level = locallevel;
+	    }
+	    if (inchar != Inbrace && !rplypm) {
+		zerr("failed to create scope for command substitution");
+		return NULL;
+	    }
+	}
+
+	if (rplyvar && cmdarg && *cmdarg) {
+	    int obreaks = breaks;
+	    Eprog cmdprog;
+	    /* Execute the shell command */
+	    queue_signals();
+	    untokenize(cmdarg);
+	    cmdprog = parse_string(cmdarg, 0);
+	    if (cmdprog) {
+		/* exec.c handles dont_queue_signals() */
+		execode(cmdprog, 1, 0, "cmdsubst");
+		cmdoutval = lastval;
+		/* "return" behaves as if in a function */
+		if (retflag) {
+		    retflag = 0;
+		    breaks = obreaks;	/* Is this ever not zero? */
+		}
+	    } else	/* parse error */
+		errflag |= ERRFLAG_ERROR;
+	    if (rplypm)
+		rplypm->node.flags &= ~PM_READONLY_SPECIAL;
+	    if (rplytmp && !errflag) {
+		int onoerrs = noerrs, rplylen;
+		noerrs = 2;
+		rplylen = zstuff(&cmdarg, rplytmp);
+		if (trim) {
+		    /* bash and ksh strip trailing newlines here */
+		    while (rplylen > 0 && cmdarg[rplylen-1] == '\n') {
+			rplylen--;
+			if (trim == 1)
+			    break;
+		    }
+		    cmdarg[rplylen] = 0;
+		}
+		noerrs = onoerrs;
+		if (rplylen >= 0)
+		    setsparam(rplyvar, metafy(cmdarg, rplylen, META_REALLOC));
+	    }
+	    unqueue_signals();
+	}
+
+	if (rplytmp)
+	    unlink(rplytmp);
+	if (rplyvar) {
+	    if (inchar != Inbrace) {
+		if ((val = dupstring(getsparam(rplyvar))))
+		    vunset = 0;
+		else {
+		    vunset = 1;
+		    val = dupstring("");
+		}
+	    } else {
+		s = dyncat(rplyvar, s);
+		rplyvar = NULL;
+	    }
+	    endparamscope();
+	    if (exit_pending) {
+		if (mypid == getpid()) {
+		    /*
+		     * paranoia: don't check for jobs, but there
+		     * shouldn't be any if not interactive.
+		     */
+		    stopmsg = 1;
+		    zexit(exit_val, ZEXIT_NORMAL);
+		} else
+		    _exit(exit_val);
+	    }
+	}
+
 	/*
 	 * In ksh emulation a leading `!' is a special flag working
-	 * sort of like our (k).
+	 * sort of like our (k).  This is true only for arrays or
+	 * associative arrays and only with subscripts [*] or [@],
+	 * so zsh's implementation is approximate.  For namerefs
+	 * in ksh, ${!ref} substitues the parameter name at the
+	 * end of any chain of references, rather than the value.
+	 *
 	 * TODO: this is one of very few cases tied directly to
 	 * the emulation mode rather than an option.  Since ksh
 	 * doesn't have parameter flags it might be neater to
 	 * handle this with the ^, =, ~ stuff, below.
 	 */
 	if ((c = *s) == '!' && s[1] != Outbrace && EMULATION(EMULATE_KSH)) {
-	    hkeys = SCANPM_WANTKEYS;
+	    hkeys = SCANPM_WANTKEYS|SCANPM_NONAMEREF;
 	    s++;
+	    /* There's a slew of other special bash meanings of parameter
+	     * references that start with "!":
+	     *  ${!name} == ${(P)name} (when name is not a nameref)
+	     *  ${!name*} == ${(k)parameters[(I)name*]}
+	     *  ${!name@} == ${(@k)parameters[(I)name*]}
+	     *  ${!name[*]} == ${(k)name} (but indexes of ordinary arrays, too)
+	     *  ${!name[@]} == ${(@k)name} (ditto, as noted above for ksh)
+	     *
+	     * See also workers/34390, workers/34397, workers/34408.
+	     */
 	} else if (c == '(' || c == Inpar) {
 	    char *t, sav;
 	    int tt = 0;
@@ -2154,10 +2381,19 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 		    escapes = 1;
 		    break;
 
+		case '!':
+		    if ((hkeys|hvals) & ~SCANPM_NONAMEREF)
+			goto flagerr;
+		    hkeys = SCANPM_NONAMEREF;
+		    break;
 		case 'k':
+		    if (hkeys & ~SCANPM_WANTKEYS)
+			goto flagerr;
 		    hkeys = SCANPM_WANTKEYS;
 		    break;
 		case 'v':
+		    if (hvals & ~SCANPM_WANTVALS)
+			goto flagerr;
 		    hvals = SCANPM_WANTVALS;
 		    break;
 
@@ -2308,7 +2544,7 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
     /*
      * Look for special unparenthesised flags.
      * TODO: could make these able to appear inside parentheses, too,
-     * i.e. ${(^)...} etc.
+     * i.e. ${(^)...} etc., but ${(~)...} already has another meaning.
      */
     for (;;) {
 	if ((c = *s) == '^' || c == Hat) {
@@ -2332,7 +2568,7 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	    }
 	} else if ((c == '#' || c == Pound) &&
 		   (inbrace || !isset(POSIXIDENTIFIERS)) &&
-		   (itype_end(s+1, IIDENT, 0) != s + 1
+		   (itype_end(s+1, INAMESPC, 0) != s + 1
 		    || (cc = s[1]) == '*' || cc == Star || cc == '@'
 		    || cc == '?' || cc == Quest
 		    || cc == '$' || cc == String || cc == Qstring
@@ -2369,8 +2605,9 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	     * Try to handle this when parameter is named
 	     * by (P) (second part of test).
 	     */
-	    if (itype_end(s+1, IIDENT, 0) != s+1 || (aspar && isstring(s[1]) &&
-				 (s[2] == Inbrace || s[2] == Inpar)))
+	    if (itype_end(s+1, INAMESPC, 0) != s+1 ||
+		(aspar && isstring(s[1]) &&
+		 (s[2] == Inbrace || s[2] == Inpar)))
 		chkset = 1, s++;
 	    else if (!inbrace) {
 		/* Special case for `$+' on its own --- leave unmodified */
@@ -2531,6 +2768,8 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	    scanflags |= SCANPM_DQUOTED;
 	if (chkset)
 	    scanflags |= SCANPM_CHECKING;
+	if (!inbrace)
+	    scanflags |= SCANPM_NONAMESPC;
 	/*
 	 * Second argument: decide whether to use the subexpression or
 	 *   the string next on the line as the parameter name.
@@ -2556,14 +2795,14 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	 * we let fetchvalue set the main string pointer s to
 	 * the end of the bit it's fetched.
 	 */
-	if (!(v = fetchvalue(&vbuf, (subexp ? &ov : &s),
-			     (wantt ? -1 :
-			      ((unset(KSHARRAYS) || inbrace) ? 1 : -1)),
-			     scanflags)) ||
-	    (v->pm && (v->pm->node.flags & PM_UNSET)) ||
-	    (v->flags & VALFLAG_EMPTY))
+	if (!rplyvar &&
+	    (!(v = fetchvalue(&vbuf, (subexp ? &ov : &s),
+			      (wantt ? -1 :
+			       ((unset(KSHARRAYS) || inbrace) ? 1 : -1)),
+			      scanflags)) ||
+	     (v->pm && (v->pm->node.flags & PM_UNSET)) ||
+	     (v->flags & VALFLAG_EMPTY)))
 	    vunset = 1;
-
 	if (wantt) {
 	    /*
 	     * Handle the (t) flag: value now becomes the type
@@ -2573,13 +2812,14 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 			       !(v->pm->node.flags & PM_UNSET))) {
 		int f = v->pm->node.flags;
 
-		switch (PM_TYPE(f)) {
+		switch (PM_TYPE(f)|(f & PM_NAMEREF)) {
 		case PM_SCALAR:  val = "scalar"; break;
 		case PM_ARRAY:   val = "array"; break;
 		case PM_INTEGER: val = "integer"; break;
 		case PM_EFLOAT:
 		case PM_FFLOAT:  val = "float"; break;
 		case PM_HASHED:  val = "association"; break;
+		case PM_NAMEREF: val = "nameref"; break;
 		}
 		val = dupstring(val);
 		if (v->pm->level)
@@ -2910,6 +3150,13 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 			chuck(ptr);
 		    else
 			ptr++;
+		} else if (c == Dnull) {
+		    chuck(ptr);
+		    while (*ptr && *ptr != c)
+			ptr++;
+		    if (*ptr == Dnull)
+			chuck(ptr);
+		    ptr--;	/* Outer loop is about to increment */
 		}
 	    }
 	    replstr = (*ptr && ptr[1]) ? ptr+1 : "";
@@ -2926,6 +3173,9 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	 */
 	if (!(flags & (SUB_MATCH|SUB_REST|SUB_BIND|SUB_EIND|SUB_LEN)))
 	    flags |= SUB_REST;
+	/* If matching at start and end, don't stop early */
+	if ((flags & (SUB_START|SUB_END)) == (SUB_START|SUB_END))
+	    flags |= SUB_LONG;
 
 	/*
 	 * With ":" treat a value as unset if the variable is set but
@@ -3076,7 +3326,13 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	    if (vunset) {
                 if (isset(EXECOPT)) {
                     *idend = '\0';
-                    zerr("%s: %s", idbeg, *s ? s : "parameter not set");
+		    if (*s){
+			int l;
+			singsub(&s);
+			s = unmetafy(s, &l);
+			zerr("%s: %l", idbeg, s, l);
+		    } else
+			zerr("%s: %s", idbeg, "parameter not set");
                     /*
                      * In interactive shell we need to return to
                      * top-level prompt --- don't clear this error
@@ -3203,7 +3459,7 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	    shortest = 0;
 	    ++s;
 	}
-	if (*itype_end(s, IIDENT, 0)) {
+	if (*itype_end(s, INAMESPC, 0)) {
 	    untokenize(s);
 	    zerr("not an identifier: %s", s);
 	    return NULL;
@@ -3219,6 +3475,9 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	    char *sval;
 	    zip = getaparam(s);
 	    if (!zip) {
+		zip = gethparam(s);
+	    }
+	    if (!zip) {
 		sval = getsparam(s);
 		if (sval)
 		    zip = hmkarray(sval);
@@ -3263,7 +3522,7 @@ paramsubst(LinkList l, LinkNode n, char **str, int qt, int pf_flags,
 	int intersect = (*s == '*' || *s == Star);
 	char **compare, **ap, **apsrc;
 	++s;
-	if (*itype_end(s, IIDENT, 0)) {
+	if (*itype_end(s, INAMESPC, 0)) {
 	    untokenize(s);
 	    zerr("not an identifier: %s", s);
 	    return NULL;
@@ -3716,6 +3975,8 @@ colonsubscript:
     if (presc) {
 	int ops = opts[PROMPTSUBST], opb = opts[PROMPTBANG];
 	int opp = opts[PROMPTPERCENT];
+	zattr savecurrent = txtcurrentattrs;
+	zattr saveunknown = txtunknownattrs;
 
 	if (presc < 2) {
 	    opts[PROMPTPERCENT] = 1;
@@ -3738,7 +3999,8 @@ colonsubscript:
 	    for (; *ap; ap++) {
 		char *tmps;
 		untokenize(*ap);
-		tmps = promptexpand(*ap, 0, NULL, NULL, NULL);
+		txtunknownattrs = TXT_ATTR_ALL;
+		tmps = promptexpand(*ap, 0, NULL, NULL);
 		*ap = dupstring(tmps);
 		free(tmps);
 	    }
@@ -3747,10 +4009,14 @@ colonsubscript:
 	    if (!copied)
 		val = dupstring(val), copied = 1;
 	    untokenize(val);
-	    tmps = promptexpand(val, 0, NULL, NULL, NULL);
+	    txtunknownattrs = TXT_ATTR_ALL;
+	    tmps = promptexpand(val, 0, NULL, NULL);
 	    val = dupstring(tmps);
 	    free(tmps);
 	}
+
+	txtpendingattrs = txtcurrentattrs = savecurrent;
+	txtunknownattrs = saveunknown;
 	opts[PROMPTSUBST] = ops;
 	opts[PROMPTBANG] = opb;
 	opts[PROMPTPERCENT] = opp;
@@ -4309,6 +4575,8 @@ modify(char **str, char **ptr, int inbrace)
 		break;
 
 	    case 's':
+	    case 'S':
+		hsubpatopt = (**ptr == 'S');
 		c = **ptr;
 		(*ptr)++;
 		ptr1 = *ptr;
@@ -4403,7 +4671,7 @@ modify(char **str, char **ptr, int inbrace)
 		break;
 
 	    case '&':
-		c = 's';
+		c = hsubpatopt ? 'S' : 's';
 		break;
 
 	    case 'g':
@@ -4492,8 +4760,11 @@ modify(char **str, char **ptr, int inbrace)
 			copy = casemodify(tt, CASMOD_UPPER);
 			break;
 		    case 's':
+		    case 'S':
+			hsubpatopt = (c == 'S');
 			if (hsubl && hsubr)
-			    subst(&copy, hsubl, hsubr, gbal);
+			    subst(&copy, dupstring(hsubl), dupstring(hsubr),
+				  gbal, hsubpatopt);
 			break;
 		    case 'q':
 			copy = quotestring(copy, QT_BACKSLASH_SHOWNULL);
@@ -4578,8 +4849,11 @@ modify(char **str, char **ptr, int inbrace)
 		    *str = casemodify(*str, CASMOD_UPPER);
 		    break;
 		case 's':
+		case 'S':
+		    hsubpatopt = (c == 'S');
 		    if (hsubl && hsubr)
-			subst(str, hsubl, hsubr, gbal);
+			subst(str, dupstring(hsubl), dupstring(hsubr),
+			      gbal, hsubpatopt);
 		    break;
 		case 'q':
 		    *str = quotestring(*str, QT_BACKSLASH);
diff --git a/Src/text.c b/Src/text.c
index 56127c457..8b1bd96b6 100644
--- a/Src/text.c
+++ b/Src/text.c
@@ -335,7 +335,7 @@ getjobtext(Eprog prog, Wordcode c)
     tlim = tptr + JOBTEXTSIZE - 1;
     tjob = 1;
     gettext2(&s);
-    if (tptr[-1] == Meta)
+    if (tptr > jbuf && tptr[-1] == Meta)
 	--tptr;
     *tptr = '\0';
     freeeprog(prog);		/* mark as unused */
diff --git a/Src/utils.c b/Src/utils.c
index 62bd3e602..ce4e875fd 100644
--- a/Src/utils.c
+++ b/Src/utils.c
@@ -74,9 +74,6 @@ set_widearray(char *mb_array, Widechar_array wca)
     }
     wca->len = 0;
 
-    if (!isset(MULTIBYTE))
-	return;
-
     if (mb_array) {
 	VARARR(wchar_t, tmpwcs, strlen(mb_array));
 	wchar_t *wcptr = tmpwcs;
@@ -86,9 +83,8 @@ set_widearray(char *mb_array, Widechar_array wca)
 	while (*mb_array) {
 	    int mblen;
 
-	    if (STOUC(*mb_array) <= 0x7f) {
-		mb_array++;
-		*wcptr++ = (wchar_t)*mb_array;
+	    if ((unsigned char) *mb_array <= 0x7f) {
+		*wcptr++ = (wchar_t)*mb_array++;
 		continue;
 	    }
 
@@ -126,14 +122,20 @@ set_widearray(char *mb_array, Widechar_array wca)
    (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)
+   %s	const char *		C string (metafied, null terminated)
+     	                 	(output "nice")
+   %l	const char *, int	C string of given length (not metafied)
+     	                 	(output raw)
    %L	long			decimal value
    %d	int			decimal value
    %z	zlong			decimal value
    %%	(none)			literal '%'
    %c	int			character at that codepoint
-   %e	int			strerror() message (argument is typically 'errno')
+   %e	int			strerror() message (argument usually 'errno')
+     	                 	(output raw)
+
+   For %s and %l, the caller is responsible for assuring end-of-string
+   is not in the middle of a metafy pair (%s) or a multibyte character.
  */
 
 static void
@@ -314,14 +316,9 @@ zerrmsg(FILE *file, const char *fmt, va_list ap)
 		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);
+		fwrite(str, num, 1, file);
 		break;
 	    }
 	    case 'L':
@@ -380,11 +377,13 @@ zerrmsg(FILE *file, const char *fmt, va_list ap)
     fflush(file);
 }
 
+#ifdef HAVE_SETUPTERM
 /*
  * Wrapper for setupterm() and del_curterm().
  * These are called from terminfo.c and termcap.c.
  */
 static int term_count;	/* reference count of cur_term */
+#endif
 
 /**/
 mod_export void
@@ -717,7 +716,8 @@ wcs_nicechar(wchar_t c, size_t *widthp, char **swidep)
  */
 
 /**/
-mod_export int is_wcs_nicechar(wchar_t c)
+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)
@@ -1071,7 +1071,7 @@ get_username(void)
 	cached_uid = current_uid;
 	zsfree(cached_username);
 	if ((pswd = getpwuid(current_uid)))
-	    cached_username = ztrdup(pswd->pw_name);
+	    cached_username = ztrdup_metafy(pswd->pw_name);
 	else
 	    cached_username = ztrdup("");
     }
@@ -1543,7 +1543,8 @@ preprompt(void)
 	if (!eolmark)
 	    eolmark = "%B%S%#%s%b";
 	opts[PROMPTPERCENT] = 1;
-	str = promptexpand(eolmark, 1, NULL, NULL, NULL);
+	txtunknownattrs = TXT_ATTR_ALL;
+	str = promptexpand(eolmark, 1, NULL, NULL);
 	countprompt(str, &w, 0, -1);
 	opts[PROMPTPERCENT] = percents;
 	zputs(str, shout);
@@ -1713,7 +1714,7 @@ printprompt4(void)
 	opts[XTRACE] = 0;
 	unmetafy(s, &l);
 	s = unmetafy(promptexpand(metafy(s, l, META_NOALLOC),
-				  0, NULL, NULL, NULL), &l);
+				  0, NULL, NULL), &l);
 	opts[XTRACE] = t;
 
 	fprintf(xtrerr, "%s", s);
@@ -1732,6 +1733,13 @@ freestr(void *a)
 mod_export void
 gettyinfo(struct ttyinfo *ti)
 {
+    fdgettyinfo(SHTTY, ti);
+}
+
+/**/
+mod_export void
+fdgettyinfo(int SHTTY, struct ttyinfo *ti)
+{
     if (SHTTY != -1) {
 #ifdef HAVE_TERMIOS_H
 # ifdef HAVE_TCGETATTR
@@ -1757,6 +1765,13 @@ gettyinfo(struct ttyinfo *ti)
 mod_export void
 settyinfo(struct ttyinfo *ti)
 {
+    fdsettyinfo(SHTTY, ti);
+}
+
+/**/
+mod_export void
+fdsettyinfo(int SHTTY, struct ttyinfo *ti)
+{
     if (SHTTY != -1) {
 #ifdef HAVE_TERMIOS_H
 # ifdef HAVE_TCGETATTR
@@ -1995,6 +2010,28 @@ redup(int x, int y)
 {
     int ret = y;
 
+#ifdef HAVE_FPURGE
+    /* Make sure buffers are cleared when changing descriptor for a
+     * FILE object.  No fflush() here because the only way anything
+     * can legitimately be left in the buffer is when an error has
+     * occurred, so attempting flush here would at best error again
+     * and at worst squirt out something unexpected.
+     */
+    if (stdout && y == fileno(stdout))
+	fpurge(stdout);
+    if (stderr && y == fileno(stderr))
+	fpurge(stderr);
+    if (shout && y == fileno(shout))
+	fpurge(shout);
+    if (xtrerr && y == fileno(xtrerr))
+	fpurge(xtrerr);
+#ifndef _IONBF
+    /* See init.c setupshin() -- stdin otherwise unbuffered */
+    if (stdin && y == fileno(stdin))
+	fpurge(stdin);
+#endif
+#endif
+
     if(x < 0)
 	zclose(y);
     else if (x != y) {
@@ -2920,7 +2957,7 @@ read1char(int echo)
     restore_queue_signals(q);
     if (echo)
 	write_loop(SHTTY, &c, 1);
-    return STOUC(c);
+    return (unsigned char) c;
 }
 
 /**/
@@ -3122,7 +3159,7 @@ spckword(char **s, int hist, int cmd, int ask)
 
     if (**s == String && !*t) {
 	guess = *s + 1;
-	if (itype_end(guess, IIDENT, 1) == guess)
+	if (itype_end(guess, INAMESPC, 1) == guess)
 	    return;
 	ic = String;
 	d = 100;
@@ -3211,7 +3248,7 @@ spckword(char **s, int hist, int cmd, int ask)
 		x = 'n';
 	    } else if (shout) {
 		char *pptbuf;
-		pptbuf = promptexpand(sprompt, 0, best, guess, NULL);
+		pptbuf = promptexpand(sprompt, 0, best, guess);
 		zputs(pptbuf, shout);
 		free(pptbuf);
 		fflush(shout);
@@ -4118,27 +4155,41 @@ inittyptab(void)
      * 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;
+    if isset(MULTIBYTE)
+	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['-'] = typtab['.'] = typtab[(unsigned char) 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[(unsigned char) Meta  ] |= IMETA;
+    typtab[(unsigned char) Marker] |= IMETA;
+    for (t0 = (int) (unsigned char) Pound; t0 <= (int) (unsigned char) LAST_NORMAL_TOK; t0++)
 	typtab[t0] |= ITOK | IMETA;
-    for (t0 = (int)STOUC(Snull); t0 <= (int)STOUC(Nularg); t0++)
+    for (t0 = (int) (unsigned char) Snull; t0 <= (int) (unsigned char) 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);
+     /* ifs */
+#define CURRENT_DEFAULT_IFS (EMULATION(EMULATE_KSH|EMULATE_SH) ? \
+			    DEFAULT_IFS_SH : DEFAULT_IFS)
+#ifdef MULTIBYTE_SUPPORT
+    if (isset(MULTIBYTE)) {
+	set_widearray(ifs ? ifs : CURRENT_DEFAULT_IFS, &ifs_wide);
+	if (ifs && !ifs_wide.chars) {
+	    zwarn("IFS has an invalid character; resetting IFS to default");
+	    zsfree(ifs);
+	    ifs = ztrdup(CURRENT_DEFAULT_IFS);
+	    set_widearray(ifs, &ifs_wide);
+	}
+    }
+#endif
+     for (s = ifs ? ifs : CURRENT_DEFAULT_IFS; *s; s++) {
+	int c = (unsigned char) (*s == Meta ? *++s ^ 32 : *s);
 #ifdef MULTIBYTE_SUPPORT
-	if (!isascii(c)) {
+	if (isset(MULTIBYTE) && !isascii(c)) {
 	    /* see comment for wordchars below */
 	    continue;
 	}
@@ -4151,10 +4202,15 @@ inittyptab(void)
 	}
 	typtab[c] |= ISEP;
     }
+    /* wordchars */
+#ifdef MULTIBYTE_SUPPORT
+    if (isset(MULTIBYTE))
+	set_widearray(wordchars, &wordchars_wide);
+#endif
     for (s = wordchars ? wordchars : DEFAULT_WORDCHARS; *s; s++) {
-	int c = STOUC(*s == Meta ? *++s ^ 32 : *s);
+	int c = (unsigned char) (*s == Meta ? *++s ^ 32 : *s);
 #ifdef MULTIBYTE_SUPPORT
-	if (!isascii(c)) {
+	if (isset(MULTIBYTE) && !isascii(c)) {
 	    /*
 	     * If we have support for multibyte characters, we don't
 	     * handle non-ASCII characters here; instead, we turn
@@ -4167,22 +4223,17 @@ inittyptab(void)
 #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;
+	typtab[(unsigned char) *s] |= ISPECIAL;
     if (typtab_flags & ZTF_SP_COMMA)
-	typtab[STOUC(',')] |= ISPECIAL;
+	typtab[(unsigned char) ','] |= 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;
+	typtab[(unsigned char) *s] |= IPATTERN;
 
     unqueue_signals();
 }
@@ -4193,10 +4244,10 @@ makecommaspecial(int yesno)
 {
     if (yesno != 0) {
 	typtab_flags |= ZTF_SP_COMMA;
-	typtab[STOUC(',')] |= ISPECIAL;
+	typtab[(unsigned char) ','] |= ISPECIAL;
     } else {
 	typtab_flags &= ~ZTF_SP_COMMA;
-	typtab[STOUC(',')] &= ~ISPECIAL;
+	typtab[(unsigned char) ','] &= ~ISPECIAL;
     }
 }
 
@@ -4309,13 +4360,27 @@ wcsitype(wchar_t c, int itype)
  * 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.
+ * Currently called only with itype INAMESPC, IIDENT, IUSER or ISEP.
  */
 
 /**/
 mod_export char *
 itype_end(const char *ptr, int itype, int once)
 {
+    if (itype == INAMESPC) {
+	itype = IIDENT;
+	if (!isset(POSIXIDENTIFIERS) || EMULATION(EMULATE_KSH)) {
+	    /* Special case for names containing ".", ksh93 namespaces */
+	    char *t = itype_end(ptr + (*ptr == '.'), itype, 0);
+	    if (t > ptr + (*ptr == '.')) {
+		if (*t == '.')
+		    ptr = t + 1;	/* Fall through */
+		else if (!once)
+		    return t;
+	    }
+	}
+    }
+
 #ifdef MULTIBYTE_SUPPORT
     if (isset(MULTIBYTE) &&
 	(itype != IIDENT || !isset(POSIXIDENTIFIERS))) {
@@ -4336,7 +4401,7 @@ itype_end(const char *ptr, int itype, int once)
 
 		if (wc == WEOF) {
 		    /* invalid, treat as single character */
-		    int chr = STOUC(*ptr == Meta ? ptr[1] ^ 32 : *ptr);
+		    int chr = (unsigned char) (*ptr == Meta ? ptr[1] ^ 32 : *ptr);
 		    /* in this case non-ASCII characters can't match */
 		    if (chr > 127 || !zistype(chr,itype))
 			break;
@@ -4375,7 +4440,7 @@ itype_end(const char *ptr, int itype, int once)
     } else
 #endif
 	for (;;) {
-	    int chr = STOUC(*ptr == Meta ? ptr[1] ^ 32 : *ptr);
+	    int chr = (unsigned char) (*ptr == Meta ? ptr[1] ^ 32 : *ptr);
 	    if (!zistype(chr,itype))
 		break;
 	    ptr += (*ptr == Meta) ? 2 : 1;
@@ -4983,11 +5048,11 @@ unmeta_one(const char *in, int *sz)
     *sz = mb_metacharlenconv_r(in, &wc, &wstate);
 #else
     if (in[0] == Meta) {
-      *sz = 2;
-      wc = STOUC(in[1] ^ 32);
+	*sz = 2;
+	wc = (unsigned char) (in[1] ^ 32);
     } else {
-      *sz = 1;
-      wc = STOUC(in[0]);
+	*sz = 1;
+	wc = (unsigned char) in[0];
     }
 #endif
     return wc;
@@ -5022,11 +5087,11 @@ ztrcmp(char const *s1, char const *s2)
 
     if(!(c1 = *s1))
 	c1 = -1;
-    else if(c1 == STOUC(Meta))
+    else if(c1 == (unsigned char) Meta)
 	c1 = *++s1 ^ 32;
     if(!(c2 = *s2))
 	c2 = -1;
-    else if(c2 == STOUC(Meta))
+    else if(c2 == (unsigned char) Meta)
 	c2 = *++s2 ^ 32;
 
     if(c1 == c2)
@@ -5212,6 +5277,7 @@ nicedupstring(char const *s)
 }
 
 
+/**/
 #ifndef MULTIBYTE_SUPPORT
 /* Unmetafy and output a string, displaying special characters readably. */
 
@@ -5246,8 +5312,9 @@ niceztrlen(char const *s)
     }
     return l;
 }
-#endif
 
+/**/
+#endif
 
 /**/
 #ifdef MULTIBYTE_SUPPORT
@@ -5458,7 +5525,7 @@ mb_metacharlenconv_r(const char *s, wint_t *wcp, mbstate_t *mbsp)
     const char *ptr;
     wchar_t wc;
 
-    if (STOUC(*s) <= 0x7f) {
+    if ((unsigned char) *s <= 0x7f) {
 	if (wcp)
 	    *wcp = (wint_t)*s;
 	return 1;
@@ -5516,10 +5583,10 @@ mb_metacharlenconv_r(const char *s, wint_t *wcp, mbstate_t *mbsp)
 mod_export int
 mb_metacharlenconv(const char *s, wint_t *wcp)
 {
-    if (!isset(MULTIBYTE) || STOUC(*s) <= 0x7f) {
+    if (!isset(MULTIBYTE) || (unsigned char) *s <= 0x7f) {
 	/* treat as single byte, possibly metafied */
 	if (wcp)
-	    *wcp = (wint_t)(*s == Meta ? s[1] ^ 32 : *s);
+	    *wcp = (wint_t)(unsigned char) (*s == Meta ? s[1] ^ 32 : *s);
 	return 1 + (*s == Meta);
     }
     /*
@@ -5581,7 +5648,7 @@ mb_metastrlenend(char *ptr, int width, char *eptr)
 	    inchar = *ptr;
 	ptr++;
 
-	if (complete && STOUC(inchar) <= STOUC(0x7f)) {
+	if (complete && (unsigned char) inchar <= (unsigned char) 0x7f) {
 	    /*
 	     * We rely on 7-bit US-ASCII as a subset, so skip
 	     * multibyte handling if we have such a character.
@@ -5657,7 +5724,7 @@ mb_charlenconv_r(const char *s, int slen, wint_t *wcp, mbstate_t *mbsp)
     const char *ptr;
     wchar_t wc;
 
-    if (slen && STOUC(*s) <= 0x7f) {
+    if (slen && (unsigned char) *s <= 0x7f) {
 	if (wcp)
 	    *wcp = (wint_t)*s;
 	return 1;
@@ -5698,7 +5765,7 @@ mb_charlenconv_r(const char *s, int slen, wint_t *wcp, mbstate_t *mbsp)
 mod_export int
 mb_charlenconv(const char *s, int slen, wint_t *wcp)
 {
-    if (!isset(MULTIBYTE) || STOUC(*s) <= 0x7f) {
+    if (!isset(MULTIBYTE) || (unsigned char) *s <= 0x7f) {
 	if (wcp)
 	    *wcp = (wint_t)*s;
 	return 1;
@@ -5717,7 +5784,7 @@ mod_export int
 metacharlenconv(const char *x, int *c)
 {
     /*
-     * Here we don't use STOUC() on the chars since they
+     * Here we don't use an (unsigned char)  cast 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.
      */
@@ -5779,7 +5846,7 @@ sb_niceformat(const char *s, FILE *stream, char **outstrp, int flags)
     eptr = ptr + umlen;
 
     while (ptr < eptr) {
-	int c = STOUC(*ptr);
+	int c = (unsigned char) *ptr;
 	if (c == '\'' && (flags & NICEFLAG_QUOTE)) {
 	    fmt = "\\'";
 	    newl = 2;
@@ -5996,9 +6063,9 @@ addunprintable(char *v, const char *u, const char *uend)
 	 */
 	int c;
 	if (*u == Meta)
-	    c = STOUC(*++u ^ 32);
+	    c = (unsigned char) (*++u ^ 32);
 	else
-	    c = STOUC(*u);
+	    c = (unsigned char) *u;
 	switch (c) {
 	case '\0':
 	    *v++ = '\\';
@@ -6645,11 +6712,14 @@ dquotedzputs(char const *s, FILE *stream)
 # if defined(HAVE_NL_LANGINFO) && defined(CODESET) && !defined(__STDC_ISO_10646__)
 /* Convert a character from UCS4 encoding to UTF-8 */
 
-static size_t
+static int
 ucs4toutf8(char *dest, unsigned int wval)
 {
-    size_t len;
+    int len;
 
+    /* UCS4 is now equvalent to UTF-32 and limited to 0 - 0x10_FFFF.
+     * This function accepts 0 - 0x7FFF_FFFF (old range of UCS4) to be
+     * compatible with wctomb(3) (in UTF-8 locale) on Linux. */
     if (wval < 0x80)
       len = 1;
     else if (wval < 0x800)
@@ -6660,8 +6730,12 @@ ucs4toutf8(char *dest, unsigned int wval)
       len = 4;
     else if (wval < 0x4000000)
       len = 5;
-    else
+    else if (wval < 0x80000000)
       len = 6;
+    else {
+      zerr("character not in range");
+      return -1;
+    }
 
     switch (len) { /* falls through except to the last case */
     case 6: dest[5] = (wval & 0x3f) | 0x80; wval >>= 6;
@@ -6678,30 +6752,89 @@ ucs4toutf8(char *dest, unsigned int wval)
 }
 #endif
 
+/* Convert UCS4 to a multibyte character in current locale.
+ * Result is saved in buf (must be at least MB_CUR_MAX bytes long).
+ * Returns the number of bytes saved in buf, or -1 if conversion fails. */
 
-/*
- * 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
+/**/
+int
+ucs4tomb(unsigned int wval, char *buf)
+{
+#if defined(HAVE_WCHAR_H) && defined(HAVE_WCTOMB) && defined(__STDC_ISO_10646__)
+    int count = wctomb(buf, (wchar_t)wval);
+    if (count == -1)
+	zerr("character not in range");
+    return count;
+#else	/* !(HAVE_WCHAR_H && HAVE_WCTOMB && __STDC_ISO_10646__) */
+# if defined(HAVE_NL_LANGINFO) && defined(CODESET)
+    if (!strcmp(nl_langinfo(CODESET), "UTF-8")) {
+	return ucs4toutf8(buf, wval);
+    } else {
+#   ifdef HAVE_ICONV
+	iconv_t cd;
+	char inbuf[4], *bsave = buf;
+	ICONV_CONST char *inptr = inbuf;
+	size_t inbytes = 4, outbytes = 6;
+	const char *codesetstr = nl_langinfo(CODESET);
+	size_t count;
+	int i;
+
+	/*
+	 * 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)");
+	    return -1;
+	}
+
+	/* store value in big endian form */
+	for (i=3; i>=0; i--) {
+	    inbuf[i] = wval & 0xff;
+	    wval >>= 8;
+	}
+	count = iconv(cd, &inptr, &inbytes, &buf, &outbytes);
+	iconv_close(cd);
+	if (count) {
+	    /* -1 indicates error. Positive value means number of "invalid"
+	     * (or "non-reversible") conversions, which we consider as
+	     * "out-of-range" characters. */
+	    zerr("character not in range");
+	    return -1;
+	}
+	return buf - bsave;
+#   else    /* !HAVE_ICONV */
+	zerr("cannot do charset conversion (iconv not available)");
+	return -1;
+#   endif   /* HAVE_ICONV */
+    }
+# else	/* !(HAVE_NL_LANGINFO && CODESET) */
+    zerr("cannot do charset conversion (NLS not supported)");
+    return -1;
+# endif	/* HAVE_NL_LANGINFO && CODESET */
+#endif	/* HAVE_WCHAR_H && HAVE_WCTOMB && __STDC_ISO_10646__ */
+}
 
 /*
  * Decode a key string, turning it into the literal characters.
@@ -6758,21 +6891,6 @@ getkeystring(char *s, int *len, int how, int *misc)
     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)),
@@ -6837,7 +6955,8 @@ getkeystring(char *s, int *len, int how, int *misc)
     }
     for (; *s; s++) {
 	if (*s == '\\' && s[1]) {
-	    int miscadded;
+	    int miscadded, count, i;
+	    unsigned int wval;
 	    if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) {
 		(*misc)--;
 		miscadded = 1;
@@ -6952,86 +7071,32 @@ getkeystring(char *s, int *len, int how, int *misc)
 		    *misc = wval;
 		    return s+1;
 		}
-#if defined(HAVE_WCHAR_H) && defined(HAVE_WCTOMB) && defined(__STDC_ISO_10646__)
-		count = wctomb(t, (wchar_t)wval);
+		count = ucs4tomb(wval, t);
 		if (count == -1) {
-		    zerr("character not in range");
-		    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;
+		    }
+		    else {
+			*t = '\0';
+			*len = t - buf;
+		    }
+		    return buf;
 		}
 		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++) {
@@ -7104,7 +7169,7 @@ getkeystring(char *s, int *len, int how, int *misc)
 	    continue;
 #ifdef MULTIBYTE_SUPPORT
 	} else if ((how & GETKEY_SINGLE_CHAR) &&
-		   isset(MULTIBYTE) && STOUC(*s) > 127) {
+		   isset(MULTIBYTE) && (unsigned char) *s > 127) {
 	    wint_t wc;
 	    int len;
 	    len = mb_metacharlenconv(s, &wc);
@@ -7207,7 +7272,7 @@ getkeystring(char *s, int *len, int how, int *misc)
 	    t = tbuf;
 	}
 	if ((how & GETKEY_SINGLE_CHAR) && t != tmp) {
-	    *misc = STOUC(tmp[0]);
+	    *misc = (unsigned char) tmp[0];
 	    return s + 1;
 	}
     }
@@ -7498,8 +7563,8 @@ restoredir(struct dirsav *d)
     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)
+	if (stat(".", &sbuf) < 0 ||
+	    sbuf.st_ino != d->ino || sbuf.st_dev != d->dev)
 	    err = -2;
     }
     return err;
@@ -7524,9 +7589,9 @@ privasserted(void)
 	    /* 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_value_t cap;
+	    for(cap = 0; !cap_get_flag(caps, cap, CAP_EFFECTIVE, &val); cap++)
+		if(val && cap != CAP_WAKE_ALARM) {
 		    cap_free(caps);
 		    return 1;
 		}
@@ -7570,6 +7635,7 @@ mode_to_octal(mode_t mode)
     return m;
 }
 
+/**/
 #ifdef MAILDIR_SUPPORT
 /*
  *     Stat a file. If it's a maildir, check all messages
@@ -7693,4 +7759,6 @@ mailstat(char *path, struct stat *st)
        *st = st_ret_last = st_ret;
        return 0;
 }
+
+/**/
 #endif
diff --git a/Src/zsh.h b/Src/zsh.h
index 40f9ea537..090abf8f5 100644
--- a/Src/zsh.h
+++ b/Src/zsh.h
@@ -135,19 +135,6 @@ struct mathfunc {
 #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      *
@@ -309,6 +296,9 @@ enum {
 /*
  * Lexical tokens: unlike the character tokens above, these never
  * appear in strings and don't necessarily represent a single character.
+ *
+ * See Src/lex.c:tokstrings[] for hints on what these mean.  Note that
+ * SEPER or SEMI are both stringified as ";".
  */
 
 enum lextok {
@@ -628,7 +618,7 @@ union linkroot {
 /* Specific elements of linked lists */
 /*************************************/
 
-typedef void (*voidvoidfnptr_t) _((void));
+typedef void (*voidvoidfnptr_t) (void);
 
 /*
  * Element of the prepromptfns list.
@@ -688,7 +678,7 @@ struct timedfn {
 #define COND_MOD   18
 #define COND_MODI  19
 
-typedef int (*CondHandler) _((char **, int));
+typedef int (*CondHandler) (char **, int);
 
 struct conddef {
     Conddef next;		/* next in list                       */
@@ -1174,28 +1164,28 @@ struct dirsav {
 /* Definitions for Hash Tables */
 /*******************************/
 
-typedef void *(*VFunc) _((void *));
-typedef void (*FreeFunc) _((void *));
+typedef void *(*VFunc) (void *);
+typedef void (*FreeFunc) (void *);
 
-typedef unsigned (*HashFunc)       _((const char *));
-typedef void     (*TableFunc)      _((HashTable));
+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 *));
+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     (*ScanFunc)       (HashNode, int);
+typedef void     (*ScanTabFunc)    (HashTable, ScanFunc, int);
 
-typedef void (*PrintTableStats) _((HashTable));
+typedef void (*PrintTableStats) (HashTable);
 
 /* Hash table for standard open hashing. Instances of struct hashtable can be *
  * created only by newhashtable(). In fact, this function creates an instance *
@@ -1362,7 +1352,7 @@ struct funcstack {
 
 /* node in list of function call wrappers */
 
-typedef int (*WrapFunc) _((Eprog, FuncWrap, char *));
+typedef int (*WrapFunc) (Eprog, FuncWrap, char *);
 
 struct funcwrap {
     FuncWrap next;
@@ -1438,8 +1428,8 @@ enum {
  * builtin structure.
  */
 
-typedef int (*HandlerFunc) _((char *, char **, Options, int));
-typedef int (*HandlerFuncAssign) _((char *, char **, LinkList, Options, int));
+typedef int (*HandlerFunc) (char *, char **, Options, int);
+typedef int (*HandlerFuncAssign) (char *, char **, LinkList, Options, int);
 #define NULLBINCMD ((HandlerFunc) 0)
 
 struct builtin {
@@ -1536,10 +1526,10 @@ struct module {
 /* 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 **));
+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;
@@ -1584,11 +1574,11 @@ struct feature_enables {
 
 /* C-function hooks */
 
-typedef int (*Hookfn) _((Hookdef, void *));
+typedef int (*Hookfn) (Hookdef, void *);
 
 struct hookdef {
     Hookdef next;
-    char *name;
+    const char *name;
     Hookfn def;
     int flags;
     LinkList funcs;
@@ -1799,33 +1789,33 @@ 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));
+    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));
+    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));
+    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));
+    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));
+    HashTable (*getfn) (Param);
+    void (*setfn) (Param, HashTable);
+    void (*unsetfn) (Param, int);
 };
 
 
@@ -1862,8 +1852,9 @@ struct param {
 	GsuHash h;
     } gsu;
 
-    int base;			/* output base or floating point prec    */
-    int width;			/* field width                           */
+    int base;			/* output base or floating point prec or */
+ 				/* for namerefs, locallevel of reference */
+    int width;			/* field width or nameref subscript idx  */
     char *env;			/* location in environment, if exported  */
     char *ename;		/* name of corresponding environment var */
     Param old;			/* old struct for use with local         */
@@ -1942,9 +1933,13 @@ struct tieddata {
 				 */
 #define PM_HASHELEM     (1<<28) /* is a hash-element */
 #define PM_NAMEDDIR     (1<<29) /* has a corresponding nameddirtab entry    */
+#define PM_NAMEREF      (1<<30) /* pointer to a different parameter         */
+
+#define PM_SELFREF	PM_UNIQUE	/* Overload when namerefs resolved  */
+#define PM_NEWREF	PM_SINGLE	/* Overload in for-loop namerefs    */
 
 /* The option string corresponds to the first of the variables above */
-#define TYPESET_OPTSTR "aiEFALRZlurtxUhHTkz"
+#define TYPESET_OPTSTR "aiEFALRZlurtxUhHT"
 
 /* These typeset options take an optional numeric argument */
 #define TYPESET_OPTNUM "LRZiEF"
@@ -1967,6 +1962,10 @@ struct tieddata {
 				  * elements
 				  */
 #define SCANPM_CHECKING   (1<<10) /* Check if set, no need to create */
+#define SCANPM_NOEXEC     (1<<11) /* No command substitutions, etc. */
+#define SCANPM_NONAMESPC  (1<<12) /* namespace syntax not allowed */
+#define SCANPM_NONAMEREF  (1<<13) /* named references are not followed */
+
 /* "$foo[@]"-style substitution
  * Only sign bit is significant
  */
@@ -2185,6 +2184,7 @@ typedef groupset *Groupset;
 #define PRINT_LINE	        (1<<6)
 #define PRINT_POSIX_EXPORT	(1<<7)
 #define PRINT_POSIX_READONLY	(1<<8)
+#define PRINT_WITH_NAMESPACE	(1<<9)
 
 /* flags for printing for the whence builtin */
 #define PRINT_WHENCE_CSH	(1<<7)
@@ -2220,8 +2220,6 @@ enum noerrexit_bits {
     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
 };
@@ -2658,22 +2656,25 @@ struct ttyinfo {
 #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 TCFAINTBEG     19
+#define TCSTANDOUTBEG  20
+#define TCUNDERLINEBEG 21
+#define TCITALICSBEG   22
+#define TCALLATTRSOFF  23
+#define TCSTANDOUTEND  24
+#define TCUNDERLINEEND 25
+#define TCITALICSEND   26
+#define TCHORIZPOS     27
+#define TCUPCURSOR     28
+#define TCDOWNCURSOR   29
+#define TCLEFTCURSOR   30
+#define TCRIGHTCURSOR  31
+#define TCSAVECURSOR   32
+#define TCRESTRCURSOR  33
+#define TCBACKSPACE    34
+#define TCFGCOLOUR     35
+#define TCBGCOLOUR     36
+#define TC_COUNT       37
 
 #define tccan(X) (tclen[X])
 
@@ -2688,38 +2689,27 @@ struct ttyinfo {
 #endif
 
 #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)
+#define TXTFAINT      0x0002
+#define TXTSTANDOUT   0x0004
+#define TXTUNDERLINE  0x0008
+#define TXTITALIC     0x0010
+#define TXTFGCOLOUR   0x0020
+#define TXTBGCOLOUR   0x0040
+
+#define TXT_ATTR_ALL  0x007F
+
 /*
  * Indicates to zle_refresh.c that the character entry is an
  * index into the list of multiword symbols.
  */
 #define TXT_MULTIWORD_MASK  0x0400
 
-/* used when, e.g an invalid colour is specified */
-#define TXT_ERROR 0x0800
+/* Used when, e.g an invalid colour is specified. Also used in REFRESH_ELEMENT
+ * to indicate that attributes should remain unchanged. */
+#define TXT_ERROR 0xF00000F000000003
+
+/* Mask for font weight */
+#define TXT_ATTR_FONT_WEIGHT     (TXTBOLDFACE|TXTFAINT)
 
 /* Mask for colour to use in foreground */
 #define TXT_ATTR_FG_COL_MASK     0x000000FFFFFF0000
@@ -2735,26 +2725,19 @@ struct ttyinfo {
 /* Flag to indicate that background is a 24-bit colour */
 #define TXT_ATTR_BG_24BIT        0x8000
 
-/* 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_24BIT|TXT_ATTR_BG_24BIT)
-
 /* Mask out everything to do with setting a foreground colour */
-#define TXT_ATTR_FG_ON_MASK \
+#define TXT_ATTR_FG_MASK \
     (TXTFGCOLOUR|TXT_ATTR_FG_COL_MASK|TXT_ATTR_FG_24BIT)
 
 /* Mask out everything to do with setting a background colour */
-#define TXT_ATTR_BG_ON_MASK \
+#define TXT_ATTR_BG_MASK \
     (TXTBGCOLOUR|TXT_ATTR_BG_COL_MASK|TXT_ATTR_BG_24BIT)
 
 /* 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 TXT_ATTR_COLOUR_MASK \
+    (TXT_ATTR_FG_MASK|TXT_ATTR_BG_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
@@ -2762,7 +2745,6 @@ struct ttyinfo {
  */
 #define COL_SEQ_FG	(0)
 #define COL_SEQ_BG	(1)
-#define COL_SEQ_COUNT	(2)
 
 struct color_rgb {
     unsigned int red, green, blue;
@@ -2778,11 +2760,7 @@ 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
+    TSC_PROMPT = 0x0002
 };
 
 /****************************************/
@@ -3006,7 +2984,7 @@ enum errflag_bits {
 /* Sorting */
 /***********/
 
-typedef int (*CompareFn) _((const void *, const void *));
+typedef int (*CompareFn) (const void *, const void *);
 
 enum {
     SORTIT_ANYOLDHOW = 0,	/* Defaults */
@@ -3064,13 +3042,13 @@ struct hist_stack {
     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));
+    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;
@@ -3240,7 +3218,7 @@ enum {
 
 /* compctl entry point pointers */
 
-typedef int (*CompctlReadFn) _((char *, char **, Options, char *));
+typedef int (*CompctlReadFn) (char *, char **, Options, char *);
 
 /* ZLE entry point pointer */
 
diff --git a/Src/zsh_system.h b/Src/zsh_system.h
index 6f4efce96..5c004d53e 100644
--- a/Src/zsh_system.h
+++ b/Src/zsh_system.h
@@ -82,12 +82,6 @@
  */
 #define _STRPTIME_DONTZERO
 
-#ifdef PROTOTYPES
-# define _(Args) Args
-#else
-# define _(Args) ()
-#endif
-
 #ifndef HAVE_ALLOCA
 # define alloca zhalloc
 #else
@@ -101,7 +95,7 @@
  #   pragma alloca
 #   else
 #    ifndef alloca
-char *alloca _((size_t));
+char *alloca (size_t);
 #    endif
 #   endif
 #  endif
@@ -783,7 +777,8 @@ 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__)
+#if defined(HAVE_SETENV) && defined(HAVE_UNSETENV) \
+    && !defined(SETENV_MANGLES_EQUAL)
 # define USE_SET_UNSET_ENV
 #endif
 
diff --git a/Src/ztype.h b/Src/ztype.h
index 5c85b0cd7..4675f73a9 100644
--- a/Src/ztype.h
+++ b/Src/ztype.h
@@ -43,7 +43,8 @@
 #define IWSEP    (1 << 13)
 #define INULL    (1 << 14)
 #define IPATTERN (1 << 15)
-#define zistype(X,Y) (typtab[STOUC(X)] & Y)
+#define INAMESPC (1 << 16)
+#define zistype(X,Y) (typtab[(unsigned char) (X)] & Y)
 #define idigit(X) zistype(X,IDIGIT)
 #define ialnum(X) zistype(X,IALNUM)
 #define iblank(X) zistype(X,IBLANK)	/* blank, not including \n */
diff --git a/Test/A01grammar.ztst b/Test/A01grammar.ztst
index 0312fe94e..d57085798 100644
--- a/Test/A01grammar.ztst
+++ b/Test/A01grammar.ztst
@@ -970,3 +970,51 @@ F:its expectations.
 0:Non-interactive shell command input is line buffered
 >Value is first
 >Value is second
+
+ fn() {
+   ! false
+ }
+0:! inverts the status of implicit return
+
+ fn () {
+   false
+   ! return
+ }
+ fn
+1:! does not affect return status of explicit return
+
+  msg=unset
+  for x in 1 2 3 4 5; do
+    continue && msg=set && print Not executed
+    print Not executed, neither.
+  done
+  print $msg
+0:continue causes immediate continuation
+>unset
+
+  msg=unset
+  () {
+    return && msg=set && print Not executed
+    print Not executed, not nor neither.
+  }
+  print $msg
+0:return causes immediate return
+>unset
+
+  msg=unset
+  for x in 1 2 3 4 5; do
+    ! continue || msg=set && print Not executed
+    print Not executed, neither.
+  done
+  print $msg
+0:! continue causes immediate continuation
+>unset
+
+  msg=unset
+  () {
+    ! return || msg=set && print Not executed
+    print Not executed, not nor neither.
+  }
+  print $msg
+0:! return causes immediate return
+>unset
diff --git a/Test/A02alias.ztst b/Test/A02alias.ztst
index ca415fa39..1c6969e74 100644
--- a/Test/A02alias.ztst
+++ b/Test/A02alias.ztst
@@ -123,7 +123,12 @@
   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 firstalias=notacommand
+  alias secondalias=firstalias
+  eval 'secondalias() { print does not work either; }')
+1:ALIAS_FUNC_DEF reports original alias if multiple
+?(eval):1: defining function based on alias `secondalias'
 
   (alias goodalias=isafunc
   setopt ALIAS_FUNC_DEF
diff --git a/Test/A04redirect.ztst b/Test/A04redirect.ztst
index 17f6dfa29..dc62efab3 100644
--- a/Test/A04redirect.ztst
+++ b/Test/A04redirect.ztst
@@ -3,9 +3,8 @@
 %prep
   mkdir redir.tmp && cd redir.tmp
 
-  myfd=99
-  (echo >&$myfd) 2>msg
-  bad_fd_msg="${$(<msg)##*:}"
+  bad_fd_msg="${$( { exec 9>&-; echo >&9 } 2>&1)##*:}"
+  [[ -n "$bad_fd_msg" ]]
 
 %test
 
diff --git a/Test/A05execution.ztst b/Test/A05execution.ztst
index bcadc6d56..07a24f9c8 100644
--- a/Test/A05execution.ztst
+++ b/Test/A05execution.ztst
@@ -2,7 +2,7 @@
 
   storepath=($path)
 
-  mkdir command.tmp command.tmp/dir1 command.tmp/dir2
+  mkdir command.tmp command.tmp/dir{1,2} command.tmp/{+,-}dir
 
   cd command.tmp
 
@@ -21,7 +21,10 @@
   print '#!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxnyyy' >tstcmd-interp-too-long
   print "#!${sh}\necho should not execute; exit 1" >xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxn
 
-  chmod 755 tstcmd dir1/tstcmd dir2/tstcmd
+  print 'echo no shebang in -dir' > -dir/tstcmd
+  print 'echo no shebang in +dir' > +dir/tstcmd
+
+  chmod 755 tstcmd dir{1,2}/tstcmd ./{-,+}dir/tstcmd
   chmod 755 tstcmd-slashless tstcmd-arg tstcmd-interp-too-long
   chmod 755 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxn
 
@@ -422,3 +425,12 @@ F:anonymous function, and a descriptor leak when backgrounding a pipeline
  (exit 4); repeat 0 do done
 0:'repeat 0' resets lastval
 
+ -dir/tstcmd
+ +dir/tstcmd
+ PATH=-dir tstcmd
+ PATH=+dir tstcmd
+0:shebang-less scripts are to be run by sh even when their file paths start with - or + (workers/52515)
+>no shebang in -dir
+>no shebang in +dir
+>no shebang in -dir
+>no shebang in +dir
diff --git a/Test/A06assign.ztst b/Test/A06assign.ztst
index f89edb888..3eff5331a 100644
--- a/Test/A06assign.ztst
+++ b/Test/A06assign.ztst
@@ -296,13 +296,26 @@
 
 # tests of var+=(array)
 
+ a=
+ a+=(1 2 3)
+ print "${(q@)a}"
+0:add array to empty parameter
+>'' 1 2 3
+
  unset a
  a+=(1 2 3)
- print -l $a
+ print "${(q@)a}"
 0:add array to unset parameter
->1
->2
->3
+>1 2 3
+
+ () {
+  setopt localoptions typeset_to_unset
+  typeset a
+  a+=(1 2 3)
+  print "${(q@)a}"
+ }
+0:add array to declared unset parameter
+>1 2 3
 
  a=(a)
  a+=(b)
diff --git a/Test/B02typeset.ztst b/Test/B02typeset.ztst
index 8b3988151..914eea92b 100644
--- a/Test/B02typeset.ztst
+++ b/Test/B02typeset.ztst
@@ -311,7 +311,7 @@
  print $OUTER
 0:Export of tied parameters
 >i:n:n:e:r
->typeset -xT OUTER outer=( i n n e r )
+>local -xT OUTER outer=( i n n e r )
 >typeset -aT OUTER outer=( i n n e r )
 >OUTER=i:n:n:e:r
 >outer=( i n n e r )
@@ -959,6 +959,20 @@
 >  [three]=''
 >)
 
+ () {
+  local -h status
+  typeset -p status
+ }
+0:parameter hiding preserved by "typeset -p"
+>typeset -h status=''
+
+ () {
+  local status
+  typeset -p status
+ }
+0:read-only special params are output when localized
+>typeset -i10 -r status=0
+
  (export PATH MANPATH
  path=(/bin)
  MANPATH=/
@@ -1085,12 +1099,12 @@
  }
 0: no array/hash in POSIX export/readonly -p
 >zsh:
->typeset -arx zsh_exported_readonly_array=( 2 )
->typeset -Arx zsh_exported_readonly_hash=( [3]=3 )
->typeset -rx zsh_exported_readonly_scalar=1
->typeset -arx zsh_exported_readonly_array=( 2 )
->typeset -Arx zsh_exported_readonly_hash=( [3]=3 )
->typeset -rx zsh_exported_readonly_scalar=1
+>local -arx zsh_exported_readonly_array=( 2 )
+>local -Arx zsh_exported_readonly_hash=( [3]=3 )
+>local -rx zsh_exported_readonly_scalar=1
+>local -arx zsh_exported_readonly_array=( 2 )
+>local -Arx zsh_exported_readonly_hash=( [3]=3 )
+>local -rx zsh_exported_readonly_scalar=1
 >sh:
 >export zsh_exported_readonly_scalar=1
 >readonly zsh_exported_readonly_scalar=1
diff --git a/Test/B03print.ztst b/Test/B03print.ztst
index 4d2cf9764..93a9669b0 100644
--- a/Test/B03print.ztst
+++ b/Test/B03print.ztst
@@ -305,8 +305,9 @@
  foo+=$'\tone\ttwo\tthree\tfour\n'
  foo+=$'\t\tone\t\ttwo\t\tthree\t\tfour'
  foo+='\0' # regression test for multibyte tab expand
- print -x4 $foo | tr '\0' Z # avoid raw nul byte in expected output below
- print -X4 $foo | tr '\0' Z
+ # avoid raw nul byte in expected output below
+ print ${"$(print -x4 $foo)"/$'\0'/Z}
+ print ${"$(print -X4 $foo)"/$'\0'/Z}
 0:Tab expansion by print
 >one	two	three	four
 >    one	two	three	four
diff --git a/Test/B04read.ztst b/Test/B04read.ztst
index 25c3d4173..14bdaeef5 100644
--- a/Test/B04read.ztst
+++ b/Test/B04read.ztst
@@ -82,6 +82,16 @@
 >Testing the
 >null hypothesis
 
+ read -ed '' <<<$'one\0two'
+0:empty delimiter terminates at nulls
+>one
+
+ print -n $'first line\x80second line\x80' |
+ while read -d $'\x80' line; do print $line; done
+0:read with a delimiter >= 0x80
+>first line
+>second line
+
 # 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
diff --git a/Test/C01arith.ztst b/Test/C01arith.ztst
index d0092fefa..ba9c65e5b 100644
--- a/Test/C01arith.ztst
+++ b/Test/C01arith.ztst
@@ -251,6 +251,14 @@
 >5000
 >255
 
+ set -- {101..120}
+ _10=42
+ echo $_10 : $1_0
+ echo $(( _10 )) : $(( 1_0 ))
+0:underscores in front of a numeric identifier is not a math constant
+>42 : 101_0
+>42 : 10
+
   # Force floating point.
   for expr in "3/4" "0x100/0x200" "0x30/0x10"; do
     print $(( $expr ))
diff --git a/Test/C02cond.ztst b/Test/C02cond.ztst
index 4366b4142..daea5b4f8 100644
--- a/Test/C02cond.ztst
+++ b/Test/C02cond.ztst
@@ -111,10 +111,6 @@
   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
@@ -148,9 +144,7 @@
 
   print -ru $ZTST_fd 'This test may take two seconds...'
   touch $newnewnew
-  if [[ $OSTYPE == "cygwin" ]]; then
-    ZTST_skip="[[ -N file ]] not supported on Cygwin"
-  elif (( isnfs )); then
+  if (( isnfs )); then
     ZTST_skip="[[ -N file ]] not supported with NFS"
   elif ! zmodload -F zsh/stat b:zstat 2> /dev/null; then
     ZTST_skip='[[ -N file ]] not tested; zsh/stat not available'
diff --git a/Test/C03traps.ztst b/Test/C03traps.ztst
index f120809a7..de57765a0 100644
--- a/Test/C03traps.ztst
+++ b/Test/C03traps.ztst
@@ -670,6 +670,22 @@ F:Must be tested with a top-level script rather than source or function
 >before-out
 >before-in
 
+  (set -o err_return
+    fn() {
+      print before-in
+      { false; true } && true
+      print after-in
+    }
+    print before-out
+    fn && true
+    print after-out
+  )
+0:ERR_RETURN not triggered on LHS of "&&" in function on LHS of "&&" (regression test)
+>before-out
+>before-in
+>after-in
+>after-out
+
   mkdir -p zdotdir
   print >zdotdir/.zshenv '
   setopt norcs errreturn
@@ -713,7 +729,7 @@ F:Must be tested with a top-level script rather than source or function
     fi
   }
   fn() {
-    setopt err_return
+    setopt localoptions err_return
     fn2 || true
   }
   fn
@@ -721,6 +737,37 @@ F:Must be tested with a top-level script rather than source or function
 >Good
 
   (setopt err_exit
+  ! true
+  print OK
+  )
+0:ERR_EXIT not triggered by "! true"
+>OK
+
+  (setopt err_exit
+  fn() { true }
+  ! fn
+  print OK
+  )
+0:ERR_EXIT not triggered by "! fn"
+>OK
+
+  (setopt err_exit
+  false && true
+  print OK
+  )
+0:ERR_EXIT not triggered by "false && true"
+>OK
+
+  (setopt err_exit
+  fn() {
+    false && true
+  }
+  fn
+  print OK
+  )
+1:ERR_EXIT not triggered by "false && true" but by return from fn
+
+  (setopt err_exit
   for x in y; do
     false && true
   done
@@ -730,14 +777,15 @@ F:Must be tested with a top-level script rather than source or function
 >OK
 
   (setopt err_exit
-  integer x=0
-  while (( ! x++ )); do
-    false && true
-  done
+  fn() {
+    for x in y; do
+      false && true
+    done
+  }
+  fn
   print OK
   )
-0:ERR_EXIT not triggered by status 1 at end of while
->OK
+1:ERR_EXIT not triggered by status 1 at end of for but by return from fn
 
   (setopt err_exit
   repeat 1; do
@@ -749,6 +797,17 @@ F:Must be tested with a top-level script rather than source or function
 >OK
 
   (setopt err_exit
+  fn() {
+    repeat 1; do
+      false && true
+    done
+  }
+  fn
+  print OK
+  )
+1:ERR_EXIT not triggered by status 1 at end of repeat but by return from fn
+
+  (setopt err_exit
   if true; then
     false && true
   fi
@@ -758,6 +817,71 @@ F:Must be tested with a top-level script rather than source or function
 >OK
 
   (setopt err_exit
+  fn() {
+    if true; then
+      false && true
+    fi
+  }
+  fn
+  print OK
+  )
+1:ERR_EXIT not triggered by status 1 at end of if but by return from fn
+
+  (setopt err_exit
+  loop=true
+  while print COND; $loop; do
+    loop=false
+    false && true
+  done
+  print OK
+  )
+0:ERR_EXIT not triggered by status 1 at end of while
+>COND
+>COND
+>OK
+
+  (setopt err_exit
+  fn() {
+    loop=true
+    while print COND; $loop; do
+      loop=false
+      false && true
+    done
+  }
+  fn
+  print OK
+  )
+1:ERR_EXIT not triggered by status 1 at end of while but by return from fn
+>COND
+>COND
+
+  (setopt err_exit
+  {
+    false && true
+  } always {
+    print ALWAYS
+  }
+  print OK
+  )
+0:ERR_EXIT not triggered by status 1 at end of always
+>ALWAYS
+>OK
+
+  (setopt err_exit
+  fn() {
+    {
+      false && true
+    } always {
+      print ALWAYS
+    }
+  }
+  fn
+  print OK
+  )
+1:ERR_EXIT not triggered by status 1 at end of always but by return from fn
+>ALWAYS
+
+  (setopt err_exit
   {
     false && true
   }
@@ -766,6 +890,17 @@ F:Must be tested with a top-level script rather than source or function
 0:ERR_EXIT not triggered by status 1 at end of { }
 >OK
 
+  (setopt err_exit
+  fn() {
+    {
+      false && true
+    }
+  }
+  fn
+  print OK
+  )
+1:ERR_EXIT not triggered by status 1 at end of { } but by return from fn
+
   unsetopt err_exit err_return
   (setopt err_exit
   for x in y; do
@@ -819,6 +954,47 @@ F:Must be tested with a top-level script rather than source or function
 1:ERR_EXIT triggered by status 1 at end of anon func
 >Still functioning
 
+  (setopt err_exit
+  loop=true; while print loop $? >&2; $loop; do loop=false; false && true; done
+  print done $? >&2
+  )
+0: ERR_EXIT neither triggered inside loop nor triggered by while statement
+?loop 0
+?loop 1
+?done 1
+
+  (setopt err_exit
+  { loop=true; while print loop $? >&2; $loop; do loop=false; false && true; done } || false
+  print done $? >&2
+  )
+1: ERR_EXIT not triggered inside loop but triggered by rhs of ||
+?loop 0
+?loop 1
+
+  (setopt err_exit
+  eval 'loop=true; while print loop $? >&2; $loop; do loop=false; false && true; done'
+  print done $? >&2
+  )
+1: ERR_EXIT not triggered inside loop but triggered by eval
+?loop 0
+?loop 1
+
+  (setopt err_exit
+  source <(echo 'loop=true; while print loop $? >&2; $loop; do loop=false; false && true; done')
+  print done $? >&2
+  )
+1: ERR_EXIT not triggered inside loop but triggered by source
+?loop 0
+?loop 1
+
+  (setopt err_exit
+  v=$(loop=true; while print loop $? >&2; $loop; do loop=false; false && true; done)
+  print done $? >&2
+  )
+1: ERR_EXIT not triggered inside loop but triggered by command substitution
+?loop 0
+?loop 1
+
   if zmodload zsh/system 2>/dev/null; then
   (
     trap 'echo TERM; exit 2' TERM
@@ -907,6 +1083,17 @@ F:Must be tested with a top-level script rather than source or function
 >trap1
 # As of 5.7.1-test-2, the output was "out1 fn1 trap1 fn2" (on separate lines).
 
+  TRAPEXIT() { echo This is TRAPEXIT; }
+  TRAPEXIT
+  TRAPEXIT
+  TRAPEXIT
+0:No memory problems with explicit call to TRAPEXIT.
+>This is TRAPEXIT
+>This is TRAPEXIT
+>This is TRAPEXIT
+>This is TRAPEXIT
+# Three explicit calls, one implicit call at function exit.
+
 %clean
 
   rm -f TRAPEXIT
diff --git a/Test/D01prompt.ztst b/Test/D01prompt.ztst
index 6879e6fd1..55861cca1 100644
--- a/Test/D01prompt.ztst
+++ b/Test/D01prompt.ztst
@@ -258,6 +258,19 @@
   fi
 0:Equivalence of terminal colour settings (background colour)
 
+  A1=${(%):-%s}
+  A2=${(%):-%u}
+  A3=${(%):-%s%u%s}
+  [[ $A3 = $A1$A2 ]]
+0:Attribute optimisation - preserve initial disabling of attribute but drop useless later one
+
+  : ${(%):-%K{blue}}
+  A1="${(%):-%b}x"
+  : ${(%):-%k}
+  A2="${(%):-%b}x"
+  [[ $A1 = $A2 && -n $A1 && -n $A2 ]]
+0:Don't restore attributes from earlier substitution after disabling bold
+
  (RPS1=foo; echo $RPS1 $RPROMPT)
  (RPS2=bar; echo $RPS2 $RPROMPT2)
 -fD:RPS1 and RPROMPT are aliases (regression from 5.0.6) (workers/49600)
diff --git a/Test/D02glob.ztst b/Test/D02glob.ztst
index 850a535e5..4d88e5c27 100644
--- a/Test/D02glob.ztst
+++ b/Test/D02glob.ztst
@@ -817,6 +817,32 @@
 *>*/glob.tmp/(flip|flop)
 *>*/glob.tmp/(flip|flop)/trailing/components
 
+# The following set test an obscure problem with branches followed by
+# exclusions that shows up when the exclusion matches against
+# something other than the complete test string, hence the complicated
+# double negative.
+  [[ ab = (|a*)~^(*b) ]]
+0:Regression test for exclusion after branches: empty first alternative
+
+  [[ ab = (b|a*)~^(*b) ]]
+0:Regression test for exclusion after branches: non-empty first alternative
+
+  [[ ab = (b*|a*)~^(*b) ]]
+0:Regression test for exclusion after branches: full length first alternative
+
+# Corresponding tests where the exclusion should succeed, so the
+# match fails.  It's hard to know how to provoke bugs here...
+  [[ abc = (|a*)~^(*b) ]]
+1:Regression test for exclusion after branches: failure case 1
+
+  [[ abc = (b|a*)~^(*b) ]]
+1:Regression test for exclusion after branches: failure case 2
+
+  [[ abc = (b*|a*)~^(*b) ]]
+1:Regression test for exclusion after branches: failure case 3
+
+# Careful: extendedglob off from this point.
+
   unsetopt extendedglob
   print -r -- ${(*)=${(@s.+.):-A+B}/(#b)(?)/-${(L)match[1]} ${match[1]}}
 0:the '*' qualfier enables extended_glob for pattern matching
diff --git a/Test/D04parameter.ztst b/Test/D04parameter.ztst
index 6bf55b4db..0e2a04eb5 100644
--- a/Test/D04parameter.ztst
+++ b/Test/D04parameter.ztst
@@ -110,6 +110,11 @@
 *>*foo:1: 1: no arguments given
 >reached
 
+  message="expand me and remove quotes"
+  (: ${UNSET_PARAM?$message})
+1:${...?....} performs expansion on the message
+?(eval):2: UNSET_PARAM: expand me and remove quotes
+
   print ${set1:+word1} ${set1+word2} ${null1:+word3} ${null1+word4}
   print ${unset1:+word5} ${unset1+word6}
 0:${...:+...}, ${...+...}
@@ -1217,6 +1222,7 @@
   typeset -T STRING string
   print $STRING $string
   unset string
+  typeset -p string
   STRING=x:y:z
   print $STRING $string
   STRING=a:b
@@ -2275,6 +2281,27 @@ F:We do not care what $OLDPWD is, as long as it does not cause an error
 F:As of this writing, var=$@ and var="$@" with null IFS have unspecified
 F:behavior, see http://austingroupbugs.net/view.php?id=888
 
+  (
+  IFS=$'\x80'
+  if [[ $IFS = $' \t\n\0' ]]; then
+    echo OK     # if $'\x80' is illegal (e.g. Linux)
+  else          # otherwise (e.g. macOS), it should work as a separator
+    s=$'foo\x80\bar'
+    [[ ${${=s}[1]} = foo ]] && echo OK
+  fi
+  )
+0D:reset IFS to default if it contains illegal character
+>OK
+
+  (
+  unsetopt multibyte
+  IFS=$'\xc3\xa9'
+  s=$'foo\xc3bar\xa9boo'
+  echo ${${=s}[2]}
+  )
+0:eight bit chars in IFS should work if multibute option is off
+>bar
+
   () {
     setopt localoptions extendedglob
     [[ $- = [[:alnum:]]## ]] || print Failed 1
@@ -2302,6 +2329,13 @@ F:behavior, see http://austingroupbugs.net/view.php?id=888
 >x
 >y
 
+  a="string"
+  print ${(S)a//#%((#b)(*))/different}
+  print $match[1]
+0:Fully anchored string must be fully searched
+>different
+>string
+
   my_width=6
   my_index=1
   my_options=Option1
@@ -2727,3 +2761,76 @@ F:behavior, see http://austingroupbugs.net/view.php?id=888
 1:parameter expansion flags parsing error gives a clue
 ?(eval):1: error in flags near position 7 in '${(zZ+x+):-}'
 
+ slash='/'
+ print -r -- x${slash/'/'}y
+0:(users/28784) substituting a single-quoted backslash, part #1: slash
+>xy
+
+ single_quote="'"
+ print -r -- x${single_quote/$'/'}y
+0:(users/28784) substituting a single-quoted backslash, part #2: single quote
+>x'y
+
+ control="foobar"
+ print -r -- x${control/'bar'}y
+0:(users/28784 inspired this) substituting a single-quoted backslash, part #3: control
+>xfooy
+
+ spacestring="string with spaces"
+ print ${spacestring:gs/[[:space:]]/ /}
+ print ${spacestring:g&}
+ print ${spacestring:gS/[[:space:]]//}
+ print ${spacestring:g&}
+0:Different behaviour of :s and :S modifiers
+>string with spaces
+>string with spaces
+>stringwithspaces
+>stringwithspaces
+
+  : ${(#X):-@}
+1:${(#X)...}: bad math expression
+?(eval):1: bad math expression: illegal character: @
+
+  echo a${(#):-@}z
+0:${(#)...}: bad math expression
+>az
+
+  printf "a%sz\n" ${(#):-@}
+0:${(#)...}: bad math expression, printf
+>az
+
+  a=( '1 +' '@' )
+  : ${(#X)a}
+1:${(#X)...}: array of bad math expressions
+?(eval):2: bad math expression: operand expected at end of string
+
+  printf "a%sz\n" ${(#)a}
+0:${(#)...}: array of bad math expressions, printf
+>az
+
+  if [[ ! -o multibyte ]]; then
+    ZTST_skip='(#X) accepts any byte if multibyte is off'
+  else
+    : ${(#X):-0x80}
+  fi
+1:${(#X)...}: out-of-range character
+?(eval):4: character not in range
+
+  [[ ${(#):-0x80} = $'\x80' ]] && echo OK
+0:${(#)...}: out-of-range character
+>OK
+
+  a=( 0x80 0x81 )
+  printf "%s\n" ${(#)a} |
+  while read x; do echo $(( #x )); done
+0:${(#)...}: array of out-of-range characters
+>128
+>129
+
+  if [[ ! -o multibyte ]]; then
+    ZTST_skip='(#X) accepts any byte if multibyte is off'
+  else
+    : ${(#X)a}
+  fi
+1:${(#X)...}: array of out-of-range characters
+?(eval):4: character not in range
diff --git a/Test/D06subscript.ztst b/Test/D06subscript.ztst
index adbd398c4..57cdc027c 100644
--- a/Test/D06subscript.ztst
+++ b/Test/D06subscript.ztst
@@ -294,3 +294,17 @@ F:Regression test for workers/42297
   [[ ${a[$i]} = ${a[i]} ]]
 0f:Math evaluation of commas in array subscripts
 F:In math, (($i)) should be the same as ((i)), see workers/47748.
+
+  string=$'foo\0bar'
+  echo ${string[(pws:\0:)1]}
+0:Word splitting by NUL
+>foo
+
+  string="a"
+  print ${string[(i)x]}
+  string=""
+  print ${string[(i)x]}
+0:Can check off end of zero length string
+F:Regression test for inconsistency of failed (i) on zero-length string
+>2
+>1
diff --git a/Test/D07multibyte.ztst b/Test/D07multibyte.ztst
index e2e9a25ef..413c4fe73 100644
--- a/Test/D07multibyte.ztst
+++ b/Test/D07multibyte.ztst
@@ -1,19 +1,7 @@
 %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
+  LANG=$(ZTST_find_UTF8)
+  if [[ -z $LANG ]]; then
     ZTST_unimplemented="no UTF-8 locale or multibyte mode is not implemented"
   else
     print -u $ZTST_fd Testing multibyte with locale $LANG
@@ -224,6 +212,20 @@
 >first
 >second
 
+  read -ed £
+0:read with multibyte delimiter where bytes of delimiter also occur in input
+<one¤twoãthree£four
+>one¤twoãthree
+
+  read -ed $'\xa0' <<<$'first\xa0second'
+0:read delimited by a byte that isn't a valid multibyte character
+>first
+
+  read -ed $'\xc2'
+0:read delimited by a single byte terminates if the byte is part of a multibyte character
+<one£two
+>one
+
   (IFS=«
   read -d » -A array
   print -l $array)
diff --git a/Test/D08cmdsubst.ztst b/Test/D08cmdsubst.ztst
index 04bf698aa..e415831a0 100644
--- a/Test/D08cmdsubst.ztst
+++ b/Test/D08cmdsubst.ztst
@@ -177,3 +177,11 @@
 0:Alias expansion needed in parsing substitutions
 >hi
 >bye
+
+# This should silently print a blank line; the original problem was
+# a parse error as the last character of the unexpanded alias
+# was erased, symptom: "command not found: W"
+  alias WI='while {false}'
+  eval 'echo $(WI blah)'
+0:Aliases with braces in command substitution can cause havoc
+>
diff --git a/Test/D09brace.ztst b/Test/D09brace.ztst
index 580ed430f..961947b67 100644
--- a/Test/D09brace.ztst
+++ b/Test/D09brace.ztst
@@ -116,3 +116,10 @@
   print -r {1..10}{..
 0:Unmatched braces after matched braces are left alone.
 >1{.. 2{.. 3{.. 4{.. 5{.. 6{.. 7{.. 8{.. 9{.. 10{..
+
+  () {
+    setopt localoptions no_multibyte
+    echo -E {$'\x80'..$'\x81'}
+  }
+0:range of 8bit chars, multibyte option unset
+>\M-^@ \M-^A
diff --git a/Test/D10nofork.ztst b/Test/D10nofork.ztst
new file mode 100644
index 000000000..5bb10266f
--- /dev/null
+++ b/Test/D10nofork.ztst
@@ -0,0 +1,515 @@
+# Tests for "nofork" command substitution.
+
+%prep
+  mkdir nofork.tmp
+  touch nofork.tmp/file{1,2}.txt
+
+  purr() { print -r -- "$@" }
+  purl() { print -rl -- "$@" }
+
+%test
+
+  REPLY=OUTER
+  purr ${| REPLY=INNER } $REPLY
+0:Basic substitution and REPLY scoping
+>INNER OUTER
+
+  reply=(x OUTER x)
+  purl ${{reply} reply=(\{ INNER \})} $reply
+0:Basic substitution, brace quoting, and array result
+>{
+>INNER
+>}
+>{
+>INNER
+>}
+
+  () {
+    setopt localoptions ignorebraces
+    purl ${{reply} reply=({ INNER })} $reply
+  }
+0:Basic substitution, ignorebraces, and array result
+>{
+>INNER
+>}
+>{
+>INNER
+>}
+
+  purr ${| REPLY=first}:${| REPLY=second}:$REPLY
+0:re-scoping of REPLY in one statement
+>first:second:OUTER
+
+  purr BEGIN${| printf -v REPLY '%s\n' one two three ; }END
+0:Adjacent words
+>BEGINone
+>two
+>three
+>END
+
+  purr "BEGIN${| printf -v REPLY '%s\n' one two three }END"
+0:Adjacent words and quoting, part 1
+>BEGINone
+>two
+>three
+>END
+
+  purr BEGIN"${| printf -v REPLY '%s\n' one two three }"END
+0:Adjacent words and quoting, part 2
+>BEGINone
+>two
+>three
+>END
+
+  purr BEGIN"${|
+   printf -v REPLY '%s\n'\
+    one two three
+  }"END
+0:Embedded newlines
+>BEGINone
+>two
+>three
+>END
+
+  purr BEGIN"${|
+   printf -v REPLY $'%s\n' one two three
+  }"END
+0:Embedded newlines and $'...'
+>BEGINone
+>two
+>three
+>END
+
+  purl ${| print -v REPLY one word here; setopt shwordsplit }
+  purl ${| print -v REPLY three words here }
+  purl "and ${| print -v REPLY one word here }"
+  unsetopt shwordsplit
+0:test word splitting on result
+F:setting option inside is too late for that substitution
+>one word here
+>three
+>words
+>here
+>and one word here
+
+ (
+  cd nofork.tmp
+  setopt globsubst
+  purr ${| REPLY=f* }
+  purr ${| REPLY=f? }*
+  unsetopt globsubst
+  purr ${| REPLY=f* }
+  purr ${| REPLY=f? }*
+ )
+1:globsubst on result
+>file1.txt file2.txt
+>file1.txt file2.txt
+>f*
+?(eval):8: no matches found: f?*
+
+  purr ${| REPLY=$'trailing newlines remain\n\n' }
+0:newline removal should not occur, part 1
+>trailing newlines remain
+>
+>
+
+  purr ${ echo $'one trailing newline\nremoved\n\n\n' }
+0:newline removal in ${ ... }, zsh mode
+>one trailing newline
+>removed
+>
+>
+>
+
+  () {
+    emulate -L ksh
+    purl ${ echo $'all trailing newlines\nremoved\n\n\n' }
+    purr "${ echo $'all trailing newlines\nremoved\n\n\n' }"
+  }
+0:newline removal in ${ ... }, emulation mode, shwordsplit
+>all
+>trailing
+>newlines
+>removed
+>all trailing newlines
+>removed
+
+  purr "${ echo $'no trailing newlines\nremoved\n\n\n' }"
+0:newline removal should not occur, part 2
+>no trailing newlines
+>removed
+>
+>
+>
+>
+
+  () {
+   purr ${| REPLY=$* ; shift 2 }
+   purr $*
+  } these are arguments
+0:access to context $argv
+>these are arguments
+>arguments
+
+  purr ${:-${| REPLY=${REPLY:-buried}}}
+  purr ${:-"${| REPLY=${REPLY:-more buried}}"}
+0:nofork inside parameter scope
+>buried
+>more buried
+
+  : ${(e):-'${| REPLY=oops'}
+1:unclosed braces are sometimes a bad substitution
+F:This seems silly, but see A01grammar ${(e):-'${'} test
+?(eval):1: bad substitution
+
+  purr ${| REPLY=oops
+1:other times lack of closing brace is merely unexpected
+F:Why not use this error in the previous case as well?
+?(eval):1: closing brace expected
+
+# Next tests check that the PS2 stack is properly managed on error
+
+  purr ${| REPLY=${REPLY:-buried}}}
+1:unbalanced braces, part 0
+?(eval):1: parse error near `}'
+
+  purr ${:-${| REPLY=${REPLY:-buried}}
+1:unbalanced braces, part 1
+?(eval):1: closing brace expected
+
+  purr ${:-"${| REPLY=${REPLY:-more buried}"}
+1:unbalanced braces, part 2
+?(eval):1: unmatched "
+
+  purr ${:-"${| REPLY=${REPLY:-more buried"}}}
+1:unbalanced braces, part 3
+?(eval):1: unmatched "
+
+  purr ${:-"${| REPLY=${REPLY:-more buried}}}"
+1:unbalanced braces, part 4
+?(eval):1: closing brace expected
+
+# Same tests with leading space (future-proofing)
+
+  purr ${ purr ${REPLY:-buried}}}
+1:unbalanced braces, part 0+
+?(eval):1: parse error near `}'
+
+  purr ${:-${ purr ${REPLY:-buried}}
+1:unbalanced braces, part 1+
+?(eval):1: closing brace expected
+
+  purr ${:-"${ purr ${REPLY:-more buried}"}
+1:unbalanced braces, part 2+
+?(eval):1: unmatched "
+
+  purr ${:-"${ purr ${REPLY:-more buried"}}}
+1:unbalanced braces, part 3+
+?(eval):1: unmatched "
+
+  purr ${:-"${ purr ${REPLY:-more buried}}}"
+1:unbalanced braces, part 4+
+?(eval):1: closing brace expected
+
+  purr "${ purr STDOUT }"
+0:capture stdout
+>STDOUT
+>
+
+# end PS2 stack tests 
+
+  purr $(purr outside ${| REPLY=inside })
+  purr BEGIN$(purr outside ${| REPLY=inside })END
+  purr "BEGIN$(purr outside ${| REPLY=inside })END"
+  purr outside ${| REPLY=$(purr inside)}
+  purr "outside ${| REPLY=$(purr inside)}"
+0:mixing with forking cmdsubst
+>outside inside
+>BEGINoutside insideEND
+>BEGINoutside insideEND
+>outside inside
+>outside inside
+
+  purr `purr outside ${| REPLY=inside }`
+  purr "outside `purr ${| REPLY=inside }`"
+  purr outside ${| REPLY=`purr inside`}
+  purr "outside ${| REPLY=`purr inside`}"
+  purr outside "`purr ${| REPLY="${:-inside}"}`"
+  purr "outside ${| REPLY=`purr ${:-inside}`}"
+0:mixing with backticks
+>outside inside
+>outside inside
+>outside inside
+>outside inside
+>outside inside
+>outside inside
+
+  purr ${| REPLY=$(( 9 + 17 )) }
+  purr $(( 9 + ${| REPLY=17 } ))
+0:mixing with arithemetic
+>26
+>26
+
+  unset reply
+  purl ${{reply} reply=(1 2 ${| REPLY=3 } 4) }
+  typeset -p reply
+0:array behavior with global assignment
+>1
+>2
+>3
+>4
+>typeset -g -a reply=( 1 2 3 4 )
+
+  unset outer
+  purr "${|
+   outer=OUTER
+   REPLY=INNER
+   return 7
+   OUTER=NOTREACHED
+  } $outer $?"
+0:return statement inside, part 1
+F:status of "print" should hide return
+>INNER OUTER 7
+
+  unset outer
+  outer=${| REPLY=${| return 7}}
+7:return status propages in assignment like $(...)
+
+  unset outer
+  purr "${|
+   outer=OUTER
+   REPLY=INNER
+   return 7
+   OUTER=NOTREACHED
+  } $outer $?"
+  print REACHED $OUTER
+0:return statement inside, part 2
+>INNER OUTER 7
+>REACHED
+
+  unset outer
+  purr "${|
+   # Localoptions needed to avoid breaking test harness?
+   # The setopt command affects surrounding context
+   setopt localoptions errreturn
+   outer=OUTER
+   REPLY=INNER
+   false
+   OUTER=NOTREACHED
+  } $outer $?"
+  print REACHED $OUTER ${options[errreturn]}
+0:errreturn works inside and remains outside
+>INNER OUTER 1
+>REACHED on
+
+ (
+  unset outer
+  purr "${|
+   outer=OUTER
+   REPLY=INNER
+   exit 7
+   OUTER=NOTREACHED
+  } $outer $OUTER $?"
+  print NOT REACHED
+ )
+7:exit statement inside
+
+ (
+  unset outer
+  purr "${|
+   setopt errexit
+   outer=OUTER
+   REPLY=INNER
+   false
+   OUTER=NOTREACHED
+  } $outer $?"
+  print NOT REACHED
+ )
+1:errexit inside
+
+  outer=GLOBAL
+  purr "${|
+   local outer=LOCAL
+   REPLY=INNER
+  } $outer $?"
+0:local declaration inside
+>INNER GLOBAL 0
+
+  unset zz
+  outer=GLOBAL
+  purr "${{zz}
+   local outer=LOCAL
+   zz=NONLOCAL
+  } $outer $?"
+  print $zz
+0:local declaration, global assignment, part 1
+>NONLOCAL GLOBAL 0
+>NONLOCAL
+
+  unset zz
+  outer=GLOBAL
+  purr "${${|
+   local outer=LOCAL
+   zz=NONLOCAL
+  }:-$zz} $outer $?"
+0:local declaration, global assignment, part 2 (evaluation order)
+>NONLOCAL GLOBAL 0
+
+  : ${| fn1() { () { print -v REPLY $'Defined Function' ;} ;} }
+  print "IN${| fn2() { () { print "${:-Second }${|fn1}" ;} ;} }OUT"
+  fn2
+0:function definition, brace nesting, quote nesting
+>INOUT
+>Second Defined Function
+
+  <<-EOF
+	${| REPLY=$'in a here document\n' }
+	EOF
+0:here-document behavior
+F:Fiddly here to get EOF past the test syntax
+>in a here document
+>
+
+  <<<${| REPLY="in a here string" }
+0:here-string behavior
+>in a here string
+
+  <<<"${ purr $'stdout as a here string' }"
+0:another capture stdout
+>stdout as a here string
+>
+
+  wrap=${| REPLY="REPLY in environment assignment" } typeset -p wrap
+  wrap=${ purr "capture in environment assignment" } typeset -p wrap
+0:assignment context
+>typeset -g wrap='REPLY in environment assignment'
+>typeset -g wrap='capture in environment assignment'
+
+# Repeat return and exit tests with stdout capture
+
+  purr "${
+   print INNER
+   return 7
+  } $?"
+0:return statement inside, part 1+
+F:status of "print" should hide return
+>INNER
+> 7
+
+  unset outer
+  outer=${ return 7 }
+7:return status propages in stdout capture
+
+  unset outer
+  purr "${
+   outer=OUTER
+   print INNER
+   return 7
+   OUTER=NOTREACHED
+  } $outer $?"
+  print REACHED $OUTER
+0:return statement inside, part 2+
+>INNER
+> OUTER 7
+>REACHED
+
+  unset outer
+  purr "${
+   # Localoptions needed to avoid breaking test harness?
+   # The setopt command affects surrounding context
+   setopt localoptions errreturn
+   outer=OUTER
+   print INNER
+   false
+   OUTER=NOTREACHED
+  } $outer $?"
+  print REACHED $OUTER ${options[errreturn]}
+0:errreturn works inside stdout capture
+>INNER
+> OUTER 1
+>REACHED on
+
+ (
+  unset outer
+  purr "${
+   outer=OUTER
+   print INNER
+   exit 7
+   OUTER=NOTREACHED
+  } $outer $OUTER $?"
+  print NOT REACHED
+ )
+7:exit statement inside stdout capture
+
+ (
+  unset outer
+  purr "${
+   setopt errexit
+   outer=OUTER
+   print INNER
+   false
+   OUTER=NOTREACHED
+  } $outer $?"
+  print NOT REACHED
+ )
+1:errexit inside stdout capture
+
+  setopt ignorebraces
+0:dummy test to set option soon enough
+F:must do this before evaluating the next test block
+
+  purr ${| REPLY=${REPLY:-buried}}}
+0:ignored braces, part 1
+>buried}
+
+  # Global $REPLY still set from earlier test
+  purr "${ purr ${REPLY:+buried}}}"
+0:ignored braces, part 2
+>buried
+>}
+
+  purr ${ { echo nested ;} }
+0:ignored braces, part 3
+>nested
+
+  purr ${ { echo nested } } DONE
+1:ignored braces, part 4
+?(eval):3: parse error near `}'
+
+  unsetopt ignorebraces
+  # "break" blocks function calls in outer loop
+  # Could use print, but that might get fixed
+  repeat 3 do purr ${
+   for x in 1 2 3 4
+    do (( x == 3 )) && break 2
+     # use error output to confirm loop count
+     print -u 2 $x
+    done
+   } XX
+  done
+0:break N propagates
+?1
+?2
+
+ # Cannot "purr": break skips pending function calls
+ # Use "repeat" to avoid infinite loop on failure 
+ repeat 3 do; echo ${|REPLY=x; break }; done
+ repeat 3 do; echo ${{x} x=y; break }; done
+ repeat 3 do; echo ${ echo z; break }; done
+0:break after assignment completes the assignment
+>x
+>y
+>z
+
+ # Subshell because error exits
+ ( purr ${ echo ${unset?oops} } )
+1:error handling (without crashing)
+*?*unset: oops
+
+ purr ${ .zsh.cmdsubst=error }
+1:reserved parameter name (without crashing)
+*?*.zsh.cmdsubst: can't modify read-only parameter
+
+%clean
+
+  unfunction purr purl
diff --git a/Test/E01options.ztst b/Test/E01options.ztst
index 2acbfd357..363846f5c 100644
--- a/Test/E01options.ztst
+++ b/Test/E01options.ztst
@@ -416,6 +416,9 @@
 1:NO_EXEC does recognize bad substitution syntax
 *?* bad substitution
 
+  (setopt noexec; : $(<nonexistentfile))
+0:NO_EXEC does not attempt to read files in $(<....)
+
   setopt NO_eval_lineno
   eval 'print $LINENO'
   setopt eval_lineno
@@ -558,12 +561,14 @@
   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]}'/)
+  print ${${:-"left[({})]over"}:fs/(\\{\\}|\\(\\)|\\[\\])//}
   unsetopt histsubstpattern
 0:HIST_SUBST_PATTERN option
 >TINGcd TINGfile1 TINGfile2 homedir
 >THUMPcd THUMPfile1 THUMPfile2
 >one.c Two.X Three.X
 >homedir scrunchyfile1 scrunchyfile2 tmpcd
+>leftover
 
   setopt ignorebraces
   echo X{a,b}Y
@@ -651,7 +656,7 @@
 >noktarg1
 >0 1
 
-  showopt() { setopt | egrep 'localoptions|ksharrays'; }
+  showopt() { echo ${(FM)${(@f)"$(setopt)"}:#(localoptions|ksharrays)*} }
   f1() { setopt localoptions ksharrays; showopt }
   f2() { setopt ksharrays; showopt }
   setopt kshoptionprint
@@ -1376,6 +1381,64 @@ F:Regression test for workers/41811
 >1
 >2
 
+  pipefailfn1() {
+     emulate -L zsh
+     setopt errreturn pipefail
+     false | { true; }
+     print "Shouldn't get here, status $?"
+  }
+  pipefailfn1
+1:PIPE_FAIL causes ERR_RETURN with complex end of pipeline: braces
+
+  pipefailfn2() {
+     emulate -L zsh
+     setopt errreturn pipefail
+     false | if true; then true; fi
+     print "Shouldn't get here, status $?"
+  }
+  pipefailfn2 || print Function failed, as expected
+0:PIPE_FAIL causes ERR_RETURN with complex end of pipeline: if
+>Function failed, as expected
+
+  pipefailfn3() {
+     emulate -L zsh
+     setopt errreturn pipefail
+     false | while true; do break; done
+     print "Shouldn't get here, status $?"
+  }
+  pipefailfn3 || print Function failed, as expected
+0:PIPE_FAIL causes ERR_RETURN with complex end of pipeline: while
+>Function failed, as expected
+
+  pipefailfn4() {
+      emulate -L zsh
+      setopt errreturn pipefail
+      false | true
+      print "Shouldn't get here, status $?"
+  }
+  pipefailfn4
+1:PIPE_FAIL causes ERR_RETURN in simple case
+
+  pipefailfn5() {
+      emulate -L zsh
+      setopt errreturn pipefail
+      false | { true | true; }
+      print "Shouldn't get here, status $?"
+  }
+  pipefailfn5 || print Function failed as expected
+0:PIPE_FAIL causes ERR_RETURN with nested successful pipe
+>Function failed as expected
+
+  pipefailfn6() {
+      emulate -L zsh
+      setopt errreturn pipefail
+      false | { false | true; }
+      print "Shouldn't get here, status $?"
+  }
+  pipefailfn6 || print Function failed as expected
+0:PIPE_FAIL causes ERR_RETURN with nested failed pipe
+>Function failed as expected
+
   for (( i = 0; i < 10; i++ )); do
      () {
         print $i
diff --git a/Test/K01nameref.ztst b/Test/K01nameref.ztst
new file mode 100644
index 000000000..bb0d11821
--- /dev/null
+++ b/Test/K01nameref.ztst
@@ -0,0 +1,893 @@
+# Tests for named references
+
+%prep
+
+ # Required in order to declare an unset hash for substitution test
+ setopt TYPESET_TO_UNSET
+
+ : ${ZTST_continue::=1}
+
+%test
+
+ typeset -n ptr
+ typeset -n
+0:minimal declaration
+>ptr
+
+ typeset -n ptr=
+ typeset -n
+0:nameref placeholder
+>ptr=''
+
+ typeset -n ptr
+ ptr=var
+ typeset -n
+0:assign nameref placeholder
+>ptr=var
+
+ unset ptr
+ typeset -n ptr
+ typeset -n ptr=var
+ typeset -n
+0:assign placeholder with new typeset
+>ptr=var
+
+ typeset -n ptr1
+ typeset -n ptr2=ptr1
+ typeset -n
+0:chain ending in placeholder
+>ptr1
+>ptr2=ptr1
+
+ typeset ptr=var
+ typeset -n ptr
+ typeset -n
+0:convert scalar to nameref
+>ptr=var
+
+ typeset -n ptr=var
+ typeset +n ptr
+ typeset -p ptr
+0:remove nameref attribute
+>typeset ptr=var
+
+ typeset -n ptr=gvar
+ () {
+   local ptr
+   typeset -p ptr
+ }
+ typeset -p ptr
+0:Local non-reference hides outside reference
+>typeset ptr
+>typeset -n ptr=gvar
+
+ typeset -n ptr
+ typeset -t ptr
+ typeset -p ptr
+0:change type of a placeholder
+F:Other type changes are fatal errors, should this also be?
+>typeset -n ptr=''
+*?*ptr: can't change type of a named reference
+
+ typeset -n ptr=var
+ typeset -t ptr
+ typeset -p ptr var
+0:change type of referenced var
+>typeset -n ptr=var
+>typeset -t var
+
+ typeset var
+ unset var
+ typeset -n ptr=var
+ typeset -t ptr
+ typeset -p ptr var
+0:change type of unset referenced var
+F:regression - at one time this incorrectly applied the tag to "ptr"
+F:note this causes "var" to become set
+>typeset -n ptr=var
+>typeset -t var
+
+ typeset -n ptr=var[2]
+ typeset -t ptr
+1:change type of referenced array element
+*?*var\[2\]: can't change type via subscript reference
+
+ typeset -n ptr[1]=var
+1:illegal nameref name
+*?*reference variable cannot be an array
+
+ typeset var=value
+ typeset -n ptr=var
+ print $ptr
+0:basic nameref expansion, no braces
+>value
+
+ typeset var=value
+ typeset -n ptr=var
+ print ${ptr}
+0:basic nameref expansion, braces
+>value
+
+ typeset var=(val1 val2)
+ typeset -n ptr=var
+ print $ptr
+0:nameref array expansion
+>val1 val2
+
+ typeset -A var=(val1 val2)
+ typeset -n ptr=var
+ print ${(kv)ptr}
+0:nameref hash expansion
+>val1 val2
+
+ typeset -n ptr=var
+ typeset var=value
+ typeset -p ptr var
+ ptr=newvalue
+ typeset -p ptr var
+0:assign existing scalar via nameref
+>typeset -n ptr=var
+>typeset var=value
+>typeset -n ptr=var
+>typeset var=newvalue
+
+ typeset -n ptr=var
+ typeset var=value
+ unset ptr
+ typeset -p var
+0:unset via nameref
+
+ typeset -n ptr=var
+ typeset var=value
+ unset -n ptr
+ typeset -p var ptr
+0:unset of the nameref itself
+F:If earlier tests change, might get "no such variable" here
+>typeset var=value
+
+ typeset -n ptr=var
+ typeset var=value
+ typeset -p ptr var
+ typeset ptr=newvalue
+ typeset -p ptr var
+0:typeset existing scalar via nameref
+>typeset -n ptr=var
+>typeset var=value
+>typeset -n ptr=var
+>typeset var=newvalue
+
+ typeset -n ptr=var
+ ptr=value
+ typeset -p var ptr
+0:assign new scalar via nameref
+>typeset -g var=value
+>typeset -n ptr=var
+
+ unset var
+ typeset -n ptr=var
+ typeset var=(val1 val2)
+ typeset -p ptr var
+ ptr=(new1 new2)
+ typeset -p ptr var
+0:assign existing array via nameref
+>typeset -n ptr=var
+>typeset -a var=( val1 val2 )
+>typeset -n ptr=var
+>typeset -a var=( new1 new2 )
+
+ typeset -p ptr ptr1 ptr2 var
+1:check state of paramtab ONE
+F:unexpected side-effects of previous tests
+*?*no such variable: ptr
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+*?*no such variable: var
+
+ typeset -n ptr=var
+ ptr=(val1 val2)
+ typeset -p var ptr
+0:assign new array via nameref
+>typeset -g -a var=( val1 val2 )
+>typeset -n ptr=var
+
+ unset var
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ typeset var=value
+ typeset -p ptr1 ptr2 var
+ print $ptr1
+0:indirect nameref expansion
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset var=value
+>value
+
+ typeset -p ptr1 ptr2 var
+1:check state of paramtab TWO
+F:unexpected side-effects of previous tests
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+*?*no such variable: var
+
+ typeset var
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ typeset ptr1=newvalue
+ typeset -p ptr1 ptr2 var
+0:typeset existing parameter indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset var=newvalue
+
+ typeset var=value
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ unset ptr1
+ typeset -p ptr1 ptr2 var
+0:unset parameter indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ typeset ptr1=newvalue
+ typeset -p ptr1 ptr2 var
+0:typeset new parameter indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset var=newvalue
+
+ unset var
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ typeset var=value
+ typeset -p ptr1 ptr2 var
+ ptr1=newvalue
+ typeset -p ptr1 ptr2 var
+0:assign new parameter indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset var=value
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset var=newvalue
+
+ typeset -p ptr1 ptr2 var
+1:check state of paramtab THREE
+F:unexpected side-effects of previous tests
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+*?*no such variable: var
+
+ typeset -a var
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ typeset ptr1=(val1 val2)
+ typeset -p ptr1 ptr2 var
+0:typeset existing array indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset -a var=( val1 val2 )
+
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ typeset ptr1=(val1 val2)
+ typeset -p ptr1 ptr2 var
+0:typeset new array indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset -a var=( val1 val2 )
+
+ typeset -p ptr1 ptr2
+1:check state of paramtab FOUR
+F:unexpected side-effects of previous tests
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+
+ unset var
+ typeset -n ptr2=var
+ typeset -n ptr1=ptr2
+ ptr1=(val1 val2)
+ typeset -p ptr1 ptr2 var
+0:assign new array indirectly
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=var
+>typeset -g -a var=( val1 val2 )
+
+ typeset -n ptr1=ptr2
+ typeset -n ptr2=ptr1
+1:direct nameref loop not allowed
+*?*invalid self reference
+
+ unset var
+ typeset -gn ptr1=var
+ typeset -p ptr1
+0:global reference to unset var
+>typeset -g -n ptr1=var
+
+ unset -n ptr1
+ typeset -gn ptr1
+ typeset -p ptr1
+ ptr1=ptr1
+1:global direct reference
+>typeset -g -n ptr1
+*?*invalid self reference
+
+ typeset -n ptr1=ptr2
+ typeset -n ptr2=ptr3
+ typeset -n ptr3=ptr1
+1:indirect nameref loop not allowed
+*?*invalid self reference
+
+ typeset -n ptr1 ptr2
+ ptr1=ptr2
+ ptr2=ptr1
+1:looping assignment not allowed
+*?*invalid self reference
+
+ unset -n ptr2
+ typeset -n ptr2='path[2]'
+ print -r -- $ptr2
+0q:nameref to array element, no braces
+>${path[2]}
+
+ unset -n ptr2
+ typeset -n ptr2='path[2]'
+ print -r -- ${ptr2}
+0q:nameref to array element, with braces
+>${path[2]}
+
+ unset -n ptr1
+ typeset -A hash=(x MISS y HIT)
+ typeset -n ptr1='hash[y]'
+ print -r -- $ptr1
+0:nameref to hash element, no braces
+>HIT
+
+ unset -n ptr1
+ typeset -A hash=(x MISS y HIT)
+ typeset -n ptr1='hash[y]'
+ print -r -- ${ptr1}
+0:nameref to hash element, with braces
+>HIT
+
+ unset -n ptr2
+ typeset -a ary=(1 2)
+ typeset -n ptr2='ary[2]'
+ ptr2=TWO
+ typeset -p ary
+0:assign array element by nameref
+>typeset -a ary=( 1 TWO )
+
+ unset -n ptr2
+ typeset -n ptr2='ary[2]'
+ ptr2=TWO
+ typeset -p ary
+0f:create array element by nameref
+F:ksh93 does not implement this either
+>typeset -a ary=( '' TWO )
+
+ unset -n ptr1
+ typeset -A hash=(x MISS y MISS)
+ typeset -n ptr1='hash[y]'
+ ptr1=HIT
+ typeset -p hash
+0:assign to hash element by nameref
+>typeset -A hash=( [x]=MISS [y]=HIT )
+
+ unset -n ptr1
+ typeset -A hash
+ typeset -n ptr1='hash[y]'
+ ptr1=HIT
+ typeset -p hash
+0f:create hash by element nameref
+F:ksh93 does not implement this either
+>typeset -A hash=( [y]=HIT )
+
+ unset -n ptr1
+ typeset -n ptr1='not[2]good'
+1:invalid nameref
+*?*invalid variable name: not\[2\]good
+
+ unset -n ptr1
+ unset hash
+ typeset -A hash
+ typeset -n ptr1='hash[y]'
+ print ${ptr1::=HIT}
+ typeset -p ptr1 hash
+0f:create hash by element substitution
+>HIT
+>typeset -n ptr1='hash[y]'
+>typeset -A hash=( [y]=HIT )
+
+ unset -n ptr
+ unset gval
+ typeset -n ptr=gval
+ gval=global
+ () { local gval=local; print $ptr; typeset -p ptr gval }
+0:up-reference part 1
+>global
+>typeset -g -n ptr=gval
+>typeset gval=local
+
+ typeset -p ptr ptr1 ptr2 val
+1:check state of paramtab FIVE
+F:unexpected side-effects of previous tests
+*?*no such variable: ptr
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+*?*no such variable: val
+
+ unset gval
+ typeset -n ptr1=gval
+ typeset gval
+ () { typeset gval=local; ptr1=global }
+ typeset -p ptr1 gval
+0:up-reference assignment part 1
+F:All tests run inside a function, so "typeset gval" creates a local;
+F:if that were omitted, ptr1= assignment would create a true global
+F:and the output below would change to "typeset -g gval=global"
+>typeset -n ptr1=gval
+>typeset gval=global
+
+ typeset -p ptr ptr1 ptr2 val gval
+1:check state of paramtab SIX
+F:unexpected side-effects of previous tests
+*?*no such variable: ptr
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+*?*no such variable: val
+*?*no such variable: gval
+
+ typeset gval=global
+ () {
+   typeset -n ptr=gval
+   local gval=local
+   print $ptr
+ }
+ typeset -p ptr gval
+1:up-reference part 2
+>global
+*?*no such variable: ptr
+>typeset gval=global
+
+ typeset -n ptr=gval
+ () {
+    local lval=local
+    typeset -n ptr=lval
+    ptr=LOCAL
+    typeset -p lval gval ptr
+  }
+ typeset -p ptr
+0:localized namerefs hide global namerefs
+*?*no such variable: gval
+>typeset lval=LOCAL
+>typeset -n ptr=lval
+>typeset -n ptr=gval
+
+ typeset -A var=(myself outside)
+ () {
+   typeset -n myself=var[myself]
+   local -h var
+   print -r -- $myself
+   typeset -p var
+ }
+0:up-reference part 3, hidden global
+>outside
+>typeset -h var
+
+ () {
+   typeset notdef
+   unset notdef
+   () {
+     typeset -n ptr=notdef
+     ptr=(DEFINED)
+   }
+   typeset -p notdef
+ }
+0:up-reference part 4, unset local and type change
+>typeset -a notdef=( DEFINED )
+
+ () {
+   typeset -n ptr1=ptr2
+   typeset -n ptr2
+   typeset -p ptr1 ptr2
+   typeset val=LOCAL
+   () {
+     ptr1=val
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p ptr1 ptr2
+ }
+ typeset -p ptr2
+1:up-reference part 5, stacked namerefs, end not in scope
+>typeset -n ptr1=ptr2
+>typeset -n ptr2
+>ptr1=ptr2
+>ptr2=val
+>ptr1=LOCAL
+>ptr2=LOCAL
+>typeset -n ptr1=ptr2
+>typeset -n ptr2=val
+*?*no such variable: ptr2
+
+ typeset ptr2
+ () {
+   typeset -n ptr1=ptr2
+   typeset -n ptr2
+   typeset -p ptr1 ptr2
+   typeset val=LOCAL
+   () {
+     ptr1=val
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p ptr1 ptr2
+ }
+ typeset -p ptr2
+0:up-reference part 6, stacked namerefs, end is in scope
+F:Same test, should part 5 output look like this?
+>typeset -n ptr1=ptr2
+>typeset -n ptr2
+>ptr1=ptr2
+>ptr2
+>ptr1=val
+>ptr2=
+>typeset -n ptr1=ptr2
+>typeset -n ptr2
+>typeset ptr2=val
+
+ () {
+   () {
+     local var
+     typeset -nu ptr1=var
+     ptr1=outer && print -u2 assignment expected to fail
+     typeset -n ptr2=var
+     ptr2=inner
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p var
+ }
+ typeset -p var
+1:up-reference part 7, upscope namerefs, end not in scope
+>ptr1=var
+>ptr2=var
+>ptr1=
+>ptr2=inner
+*?*typeset*: no such variable: var
+*?*typeset*: no such variable: var
+
+ typeset var
+ () {
+   () {
+     local var
+     typeset -nu ptr1=var
+     ptr1=outer || print -u2 assignment expected to succeed
+     typeset -n ptr2=var
+     ptr2=inner
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p var
+ }
+ typeset -p var
+0:up-reference part 8, upscope namerefs, end in scope
+>ptr1=var
+>ptr2=var
+>ptr1=outer
+>ptr2=inner
+>typeset -g var=outer
+>typeset var=outer
+
+ if zmodload zsh/parameter; then
+ () {
+   zmodload -u zsh/parameter
+   typeset -n myself=parameters[myself]
+   local -h parameters
+   print -r -- $myself
+   typeset -p parameters
+ }
+ else ZTST_skip='Cannot zmodload zsh/parameter, skipping autoload test'
+ fi
+0:up-reference part 9, autoloading with hidden special
+>nameref-local-nameref-local
+>typeset -h parameters
+
+ if [[ $options[typesettounset] != on ]]; then
+   ZTST_skip='Ignoring zmodload bug that resets TYPESET_TO_UNSET'
+   setopt typesettounset
+ fi
+0:options reloaded
+F:Checking for a bug in zmodload that affects later tests
+
+ typeset ptr2=var2
+ typeset var2=GLOBAL
+ () {
+   typeset -n ptr1=ptr2
+   typeset ptr2=var1
+   typeset var1=VAR1
+   typeset var2=VAR2
+   print -r -- ${(P)ptr1}
+ }
+0:Order of evaluation with ${(P)...}
+>VAR2
+
+ ary=(one two three four)
+ typeset -n ptr=ary
+ print -r ${(j.:.)ptr//o/0}
+0:expansion flags and string replacement
+>0ne:tw0:three:f0ur
+
+ var=value
+ typeset -n ptr=var
+ myscalar=ptr
+ echo ${(P)myscalar}
+0:named references with (P), as ${(P)name_of_nameref}
+>value
+
+ var=value
+ myscalar=var
+ typeset -n ptr=myscalar
+ echo ${(P)ptr}
+0:named references with (P), as ${(P)nameref}
+>value
+
+ ary=( 'bry[1]' 'bry[2]' ) 
+ bry=( lorem ipsum )
+ typeset -n ptr='ary[2]'
+ print -r -- ${ptr}
+ print -r -- ${(P)ptr}
+0:named references with (P), array element to array element
+>bry[2]
+>ipsum
+
+ unset -n ref
+ unset var
+ typeset -n ref=var
+ typeset var=GLOBAL
+ () {
+  typeset -n ref=$1
+  print -r $ref
+  ref=RESET
+  typeset -p ref var
+ } ref
+ typeset -p ref var
+0:local reference points to same-name global reference, part 1
+>GLOBAL
+>typeset -n ref=ref
+>typeset -g var=RESET
+>typeset -n ref=var
+>typeset var=RESET
+
+ unset -n ref
+ unset var
+ typeset -n ref=var
+ () {
+  typeset -n ref=$1
+  print -r $ref
+  ref=RESET
+  typeset -p ref var
+ } ref
+ typeset -p ref var
+0:local reference points to same-name global reference, part 2
+>
+>typeset -n ref=ref
+>typeset -g var=RESET
+>typeset -n ref=var
+>typeset -g var=RESET
+
+ unset -n ref
+ unset one
+ typeset -n ref
+ typeset one=ONE
+ for ref in one ref two; do print -r $ref; done
+1:for-loop variable is a reference, part 1
+>ONE
+*?*ref: invalid self reference
+
+ unset -n ref
+ unset one
+ typeset -n ref
+ () {
+  typeset one=ONE
+  for ref in one ref two; do print -r ${(t)ref}; done
+ }
+1:for-loop variable is a reference, part 2
+>scalar-local
+*?*ref: invalid self reference
+
+ unset -n ref
+ unset one var
+ typeset -n ref=var
+ () {
+  typeset one=ONE
+  typeset -n ref=ref
+  for ref in one ref two; do
+   typeset -p ref
+   print -r $ref
+  done
+  typeset -p ref
+ }
+ typeset -p ref
+0:for-loop variable is a reference, part 3
+>typeset -n ref=one
+>ONE
+>typeset -n ref=ref
+>
+>typeset -n ref=two
+>
+>typeset -n ref=two
+>typeset -n ref=var
+
+ typeset -g .K01.scalar='RW'
+ typeset -gA .K01.assoc=(x y)
+ typeset -ga .K01.array=(z)
+ typeset -gi .K01.integer=0
+ typeset -gE .K01.double=0.0
+ typeset -gF .K01.float=0.0
+ typeset -gr .K01.readonly='RO'
+ typeset -n gref
+ for gref in ARGC .K01.{scalar,assoc,array,integer,double,float,readonly}
+ do
+   { unset gref } always { TRY_BLOCK_ERROR=0 }
+ done
+ typeset -p .K01.{scalar,assoc,array,integer,double,float,readonly}
+ unset .K01.{scalar,assoc,array,integer,double,float}
+0:unset various types via nameref, including a readonly special
+>typeset -g .K01.scalar
+>typeset -g -A .K01.assoc
+>typeset -g -a .K01.array
+>typeset -g -i .K01.integer
+>typeset -g -E .K01.double
+>typeset -g -F .K01.float
+>typeset -g -r .K01.readonly=RO
+*?*read-only variable: ARGC
+*?*read-only variable: .K01.readonly
+
+ unset -n ref
+ unset one
+ typeset -n ref
+ () {
+  setopt localoptions warn_nested_var
+  typeset one=ONE
+  for ref in one two; do print -r ${(t)ref}; done
+  typeset -n ref
+  for ref in one two; do print -r ${(t)ref}; done
+ }
+0:for-loop variable is a reference, part 4, warnings
+>scalar-local
+>
+>scalar-local
+>
+*?*reference ref*to local variable one
+
+ unset -n ref
+ typeset -n ref
+ () {
+   setopt localoptions warn_nested_var
+   typeset inner
+   ref=inner
+ }
+ typeset -p ref
+0:Global variable is a reference, warning
+>typeset -n ref=inner
+*?*reference ref*to local variable inner
+
+ typeset -n ptr='ary[$(echo 2)]'
+ typeset -a ary=(one two three)
+ print $ptr
+1:attempt deferred command substitution in subscript
+F:runs in `setopt noexec` so $(...) returns nothing
+*?*bad math expression: empty string
+
+ unset -n ref
+ typeset -n ref=GLOBAL
+ () {
+   typeset -gn ref=RESET
+ }
+ typeset -p ref
+0:reset global reference within function
+>typeset -n ref=RESET
+
+ unset -n ref
+ typeset -rn ref=RO
+ typeset -p ref
+ (typeset -n ref=RW)
+ print status: $? expected: 1
+ typeset +r -n ref
+ typeset -p ref
+ typeset -r +n ref
+ typeset -p ref
+ (typeset -rn ref)
+ print status: $? expected: 1
+ typeset +r -n ref=RW	# Assignment occurs after type change,
+ typeset -p ref RO	# so RO=RW here.  Potentially confusing.
+ typeset -r -n ref=RX	# No type change, so referent changes ...
+ typeset -p ref RO	# ... and previous refererent does not.
+ typeset +rn ref=RW	# Here ref=RW, again type changed first.
+ typeset -p ref
+0:add and remove readonly attribute with references
+>typeset -rn ref=RO
+*?*: ref: read-only reference
+>status: 1 expected: 1
+>typeset -n ref=RO
+>typeset -r ref=RO
+*?*: ref: read-only variable
+>status: 1 expected: 1
+>typeset -n ref=RO
+>typeset -g RO=RW
+>typeset -rn ref=RX
+>typeset -g RO=RW
+>typeset ref=RW
+
+ () {
+  typeset -n r1 r2=
+  typeset -p r1 r2
+  print -- ${(!)r1-unset}
+  print -- ${+r1}
+  typeset -p r1
+ }
+0:unset nameref remains unset when resolved
+F:relies on global TYPESET_TO_UNSET in %prep
+>typeset -n r1
+>typeset -n r2=''
+>unset
+>0
+>typeset -n r1
+
+ bar=xx
+ typeset -n foo=bar
+ () {
+   typeset -n foo; foo=zz
+   foo=zz || print -u2 foo: assignment failed
+   print $bar $zz
+ }
+ () { typeset -n foo; foo=zz; local zz; foo=zz; print $bar $zz }
+0:regression: local nameref may not in-scope a global parameter
+F:previously this could create an infinite recursion and crash
+>xx
+>xx zz
+*?*foo: assignment failed
+
+ typeset -nm foo=bar
+1:create nameref by pattern match not allowed
+*?*typeset:1: invalid reference
+
+#
+# The following tests are run in interactive mode, using PS1 as an
+# assignable special with side-effects.  This crashed at one time.
+#
+
+ # Note bypassing TYPESET_TO_UNSET here
+ $ZTST_testdir/../Src/zsh -fis <<<$'
+ typeset -n p=PS1
+ () {
+  typeset -p p
+  local p
+  typeset -p p
+  p=xx
+  typeset -p p
+ }
+ '
+0:regression: assign to local that shadows global named reference
+>typeset -g -n p=PS1
+>typeset p=''
+>typeset p=xx
+*?*
+
+ # Note bypassing TYPESET_TO_UNSET here
+ $ZTST_testdir/../Src/zsh -fis <<<$'
+ () {
+   typeset p=PS1
+   typeset -n p
+   p=zz
+ }
+ typeset -p PS1
+ '
+0:regression - converting a string into a named reference
+>typeset PS1=zz
+*?*
+
+%clean
diff --git a/Test/K02parameter.ztst b/Test/K02parameter.ztst
new file mode 100644
index 000000000..0b1a8dd4a
--- /dev/null
+++ b/Test/K02parameter.ztst
@@ -0,0 +1,154 @@
+# Test parameter expansion with namespace syntax
+# (heavily borrowed from D04parameter.ztst)
+
+%prep
+
+%test
+
+  .k02.foo='the first parameter'
+  .k02.bar='the second parameter'
+  print -l $.k02.foo ${.k02.bar}
+0:Basic scalars with namespace
+F:Braces are required
+>$.k02.foo
+>the second parameter
+
+  typeset .k02.bar='the second parameter'
+  print -l ${.k02.bar}
+0:Scalar but with typeset
+>the second parameter
+
+  .k02.array1=(the first array)
+  .k02.array2=(the second array)
+  print -l $.k02.array1 ${.k02.array2}
+0:Basic arrays with namespace
+>$.k02.array1
+>the
+>second
+>array
+
+  typeset -a .k02.array2=(the second array)
+  print -l ${.k02.array2}
+0:Array but with typeset
+>the
+>second
+>array
+
+  setopt ksharrays
+  print -l ${.k02.array2}
+  unsetopt ksharrays
+0:Basic ksharray with namespace
+>the
+
+  setopt shwordsplit
+  print -l ${.k02.foo} ${==.k02.bar}
+  unsetopt shwordsplit
+0:Basic shwordsplit with namespace
+>the
+>first
+>parameter
+>the second parameter
+
+  print ${+.k02.foo} ${+.k02.notappearinginthistest}
+0:$+... and namespace
+>1 0
+
+  .k02.x=()
+  print ${+.k02.x} ${+.k02.x[1]} ${+.k02.x[(r)foo]} ${+.k02.x[(r)bar]}
+  .k02.x=(foo)
+  print ${+.k02.x} ${+.k02.x[1]} ${+.k02.x[(r)foo]} ${+.k02.x[(r)bar]}
+0:$+... with arrays and namespace
+>1 0 0 0
+>1 1 1 0
+
+  # See D04 for complete explanation.
+  # For K02 we're just testing that flag syntax works.
+  .k02.foo='<five> {six} (seven) >eight< }nine{ |forty-two| $many$ )ten( more'
+  .k02.array=(${(z).k02.foo})
+  print -l ${(Q).k02.array}
+0:${(z)...} and ${(Q)...} for some hard to parse cases
+><
+>five
+>>
+>{six}
+>(
+>seven
+>)
+>>
+>eight
+><
+>}nine{
+>|
+>forty-two
+>|
+>$many$
+>)
+>ten( more
+
+  .k02.array=(characters in an array)
+  print ${(c)#.k02.array}
+0:${(c)#...}
+>22
+
+  () {
+    typeset -n .k02.ref=.k02.array
+    emulate -L ksh
+    print -l ${!.k02.ref} ${(!).k02.ref} ${.k02.ref}
+  }
+0:namerefs with namespaces
+>.k02.array
+>.k02.array
+>characters
+
+  k.=empty
+  k.2=test
+  print ${k.} ${k.2}
+0:Parse without leading dot (future proofing)
+>empty test
+
+  .k=OK
+  print ${.k}
+0:Bare namespace is usable (ksh compatibility)
+>OK
+
+  .k.=empty
+1:Namespace must precede an identifier, assignment
+?(eval):1: not an identifier: .k.
+
+  typeset .k.=empty
+1:Namespace must precede an identifier, typeset
+?(eval):typeset:1: not valid in this context: .k.
+
+  print ${.k.}
+1:Namespace must precede an identifier, reference
+?(eval):1: bad substitution
+
+  .2.b=not
+1:Namespace identifier must not begin with a digit, assignment
+?(eval):1: not an identifier: .2.b
+
+  typeset .2.b=not
+1:Namespace identifier must not begin with a digit, typeset
+?(eval):typeset:1: not valid in this context: .2.b
+
+  print ${.2.b}
+1:Namespace identifier must not begin with a digit, reference
+?(eval):1: bad substitution
+
+  .not.2b=question
+1:Identifier starting with a digit must be all digits, assignment
+?(eval):1: not an identifier: .not.2b
+
+  typeset .not.2b=question
+1:Identifier starting with a digit must be all digits, typeset
+?(eval):typeset:1: not valid in this context: .not.2b
+
+  print ${.not.2b}
+1:Identifier starting with a digit must be all digits, reference
+?(eval):1: bad substitution
+
+  integer .var.d=0
+  float .var.f=.2
+  print $((.var.x = ++.var.d - -.var.f))
+0:Namespaces in math context
+>1.2
diff --git a/Test/README b/Test/README
index 670434ac3..b9d393d7c 100644
--- a/Test/README
+++ b/Test/README
@@ -6,6 +6,7 @@ scripts names:
  C: shell commands with special syntax
  D: substititution
  E: options
+ K: features adopted from ksh
  P: privileged (needs super-user privileges)
  V: modules
  W: builtin interactive commands and constructs
diff --git a/Test/V07pcre.ztst b/Test/V07pcre.ztst
index c9c844d2a..b8cd31c96 100644
--- a/Test/V07pcre.ztst
+++ b/Test/V07pcre.ztst
@@ -6,20 +6,8 @@
     return 0
   fi
   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
+  LANG=$(ZTST_find_UTF8)
+  if [[ -z $LANG ]]; then
     ZTST_unimplemented="no UTF-8 locale or multibyte mode is not implemented"
   else
     print -u $ZTST_fd Testing PCRE multibyte with locale $LANG
@@ -120,6 +108,11 @@
 >0 xo→t →t
 >0 Xo→t →t
 
+  [[ foo =~ (pre)?f(o*)(opt(i)onal)?(y)* ]]
+  typeset -p match
+0:Empty string for optional captures that don't match
+>typeset -g -a match=( '' oo '' '' '' )
+
   string="The following zip codes: 78884 90210 99513"
   pcre_compile -m "\d{5}"
   pcre_match -b -- $string && print "$MATCH; ZPCRE_OP: $ZPCRE_OP"
@@ -129,12 +122,17 @@
 >78884; ZPCRE_OP: 25 30
 >90210; ZPCRE_OP: 31 36
 
-# Embedded NULs allowed in plaintext, but not in RE (although \0 as two-chars allowed)
+# Embedded NULs allowed in plaintext, in RE, pcre supports \0 as two-chars
   [[ $'a\0bc\0d' =~ '^(a\0.)(.+)$' ]]
   print "${#MATCH}; ${#match[1]}; ${#match[2]}"
 0:ensure ASCII NUL passes in and out of matched plaintext
 >6; 3; 3
 
+# PCRE2 supports NULs also in the RE
+  [[ $'a\0b\0c' =~ $'^(.\0)+' ]] && print "${#MATCH}; ${#match[1]}"
+0:ensure ASCII NUL works also in the regex
+>4; 2
+
 # Ensure the long-form infix operator works
   [[ foo -pcre-match ^f..$ ]]
   print $?
@@ -174,3 +172,37 @@
     echo $match[2] )
 0:regression for segmentation fault, workers/38307
 >test
+
+  LANG_SAVE=$LANG
+  [[ é =~ '^.\z' ]]; echo $?
+  LANG=C
+  [[ é =~ '^..\z' ]]; echo $?
+  LANG=$LANG_SAVE
+  [[ é =~ '^.\z' ]]; echo $?
+0:switch between C/UTF-8 locales
+>0
+>0
+>0
+
+  [[ abc =~ 'a(d*)bc' ]] && print "$#MATCH; $#match; ${#match[1]}"
+0:empty capture
+>3; 1; 0
+
+  [[ category/name-12345 =~ '(?x)^
+    (?<category> [^/]* ) /
+    (?<package>
+      (?<name> \w+ ) -
+      (?<version> \d+ ))$' ]]
+  typeset -p1 .pcre.match
+0:named captures
+>typeset -g -A .pcre.match=(
+>  [category]=category
+>  [name]=name
+>  [package]=name-12345
+>  [version]=12345
+>)
+
+  pcre_compile 'cat(er(pillar)?)?'
+  pcre_match -d 'the caterpillar catchment' && print $match
+0:pcre_match -d
+>caterpillar cater cat
diff --git a/Test/V10private.ztst b/Test/V10private.ztst
index 56ffbc5b4..26004a2dc 100644
--- a/Test/V10private.ztst
+++ b/Test/V10private.ztst
@@ -10,6 +10,8 @@
    sed -e 's,# test_zsh_param_private,zmodload zsh/param/private,' < $ZTST_srcdir/B02typeset.ztst > private.TMP/B02
  fi
 
+ setopt TYPESET_TO_UNSET
+
 %test
 
  (zmodload -u zsh/param/private && zmodload zsh/param/private)
@@ -26,7 +28,7 @@
  print $scalar_test
 0:basic scope hiding
 >toplevel
->local scalar_test
+>local hide scalar_test
 >0
 >toplevel
 
@@ -52,7 +54,7 @@
  print $+unset_test
 0:variable defined only in scope
 >0
->local unset_test
+>local hide unset_test
 >setme
 >0
 
@@ -68,7 +70,7 @@
  }
  print $array_test
 0:nested scope with different type, correctly restored
->local array_test
+>local hide array_test
 >in function
 >top level
 
@@ -111,7 +113,7 @@
  typeset -a hash_test=(top level)
  typeset -p hash_test
  inner () {
-  private -p hash_test
+  typeset -p hash_test
   print ${(t)hash_test} ${(kv)hash_test}
  }
  outer () {
@@ -246,7 +248,7 @@ F:note "typeset" rather than "private" in output from outer
 1:privates are not visible in anonymous functions, part 3
 >X top level
 >array_test not set
-?(anon):4: array_test: can't change parameter attribute
+?(anon):4: array_test: can't modify read-only parameter
 F:future revision will create a global with this assignment
 
  typeset -a array_test
@@ -299,6 +301,256 @@ F:future revision will create a global with this assignment
 *>*
 *>*
 
+ typeset top=TOP
+ () {
+  local -P -n test=top
+  print $top
+  () { print UP: $test }
+ }
+0:nameref can be declared private
+>TOP
+>UP:
+
+ () {
+   typeset -a ary
+   local -P -n ref=ary
+   {
+    (){
+     ref=XX	# Should be an error
+     typeset -p ary ref
+    }
+   } always {
+    TRY_BLOCK_ERROR=0
+    typeset -p ary ref
+   }
+ }
+ typeset -p ary
+1:assignment to private nameref in wrong scope, part 1
+>typeset -a ary
+>typeset -hn ref=ary
+*?*ref: can't modify read-only parameter
+*?*no such variable: ary
+
+ () {
+   typeset -a ary
+   local -P -n ref=ary
+   {
+    (){
+     typeset ref=XX	# Should create a local
+     typeset -p ary ref
+    }
+   } always {
+    TRY_BLOCK_ERROR=0
+    typeset -p ary ref
+   }
+ }
+ typeset -p ary
+1:assignment to private nameref in wrong scope, part 2
+>typeset -g -a ary
+>typeset ref=XX
+>typeset -a ary
+>typeset -hn ref=ary
+*?*no such variable: ary
+
+ () {
+   typeset -n ptr1=ptr2
+   private -n ptr2	# TYPESET_TO_UNSET makes this not a "placeholder"
+   typeset -p ptr1 ptr2
+   typeset val=LOCAL
+   () {
+     ptr1=val		# Test dies here as ptr2 is private and unset
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p ptr1 ptr2
+ }
+ typeset -p ptr2
+1:up-reference for private namerefs, end unset and not in scope
+F:See K01nameref.ztst up-reference part 5
+F:Here ptr1 finds private ptr2 by scope mismatch
+>typeset -n ptr1=ptr2
+>typeset -hn ptr2
+*?*read-only variable: ptr2
+
+ () {
+   typeset -n ptr1=ptr2
+   private -n ptr2=	# Assignment makes this a placeholder, not unset
+   typeset -p ptr1 ptr2
+   typeset val=LOCAL
+   () {
+     ptr1=val || print -u2 ptr1: assignment failed
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p ptr1 ptr2
+ }
+ typeset -p ptr2
+1:up-reference for private namerefs, end not in scope
+F:See K01nameref.ztst up-reference part 5
+F:Here ptr1 finds private ptr2 by scope mismatch
+>typeset -n ptr1=ptr2
+>typeset -hn ptr2=''
+>ptr1=ptr2
+>ptr1=
+>ptr2=
+>typeset -n ptr1=ptr2
+>typeset -hn ptr2=''
+*?*ptr1: assignment failed
+*?*no such variable: ptr2
+
+ typeset ptr2
+ () {
+   typeset -n ptr1=ptr2
+   private -n ptr2	# Set/unset is irrelevant, not referenced
+   typeset -p ptr1 ptr2
+   typeset val=LOCAL
+   () {
+     ptr1=val
+     typeset -n
+     printf "%s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p ptr1 ptr2
+ }
+ typeset -p ptr2
+0:up-reference for private namerefs, end is in scope
+F:See K01typeset.ztst up-reference part 5
+F:Here ptr1 points to global ptr2 so assignment succeeds
+>typeset -n ptr1=ptr2
+>typeset -hn ptr2
+>ptr1=ptr2
+>ptr2=val
+>ptr1=val
+>ptr2=val
+>typeset -n ptr1=ptr2
+>typeset -hn ptr2
+>typeset ptr2=val
+
+ () {
+   setopt localoptions errreturn
+   private -n ptr2
+   typeset -n ptr1=ptr2
+   typeset -p ptr1 ptr2
+   typeset val=LOCAL
+   () {
+     ptr1=val
+     typeset -n
+     printf "v %s=%s\n" ptr1 "$ptr1" ptr2 "$ptr2"
+   }
+   typeset -p ptr1 ptr2
+ }
+ typeset -p ptr1 ptr2
+1:up-reference for private namerefs, end is in scope but private
+F:Should we allow "public" namerefs to private parameters?
+*?*ptr2: invalid reference
+*?*no such variable: ptr1
+*?*no such variable: ptr2
+
+ () {
+   private x=1
+   unset x
+   x=2
+ }
+0:regression test for unset private
+
+ () {
+   private x=1
+   unset x
+   private x=2
+   print $x
+ }
+0:private may be called twice
+>2
+
+ () {
+   private x=1
+   private -a x
+   print $x
+ }
+1:private may not change parameter type
+?(anon):private:2: can't change type of private param: x
+
+ () {
+   private fd1 fd2
+   exec {fd1}>&1
+   print OK
+   () { exec {fd2}>&2 }
+   print BAD $fd2
+ }
+1:redirection cannot assign private in wrong scope
+F:Better if caught in checkclobberparam() but exec.c doesn't know scope
+>OK
+?(anon): fd2: can't modify read-only parameter
+
+ () {
+   private z=outer
+   print ${(t)z} $z
+   print ${|
+    print ${(t)z} $z
+    REPLY=$z
+   }
+ }
+0:nofork may read private in calling function
+>scalar-local-hide-special outer
+>scalar-local-hide-special outer
+>outer
+
+ () {
+   private z=outer
+   print ${(t)z} $z
+   print ${| REPLY=${{z} z=nofork} }
+   print ${(t)z} $z
+ }
+0:nofork may write to private in calling function
+>scalar-local-hide-special outer
+>nofork
+>scalar-local-hide-special nofork
+
+ () {
+   local q=outer
+   print ${|
+     private q=nofork
+     REPLY=${| REPLY=$q}
+   }
+ }
+0:nofork cannot see private in surrounding nofork
+>outer
+
+ () {
+   private z=outer
+   print ${(t)z} $z
+   print ${{z}
+     private q
+     z=${{q} q=nofork}
+   }
+   print ${(t)z} $z
+ }
+1:nofork may not change private in surrounding nofork
+>scalar-local-hide-special outer
+*?*: q: can't modify read-only parameter
+
+ () {
+   private q=outer
+   print ${|
+     () { REPLY="{$q}" }
+   }
+   print ${{q}
+     () { q=nofork }
+   }
+ }
+1:function may not access private from inside nofork
+>{}
+*?*: q: can't modify read-only parameter
+
+ () {
+   print ${|
+     private q
+     () { q=nofork }
+   }
+ }
+1:function may not access private declared in nofork
+*?*: q: can't modify read-only parameter
+
 %clean
 
+  unsetopt TYPESET_TO_UNSET
   rm -r private.TMP
diff --git a/Test/X02zlevi.ztst b/Test/X02zlevi.ztst
index 8146d6752..ccfb7b1c6 100644
--- a/Test/X02zlevi.ztst
+++ b/Test/X02zlevi.ztst
@@ -1,16 +1,7 @@
 # Tests of the vi mode of ZLE
 
 %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
+  ZSH_TEST_LANG=$(ZTST_find_UTF8)
   if ( zmodload zsh/zpty 2>/dev/null ); then
     . $ZTST_srcdir/comptest
     comptestinit -v -z $ZTST_testdir/../Src/zsh
@@ -605,6 +596,13 @@
 >BUFFER: 1ls `2`  $(3) "4" $'5' ${6}
 >CURSOR: 0
 
+  zpty_run 'bindkey -s -a "cw" "dwi"'
+  zletest $'one two\e0cwyksi'
+  zpty_run 'bindkey -r -a "cw"'
+0:for a vi command, wait to allow a longer binding to be used
+>BUFFER: yksitwo
+>CURSOR: 4
+
 %clean
 
   zmodload -ui zsh/zpty
diff --git a/Test/X03zlebindkey.ztst b/Test/X03zlebindkey.ztst
index 43692a85b..1b63b3920 100644
--- a/Test/X03zlebindkey.ztst
+++ b/Test/X03zlebindkey.ztst
@@ -3,16 +3,7 @@
 # into bindings.  The latter is particularly tricky with multibyte sequences.
 
 %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
+  ZSH_TEST_LANG=$(ZTST_find_UTF8)
   if ( zmodload zsh/zpty 2>/dev/null ); then
     . $ZTST_srcdir/comptest
     comptestinit -z $ZTST_testdir/../Src/zsh
@@ -46,6 +37,28 @@
 >"^Xy" "bar"
 >"^Xy" undefined-key
 
+  zpty_run 'bindkey -s "\e[" altbracket'
+  zletest $'$\C-A\e[17~'
+  zpty_run 'bindkey -r "\e["'
+0:binding to CSI introduction is not used if a full sequence arrives
+>BUFFER: $
+>CURSOR: 0
+
+  zpty_run 'bindkey -s "\e[1" altbracketone'
+  zletest $'$\C-A\e[17~'
+  zpty_run 'bindkey -r "\e[1"'
+0:binding to longer prefix of a CSI sequence is used
+# we assume the user knows what they're doing
+>BUFFER: altbracketone7~$
+>CURSOR: 15
+
+  zpty_run 'bindkey -s "\e[" altbracket'
+  zletest $'$\C-A\e[177'
+  zpty_run 'bindkey -r "\e["'
+0:use prefix binding where we don't have a CSI sequence
+>BUFFER: altbracket177$
+>CURSOR: 13
+
 # As we're only looking at definitions here, we don't
 # bother using the pseudo-terminal; just test in the normal fashion.
   bindkey -e
diff --git a/Test/X04zlehighlight.ztst b/Test/X04zlehighlight.ztst
index f84c02505..87a59fde5 100644
--- a/Test/X04zlehighlight.ztst
+++ b/Test/X04zlehighlight.ztst
@@ -40,7 +40,7 @@
         # Fix e^Mexit - match ((?)\r(?)), if \2 == \3, then replace with \2
         # otherwise replace with \1 stripped out of leading/trailing [[:space:]]
         REPLY=${REPLY//(#b)((?(#c0,1))$cm(?(#c0,1)))/${${${(M)match[2]:#${match[3]}}:+${match[2]}}:-${${match[1]##[[:space:]]##}%%[[:space:]]##}}}
-        [[ -n "$REPLY" ]] && print -r -- ${${REPLY%%[[:space:]]##}##[[:space:]]##}
+        [[ -n "$REPLY" ]] && print -r -- ${${REPLY%%${~cm}*}##[[:space:]]##}
       done
     }
     zpty_stop() {
@@ -79,7 +79,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:region highlight - standout overlapping on other region_highlight entry
->0m27m24mtr7mu27me word2 word3
+>0mtr7mu0me word2 word3
 
   zpty_start
   zpty_input 'rh_widget() { BUFFER="true"; region_highlight+=( "0 4 fg=green" ); }'
@@ -90,7 +90,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:basic region_highlight with 8 colors
->0m27m24mCDE|32|trueCDE|39|
+>0mCDE|32|true
 
   zpty_start
   zpty_input 'rh_widget() { region_highlight+=( "0 4 fg=green memo=someplugin" ); typeset -p region_highlight }'
@@ -145,7 +145,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:basic region_highlight with true-color (hex-triplets)
->0m27m24m38;2;4;8;16mtrueCDE|39|
+>0m38;2;4;8;16mtrue
 
   zpty_start
   zpty_input 'zmodload zsh/nearcolor'
@@ -157,7 +157,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:basic region_highlight with near-color (hex-triplets at input)
->0m27m24mCDE|3232|trueCDE|39|
+>0mCDE|3232|true
 
   zpty_start
   zpty_input 'rh_widget() { BUFFER="true"; region_highlight+=( "0 4 fg=green" ); rh2; }'
@@ -169,7 +169,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:overlapping region_highlight with 8 colors
->0m27m24mCDE|32|tCDE|31|rCDE|39|CDE|32|ueCDE|39|
+>0mCDE|32|tCDE|31|rCDE|32|ue
 
   zpty_start
   zpty_input 'rh_widget() { BUFFER="true"; region_highlight+=( "0 4 fg=#00cc00" ); rh2; }'
@@ -181,7 +181,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:overlapping region_highlight with true-color
->0m27m24m38;2;0;204;0mt38;2;204;0;0mrCDE|39|38;2;0;204;0mueCDE|39|
+>0m38;2;0;204;0mt38;2;204;0;0mr38;2;0;204;0mue
 
   zpty_start
   zpty_input 'zmodload zsh/nearcolor'
@@ -194,7 +194,7 @@
   zpty_line 1 p       # the line of interest, preserving escapes ("p")
   zpty_stop
 0:overlapping region_highlight with near-color (hex-triplets at input)
->0m27m24mCDE|340|tCDE|3160|rCDE|39|CDE|340|ueCDE|39|
+>0mCDE|340|tCDE|3160|rCDE|340|ue
 
   zpty_start
   zpty_input 'f () { zle clear-screen; zle g -f nolast; BUFFER=": ${(q)LASTWIDGET}" }; zle -N f'
@@ -205,7 +205,7 @@
   zpty_line 1 p
   zpty_stop
 0:zle $widgetname -f nolast
->0m27m24m0m27m24m: clear-screen
+>0m0m: clear-screen
 
 %clean
 
diff --git a/Test/X05zleincarg.ztst b/Test/X05zleincarg.ztst
new file mode 100644
index 000000000..cd9817c82
--- /dev/null
+++ b/Test/X05zleincarg.ztst
@@ -0,0 +1,562 @@
+# Tests the incarg ZLE widget
+
+%prep
+  ZSH_TEST_LANG=$(ZTST_find_UTF8)
+  if ( zmodload zsh/zpty 2>/dev/null ); then
+    . $ZTST_srcdir/comptest
+    comptestinit -v -z $ZTST_testdir/../Src/zsh
+  else
+    ZTST_unimplemented="the zsh/zpty module is not available"
+  fi
+  zpty_run '
+    autoload -Uz incarg
+    for name in {,vim-,vim-backward-}{,sync-}{inc,dec}arg; do
+      zle -N "$name" incarg
+    done
+    bindkey -v "^N" incarg
+    bindkey -v "^P" decarg
+    bindkey -v "^F" sync-incarg
+    bindkey -v "^B" sync-decarg
+    bindkey -a "^N" vim-incarg
+    bindkey -a "^P" vim-decarg
+    bindkey -a "^F" vim-sync-incarg
+    bindkey -a "^B" vim-sync-decarg
+    bindkey -a "^E" vim-backward-incarg
+    bindkey -a "^Y" vim-backward-decarg
+    unset TMUX_PANE ITERM_SESSION_ID
+    tmux() {
+      echo "$TMUX_PANE"
+    }
+  '
+
+%test
+
+# Basic increment & decrement
+
+  zletest $'0\C-n'
+0:incarg increments an integer
+>BUFFER: 1
+>CURSOR: 1
+
+  zletest $'0\C-p'
+0:decarg decrements an integer
+>BUFFER: -1
+>CURSOR: 2
+
+  zletest $'echo 0\e0\C-n'
+0:vim-incarg increments an integer
+>BUFFER: echo 1
+>CURSOR: 5
+
+  zletest $'echo 0\e0\C-p'
+0:vim-decarg decrements an integer
+>BUFFER: echo -1
+>CURSOR: 6
+
+  zletest $'echo 0 foo\e\C-e'
+0:vim-backward-incarg increments an integer
+>BUFFER: echo 1 foo
+>CURSOR: 5
+
+  zletest $'echo 0 foo\e\C-y'
+0:vim-backward-decarg decrements an integer
+>BUFFER: echo -1 foo
+>CURSOR: 6
+
+# sync- variants
+
+  zletest $'0\C-f'
+0:sync-incarg does nothing on unsupported terminals
+>BUFFER: 0
+>CURSOR: 1
+
+  zpty_run 'TMUX_PANE=0'
+  zletest $'0\C-f'
+  zpty_run 'unset TMUX_PANE'
+0:sync-incarg does nothing on tmux in pane 0
+>BUFFER: 0
+>CURSOR: 1
+
+  zpty_run 'TMUX_PANE=1'
+  zletest $'0\C-f'
+  zpty_run 'unset TMUX_PANE'
+0:sync-incarg increments by 1 on tmux in pane 1
+>BUFFER: 1
+>CURSOR: 1
+
+  zpty_run 'TMUX_PANE=2'
+  zletest $'0\C-f'
+  zpty_run 'unset TMUX_PANE'
+0:sync-incarg increments by 2 on tmux in pane 2
+>BUFFER: 2
+>CURSOR: 1
+
+  zpty_run 'ITERM_SESSION_ID=w0t0p0:00000000-0000-0000-0000-000000000000'
+  zletest $'0\C-f'
+  zpty_run 'unset ITERM_SESSION_ID'
+0:sync-incarg does nothing on tmux in pane 0
+>BUFFER: 0
+>CURSOR: 1
+
+  zpty_run 'ITERM_SESSION_ID=w0t0p1:00000000-0000-0000-0000-000000000000'
+  zletest $'0\C-f'
+  zpty_run 'unset ITERM_SESSION_ID'
+0:sync-incarg increments by 1 on tmux in pane 1
+>BUFFER: 1
+>CURSOR: 1
+
+  zpty_run 'ITERM_SESSION_ID=w0t0p2:00000000-0000-0000-0000-000000000000'
+  zletest $'0\C-f'
+  zpty_run 'unset ITERM_SESSION_ID'
+0:sync-incarg increments by 2 on tmux in pane 2
+>BUFFER: 2
+>CURSOR: 1
+
+  zpty_run 'TMUX_PANE=1'
+  zpty_run 'ITERM_SESSION_ID=w0t0p2:00000000-0000-0000-0000-000000000000'
+  zletest $'0\C-f'
+  zpty_run 'unset TMUX_PANE ITERM_SESSION_ID'
+0:sync-incarg prioritizes tmux pane number over iTerm2's
+>BUFFER: 1
+>CURSOR: 1
+
+  zletest $'0\e2\C-n'
+0:incarg changes the incremented amount based on the numeric argument
+>BUFFER: 2
+>CURSOR: 0
+
+  zpty_run 'incarg=3'
+  zletest $'0\e\C-n'
+  zpty_run 'unset incarg'
+0:incarg changes the default incremented amount based on the incarg variable
+>BUFFER: 3
+>CURSOR: 0
+
+  zpty_run 'incarg=3'
+  zletest $'0\e2\C-n'
+  zpty_run 'unset incarg'
+0:incarg prioritizes the numeric argument over the incarg variable
+>BUFFER: 2
+>CURSOR: 0
+
+  zpty_run 'TMUX_PANE=2'
+  zletest $'0\e2\C-f'
+  zpty_run 'unset TMUX_PANE'
+0:The sync- variants of incarg takes the numeric argument into account
+>BUFFER: 4
+>CURSOR: 0
+
+# Leading zeros
+
+  zletest $'000\C-n'
+0:incarg preserves leading zeros of decimal integers
+>BUFFER: 001
+>CURSOR: 3
+
+  zletest $'-001\C-n\C-n'
+0:incarg preserves leading zeros when the digit turns from negative to positive
+>BUFFER: 001
+>CURSOR: 3
+
+  zletest $'001\C-p\C-p'
+0:incarg preserves leading zeros when the digit turns from positive to negative
+>BUFFER: -001
+>CURSOR: 4
+
+  zletest $'001\e1000\C-n'
+0:incarg works when the result has more number of digits than the original
+>BUFFER: 1001
+>CURSOR: 3
+
+  zletest $'001\e2000\C-p'
+0:decargs works on integers with leading zeros when the result has more digits than the original
+>BUFFER: -1999
+>CURSOR: 4
+
+  zletest $'-000\C-n'
+0:incarg produces the correct number of zeros when incrementing integers starting with -0
+>BUFFER: 001
+>CURSOR: 3
+
+  zletest $'-000\C-p'
+0:decarg produces the correct number of zeros when incrementing integers starting with -0
+>BUFFER: -001
+>CURSOR: 4
+
+  zpty_run 'incarg=0'
+  zletest $'-000\C-n'
+  zpty_run 'unset incarg'
+0:incarg removes the sign when the target integer starts with -0 and the increment amount is 0
+>BUFFER: 000
+>CURSOR: 3
+
+  zletest $'-0\C-n'
+0:incarg turns -0 into 1
+>BUFFER: 1
+>CURSOR: 1
+
+  zletest $'-0\C-p'
+0:decarg turns -0 into -1
+>BUFFER: -1
+>CURSOR: 2
+
+  zpty_run 'incarg=0'
+  zletest $'-0\C-n'
+  zpty_run 'unset incarg'
+0:incarg turns -0 into 0 when the increment amount is 0
+>BUFFER: 0
+>CURSOR: 1
+
+# Binaries
+
+  zletest $'0b11\C-n'
+0:incarg can increment a binary integer
+>BUFFER: 0b100
+>CURSOR: 5
+
+  zletest $'0B11\C-n'
+0:incarg can increment a binary integer with an upper case prefix
+>BUFFER: 0B100
+>CURSOR: 5
+
+  zletest $'0b100\C-p'
+0:decarg can decrement a binary integer
+>BUFFER: 0b11
+>CURSOR: 4
+
+  zletest $'0b0011\C-n'
+0:incarg can preserve leading zeros of binaries
+>BUFFER: 0b0100
+>CURSOR: 6
+
+  zletest $'0b001\e8\C-n'
+0:incarg works on binaries when the result has more zeros than the original
+>BUFFER: 0b1001
+>CURSOR: 5
+
+  zletest $'0b0\C-p'
+0:decarg fails to produce a negative binary value
+>BUFFER: 0b0
+>CURSOR: 3
+
+# Octals
+
+  zletest $'0o7\C-n'
+0:incarg can increment an octal integer
+>BUFFER: 0o10
+>CURSOR: 4
+
+  zletest $'0O7\C-n'
+0:incarg can increment an octal integer with an upper case prefix
+>BUFFER: 0O10
+>CURSOR: 4
+
+  zletest $'0o10\C-p'
+0:decarg can decrement an octal integer
+>BUFFER: 0o7
+>CURSOR: 3
+
+  zletest $'0o0\C-p'
+0:decarg fails to produce a negative octal value
+>BUFFER: 0o0
+>CURSOR: 3
+
+# Hexadecimals
+
+  zletest $'0x9\C-n'
+0:incarg can increment a hexadecimal integer
+>BUFFER: 0xa
+>CURSOR: 3
+
+  zletest $'0X9\C-n'
+0:incarg can increment a hexadecimal integer with an upper case prefix
+>BUFFER: 0XA
+>CURSOR: 3
+
+  zletest $'0xf\C-n'
+0:incarg can increment a hexadecimal integer with no numeric digit
+>BUFFER: 0x10
+>CURSOR: 4
+
+  zletest $'0x10\C-p'
+0:decarg can decrement a hexadecimal integer
+>BUFFER: 0xf
+>CURSOR: 3
+
+  zletest $'0x0\C-p'
+0:decarg fails to produce a negative hexadecimal value
+>BUFFER: 0x0
+>CURSOR: 3
+
+  zletest $'0x0b1\C-n'
+0:incarg interprets integers starting with 0x0b as a hexadecimal
+>BUFFER: 0x0b2
+>CURSOR: 5
+
+  zletest $'0x0b1\e\C-e'
+0:vim-backward-incarg interprets integers starting with 0x0b as a hexadecimal
+>BUFFER: 0x0b2
+>CURSOR: 4
+
+# Cursor position - incarg
+
+  zletest $'echo 012ab\eF i\C-n'
+0:incarg does nothing when the cursor is placed just to the left of an integer
+>BUFFER: echo 012ab
+>CURSOR: 4
+
+  zletest $'echo 012ab\eF0i\C-n'
+0:incarg works when the cursor is placed at the leftmost digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 8
+
+  zletest $'echo 012ab\eF1i\C-n'
+0:incarg works when the cursor is placed at the inner digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 8
+
+  zletest $'echo 012ab\eF2i\C-n'
+0:incarg works when the cursor is placed at the rightmost digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 8
+
+  zletest $'echo 012ab\eFai\C-n'
+0:incarg works when the cursor is placed just to the right of an integer
+>BUFFER: echo 013ab
+>CURSOR: 8
+
+  zletest $'echo 012ab\ei\C-n'
+0:incarg does nothing when the cursor is placed more than a single letter away to the right
+>BUFFER: echo 012ab
+>CURSOR: 9
+
+  zletest $'10x9\e0\C-n'
+0:incarg turns [0-9]0x[0-9a-f] into [0-9]1x[0-9a-f] when the cursor is at the left of x
+>BUFFER: 11x9
+>CURSOR: 1
+
+  zletest $'10x9\eFx\C-n'
+0:incarg takes [0-9]0x[0-9a-f] and increments the hexadecimal part when the cursor is on x
+>BUFFER: 10xa
+>CURSOR: 3
+
+  zletest $'10x9\e\C-n'
+0:incarg takes [0-9]0x[0-9a-f] and increments the hexadecimal part when the cursor is at the right of x
+>BUFFER: 10xa
+>CURSOR: 3
+
+  zletest $'10b1\e0\C-n'
+0:incarg turns [0-9]0b[01] into [0-9]1b[01] when the cursor is at the left of b
+>BUFFER: 11b1
+>CURSOR: 1
+
+  zletest $'10b1\eFb\C-n'
+0:incarg takes [0-9]0b[01] and increments the binary part when the cursor is on b
+>BUFFER: 10b10
+>CURSOR: 4
+
+  zletest $'10b1\e\C-n'
+0:incarg takes [0-9]0b[01] and increments binary part when the cursor is at the right of b
+>BUFFER: 10b10
+>CURSOR: 4
+
+  zletest $'10o7\e0\C-n'
+0:incarg turns [0-9]0o[0-7] into [0-9]1o[0-7] when the cursor is at the left of o
+>BUFFER: 11o7
+>CURSOR: 1
+
+  zletest $'10o7\eFo\C-n'
+0:incarg takes [0-9]0o[0-7] and increments the octal part when the cursor is on o
+>BUFFER: 10o10
+>CURSOR: 4
+
+  zletest $'10o7\e\C-n'
+0:incarg takes [0-9]0o[0-7] and increments the octal part when the cursor is at the right of o
+>BUFFER: 10o10
+>CURSOR: 4
+
+  zletest $'0b0x9\eF0\C-n'
+0:incarg takes 0b0x[0-9a-f] and increments the binary part when the cursor is at the left of x
+>BUFFER: 0b1x9
+>CURSOR: 2
+
+  zletest $'0b0x9\eFx\C-n'
+0:incarg takes 0b0x[0-9a-f] and increments the hexadecimal part when the cursor is on x
+>BUFFER: 0b0xa
+>CURSOR: 4
+
+  zletest $'0b0x9\e\C-n'
+0:incarg takes 0b0x[0-9a-f] and increments the hexadecimal part when the cursor is at the right of x
+>BUFFER: 0b0xa
+>CURSOR: 4
+
+# Cursor position - vim-incarg
+
+  zletest $'echo 012ab\eF \C-n'
+0:vim-incarg works when the cursor is placed to the left of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eF0\C-n'
+0:vim-incarg works when the cursor is placed at the leftmost digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eF1\C-n'
+0:vim-incarg works when the cursor is placed at the inner digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eF2\C-n'
+0:incarg works when the cursor is placed at the rightmost digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eFa\C-n'
+0:vim-incarg does nothing when the cursor is placed to the right of an integer
+>BUFFER: echo 012ab
+>CURSOR: 8
+
+  zletest $'echo 012ab\ei\C-n'
+0:vim-incarg does nothing when the cursor is placed more than a single letter away to the right
+>BUFFER: echo 012ab
+>CURSOR: 9
+
+# Cursor position - vim-backward-incarg
+
+  zletest $'echo 012ab\eF \C-e'
+0:vim-backward-incarg does nothing when the cursor is placed just to the left of an integer
+>BUFFER: echo 012ab
+>CURSOR: 4
+
+  zletest $'echo 012ab\eF0\C-e'
+0:vim-backward-incarg works when the cursor is placed at the leftmost digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eF1\C-e'
+0:vim-backward-incarg works when the cursor is placed at the inner digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eF2\C-e'
+0:vim-backward-incarg works when the cursor is placed at the rightmost digit of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\eFa\C-e'
+0:vim-backward-incarg works when the cursor is placed just to the right of an integer
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'echo 012ab\e\C-e'
+0:vim-backward-incarg works when the cursor is placed more than a single letter away to the right
+>BUFFER: echo 013ab
+>CURSOR: 7
+
+  zletest $'10x9\eFx\C-e'
+0:vim-backward-incarg will take [0-9]0x[0-9a-f] and increment the hexadecimal part when the cursor is on x
+>BUFFER: 10xa
+>CURSOR: 3
+
+  zletest $'10x9\e\C-e'
+0:vim-backward-incarg will take [0-9]0x[0-9a-f] and increment the hexadecimal part when the cursor is on the right of x
+>BUFFER: 10xa
+>CURSOR: 3
+
+  zletest $'10b1\e0\C-e'
+0:vim-backward-incarg will turn [0-9]0b[01] into [0-9]1b[01] when the cursor is at the left of b
+>BUFFER: 11b1
+>CURSOR: 1
+
+  zletest $'10b1\eFb\C-e'
+0:vim-backward-incarg will take [0-9]0b[01] and increment the binary part when the cursor is on b
+>BUFFER: 10b10
+>CURSOR: 4
+
+  zletest $'10b1\e\C-e'
+0:vim-backward-incarg will take [0-9]0b[01] and increment the binary part when the cursor is on the right of b
+>BUFFER: 10b10
+>CURSOR: 4
+
+  zletest $'10o7\e0\C-e'
+0:vim-backward-incarg will turn [0-9]0o[0-7] into [0-9]1o[0-7] when the cursor is at the left of o
+>BUFFER: 11o7
+>CURSOR: 1
+
+  zletest $'10o7\eFo\C-e'
+0:vim-backward-incarg will take [0-9]0o[0-7] and increment the octal part when the cursor is on o
+>BUFFER: 10o10
+>CURSOR: 4
+
+  zletest $'10o7\e\C-e'
+0:vim-backward-incarg will take [0-9]0o[0-7] and increment the octal part when the cursor is at the right of o
+>BUFFER: 10o10
+>CURSOR: 4
+
+  zletest $'0b0x9\eF0\C-e'
+0:vim-backward-incarg will take 0b0x[0-9a-f] and increment the binary 0b0 when the cursor is on the left of x
+>BUFFER: 0b1x9
+>CURSOR: 2
+
+  zletest $'0b0x9\eFx\C-e'
+0:vim-backward-incarg will take 0b0x[0-9a-f] and increment the hexadecimal part when the cursor is on x
+>BUFFER: 0b0xa
+>CURSOR: 4
+
+  zletest $'0b0x9\e\C-e'
+0:vim-backward-incarg will take 0b0x[0-9a-f] and increment the hexadecimal part when the cursor is at the right of x
+>BUFFER: 0b0xa
+>CURSOR: 4
+
+# Repeats
+
+  zletest $'echo 0\e0\C-n.'
+0:vim-incarg is compatible with the repeat command
+>BUFFER: echo 2
+>CURSOR: 5
+
+  zletest $'echo 0\e0\C-p.'
+0:vim-decarg is compatible with the repeat command
+>BUFFER: echo -2
+>CURSOR: 6
+
+  zletest $'echo 0 foo\e\C-e.'
+0:vim-backward-incarg is compatible with the repeat command
+>BUFFER: echo 2 foo
+>CURSOR: 5
+
+  zletest $'echo 0\e010\C-n.'
+0:Repeats of vim-incarg takes the numeric argument into account
+>BUFFER: echo 20
+>CURSOR: 6
+
+  zletest $'echo 0 foo\e10\C-e.'
+0:Repeats of vim-backward-incarg takes the numeric argument into account
+>BUFFER: echo 20 foo
+>CURSOR: 6
+
+  zpty_run 'TMUX_PANE=0'
+  zletest $'echo 0\e0\C-f.'
+  zpty_run 'unset TMUX_PANE'
+0:Repeats of vim-sync-incarg work in pane 0
+>BUFFER: echo 0
+>CURSOR: 5
+
+  zpty_run 'TMUX_PANE=1'
+  zletest $'echo 0\e0\C-f.'
+  zpty_run 'unset TMUX_PANE'
+0:Repeats of vim-sync-incarg work in pane 1
+>BUFFER: echo 2
+>CURSOR: 5
+
+  zpty_run 'TMUX_PANE=2'
+  zletest $'echo 0\e0\C-f.'
+  zpty_run 'unset TMUX_PANE'
+0:Repeats of vim-sync-incarg work in pane 2
+>BUFFER: echo 4
+>CURSOR: 5
+
+%clean
+
+  zmodload -ui zsh/zpty
diff --git a/Test/Y01completion.ztst b/Test/Y01completion.ztst
index 6af0efc6d..fc18b19a4 100644
--- a/Test/Y01completion.ztst
+++ b/Test/Y01completion.ztst
@@ -1,16 +1,7 @@
 # Tests for completion system.
 
 %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
+  ZSH_TEST_LANG=$(ZTST_find_UTF8)
   if ( zmodload zsh/zpty 2>/dev/null ); then
     . $ZTST_srcdir/comptest
     mkdir comp.tmp
@@ -44,6 +35,54 @@
 >line: {: dir1/}{}
 >line: {: dir2/}{}
 
+  comptest $': d\t\t\t\t\t \t'
+0:unambiguous prefix and autoremovable suffix
+>line: {: dir}{}
+>line: {: dir}{}
+>DESCRIPTION:{file}
+>DI:{dir1}
+>DI:{dir2}
+>line: {: dir1/}{}
+>line: {: dir2/}{}
+>line: {: dir1/}{}
+>line: {: dir1 }{}
+>DESCRIPTION:{file}
+>DI:{dir1}
+>DI:{dir2}
+>FI:{file1}
+>FI:{file2}
+
+  comptest $': suf\ebd\t\t\t\t\t \t'
+0:unambiguous prefix and autoremovable suffix with _prefix completer
+>line: {: dir}{suf}
+>line: {: dir}{suf}
+>DESCRIPTION:{file}
+>DI:{dir1}
+>DI:{dir2}
+>line: {: dir1/}{suf}
+>line: {: dir2/}{suf}
+>line: {: dir1/}{suf}
+>line: {: dir1 }{suf}
+>DESCRIPTION:{file}
+>DI:{dir1}
+>DI:{dir2}
+>FI:{file1}
+>FI:{file2}
+F:regression test workers/51641
+
+  comptesteval 'comptest-postfunc() { compstate[insert]=1 compstate[list]= }'
+  comptest $': \t \t'
+0:compstate[insert]=1 compstate[list]=
+>line: {: dir1/}{}
+>line: {: dir1 dir1/}{}
+
+  comptest $': suf\eb\t \t'
+0:compstate[insert]=1 compstate[list]= with _prefix completer
+>line: {: dir1/}{suf}
+>line: {: dir1 dir1/}{suf}
+F:regression test workers/51641
+
+  comptesteval 'comptest-postfunc() {}'
   comptest $': *\t\t\t\t\t\t'
 0:_expand shows file types
 >line: {: dir1/}{}
@@ -84,6 +123,27 @@
 >line: {: ~user2}{}
 >line: {: ~user1}{}
 
+  comptesteval 'zsh_directory_name() { compadd "$expl[@]" -- name/1 name2 }'
+  comptest $': ~[\t\t\t\t'
+0:dynamic directory names after ~[
+>line: {: ~[name}{}
+>line: {: ~[name}{}
+>DESCRIPTION:{dynamically named directory}
+>NO:{name/1}
+>NO:{name2}
+>line: {: ~[name/1]}{}
+>line: {: ~[name2]}{}
+
+  comptest $': ~[]\C-b\t\t\t\t'
+0:dynamic directory names inside ~[...]
+>line: {: ~[name}{]}
+>line: {: ~[name}{]}
+>DESCRIPTION:{dynamically named directory}
+>NO:{name/1}
+>NO:{name2}
+>line: {: ~[name/1}{]}
+>line: {: ~[name2}{]}
+
   comptest $'echo ;:\C-b\C-b\t'
 0:directories and files before separator
 >line: {echo }{;:}
@@ -269,10 +329,10 @@ F:regression test workers/31611
   comptesteval "typeset -a bar=({$'\\0'..$'\\C-?'})"
   comptesteval 'typeset -A bat=( "$bar[@]" )'
   comptesteval 'typeset bay="$bar"'
-  comptesteval 'zstyle ":completion:*:parameters" extra-verbose yes'
+  comptesteval 'zstyle ":completion:*:parameters" verbose yes'
   comptesteval 'zstyle ":completion:*" fake-parameters bar bat bay'
   comptest $': $ba\t'
-0:extra-verbose shows parameter values
+0:verbose shows parameter values
 >line: {: $ba}{}
 >DESCRIPTION:{parameter}
 >NO:{bar  -- ( '^@' '^A' '^B' '^C' '^D' '^E' '^F' '^G' '^H' '\t' '\n' '^K' '^L' '}
@@ -282,15 +342,15 @@ F:regression test workers/31611
   comptesteval "path=( $ZTST_srcdir:A )"
   comptesteval 'typeset -H paths=HIDDEN'
   comptest $': $path\t'
-0:extra-verbose doesn't show special or hidden parameter values
+0:verbose doesn't show special or hidden parameter values
 >line: {: $path}{}
 >DESCRIPTION:{parameter}
 >NO:{path}
 >NO:{paths}
 
-  comptesteval 'zstyle -d ":completion:*:parameters" extra-verbose'
+  comptesteval 'zstyle -d ":completion:*:parameters" verbose'
   comptest $': $ba\t'
-0:parameter values not shown without extra-verbose
+0:parameter values not shown without verbose
 >line: {: $ba}{}
 >DESCRIPTION:{parameter}
 >NO:{bar}
diff --git a/Test/comptest b/Test/comptest
index 79c69979a..39ad14768 100644
--- a/Test/comptest
+++ b/Test/comptest
@@ -40,7 +40,7 @@ KEYTIMEOUT=1
 setopt zle
 autoload -U compinit
 compinit -u
-zstyle ":completion:*" completer _expand _complete _ignored
+zstyle ":completion:*" completer _expand _complete _prefix _ignored
 zstyle ":completion:*:default" list-colors "no=<NO>" "fi=<FI>" "di=<DI>" "ln=<LN>" "pi=<PI>" "so=<SO>" "bd=<BD>" "cd=<CD>" "ex=<EX>" "mi=<MI>" "tc=<TC>" "sp=<SP>" "lc=<LC>" "ec=<EC>\n" "rc=<RC>"
 zstyle ":completion:*" group-name ""
 zstyle ":completion:*:messages" format "<MESSAGE>%d</MESSAGE>
@@ -51,6 +51,12 @@ zstyle ":completion:*:options" verbose yes
 zstyle ":completion:*:values" verbose yes
 setopt noalwayslastprompt listrowsfirst completeinword
 zmodload zsh/complist
+zle -C complete-word complete-word complete-word-with-postfunc
+complete-word-with-postfunc() {
+  local +h -a comppostfuncs=( comptest-postfunc )
+  _main_complete "$@"
+}
+comptest-postfunc() {}
 complete-word-with-report () {
   print -lr "<WIDGET><complete-word>"
   zle complete-word
diff --git a/Test/runtests.zsh b/Test/runtests.zsh
index b66d579b6..538663f50 100644
--- a/Test/runtests.zsh
+++ b/Test/runtests.zsh
@@ -15,6 +15,7 @@ for file in "${(f)ZTST_testlist}"; do
     (( skipped++ ))
   elif (( $retval )); then
     (( failure++ ))
+    (( $retval > 128 )) && print "$file: failed: SIG$signals[$retval - 127]."
   else
     (( success++ ))
   fi
diff --git a/Test/ztst.zsh b/Test/ztst.zsh
index aca275c1c..1d05baddf 100755
--- a/Test/ztst.zsh
+++ b/Test/ztst.zsh
@@ -25,17 +25,22 @@
 # 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_CTYPE ]] && LC_CTYPE=C
-[[ -n $LC_COLLATE ]] && LC_COLLATE=C
-[[ -n $LC_NUMERIC ]] && LC_NUMERIC=C
-[[ -n $LC_MESSAGES ]] && LC_MESSAGES=C
-[[ -n $LANG ]] && LANG=C
-# Test file may (or may not) set LANG to other locales. In either case,
-# LANG must be passed to child zsh.
-export LANG
+# By default tests are run in C locale. LANG must be passed to child zsh.
+unset -m LC_\*
+export LANG=C
+
+# find UTF-8 locale
+ZTST_find_UTF8 () {
+  setopt multibyte
+  local langs=(en_{US,GB}.{UTF-,utf}8 en.UTF-8
+               ${(M)$(locale -a 2>/dev/null):#*.(utf8|UTF-8)})
+  for LANG in $langs; do
+    if [[ é = ? ]]; then
+      echo $LANG
+      return
+    fi
+  done
+}
 
 # Don't propagate variables that are set by default in the shell.
 typeset +x WORDCHARS
@@ -321,6 +326,7 @@ ZTST_diff() {
   emulate -L zsh
   setopt extendedglob
 
+  local -a diff_arg
   local diff_out
   integer diff_pat diff_ret
 
@@ -337,6 +343,7 @@ ZTST_diff() {
     ;;
   esac
   shift
+  [[ $OSTYPE != solaris* ]] && diff_arg=( -a )
       
   if (( diff_pat )); then
     local -a diff_lines1 diff_lines2
@@ -377,7 +384,7 @@ ZTST_diff() {
       diff_ret=1
     fi
   else
-    diff_out=$(diff -a "$@")
+    diff_out=$(diff $diff_arg "$@")
     diff_ret="$?"
     if [[ "$diff_ret" != "0" ]]; then
       print -r -- "$diff_out"
diff --git a/Util/check-tmux-state b/Util/check-tmux-state
index 2c6106203..9772eefc1 100644..100755
--- a/Util/check-tmux-state
+++ b/Util/check-tmux-state
@@ -59,7 +59,7 @@ __tmux-window-options
 # in the _tmux function definition file.
 typeset -a supported_commands
 supported_commands=( $( grep '^_tmux-[^(]*() *{$' $func |
-                        sed -e 's,^.*\<_tmux-,,' -e 's,(.*$,,' ) )
+                        sed -e 's,^_tmux[-]\([a-z-]*\)[(].*,\1,' ) )
 
 # Ask tmux for available commands:
 typeset -a available_commands
@@ -74,18 +74,18 @@ available_aliases=( $( $tmux list-commands |
 # Gather information about options:
 typeset -a supported_session_options
 supported_session_options=( ${"${tmux_session_options[@]}"%%:*} )
-typeset -a available_session_options
-available_session_options=( $( $tmux show-options -g | cut -f1 -d' ' ) )
+typeset -aU available_session_options
+available_session_options=( ${${${(f)"$($tmux show-options -g)"}:#@*}%%(\[<->\])# *} )
 
-typeset -a available_server_options
-supported_server_options=( ${"${tmux_server_options[@]}"%%:*} )
 typeset -a supported_server_options
-available_server_options=( $( $tmux show-options -s -g | cut -f1 -d' ' ) )
+supported_server_options=( ${"${tmux_server_options[@]}"%%:*} )
+typeset -aU available_server_options
+available_server_options=( ${${${(f)"$($tmux show-options -s -g)"}:#@*}%%(\[<->\])# *} )
 
 typeset -a supported_window_options
 supported_window_options=( ${"${tmux_window_options[@]}"%%:*} )
-typeset -a available_window_options
-available_window_options=( $( $tmux show-options -w -g | cut -f1 -d' ' ) )
+typeset -aU available_window_options
+available_window_options=( ${${${(f)"$($tmux show-options -w -g)"}:#@*}%%(\[<->\])# *} )
 
 typeset -a supported available
 
diff --git a/Util/printdefines b/Util/printdefines
new file mode 100644
index 000000000..c127ad586
--- /dev/null
+++ b/Util/printdefines
@@ -0,0 +1,634 @@
+#!/bin/zsh -f
+emulate -L zsh -o extendedglob
+
+zmodload zsh/param/private
+
+local -AHPrt jobstats=(
+ mapbase 16
+ $((0x0001)) STAT_CHANGED	# status changed and not reported
+ $((0x0002)) STAT_STOPPED	# all procs stopped or exited
+ $((0x0004)) STAT_TIMED		# job is being timed
+ $((0x0008)) STAT_DONE		# job is done
+ $((0x0010)) STAT_LOCKED	# shell is finished creating this job,
+                         	#   may be deleted from job table
+ $((0x0020)) STAT_NOPRINT	# job was killed internally,
+                         	#   we don't want to show that
+ $((0x0040)) STAT_INUSE		# this job entry is in use
+ $((0x0080)) STAT_SUPERJOB	# job has a subjob
+ $((0x0100)) STAT_SUBJOB	# job is a subjob
+ $((0x0200)) STAT_WASSUPER	# was a super-job, sub-job needs to be
+				# deleted
+ $((0x0400)) STAT_CURSH		# last command is in current shell
+ $((0x0800)) STAT_NOSTTY	# the tty settings are not inherited
+				# from this job when it exits.
+ $((0x1000)) STAT_ATTACH	# delay reattaching shell to tty
+ $((0x2000)) STAT_SUBLEADER	# is super-job, but leader is sub-shell
+
+ $((0x4000)) STAT_BUILTIN	# job at tail of pipeline is a builtin
+ $((0x8000)) STAT_SUBJOB_ORPHANED
+                        	# STAT_SUBJOB with STAT_SUPERJOB exited
+ $((0x10000)) STAT_DISOWN	# STAT_SUPERJOB with disown pending
+
+#-1 SP_RUNNING			# fake status for jobs currently running
+)
+local -AHPrt paramflags=(
+ mapbase 2
+ 0		PM_SCALAR	# scalar
+ $((1<<0))	PM_ARRAY	# array
+ $((1<<1))	PM_INTEGER	# integer
+ $((1<<2))	PM_EFLOAT	# double with %e output
+ $((1<<3))	PM_FFLOAT	# double with %f output
+ $((1<<4))	PM_HASHED	# association
+
+ $((1<<5))	PM_LEFT		# left justify, remove leading blanks
+ $((1<<6))	PM_RIGHT_B	# right justify, fill with leading blanks
+ $((1<<7))	PM_RIGHT_Z	# right justify, fill with leading zeros
+ $((1<<8))	PM_LOWER	# all lower case
+
+ $((1<<9))	PM_UPPER	# all upper case
+# $((1<<9))	PM_UNDEFINED	# undefined (autoloaded) shell function
+
+ $((1<<10))	PM_READONLY	# readonly
+ $((1<<11))	PM_TAGGED	# tagged
+ $((1<<12))	PM_EXPORTED	# exported
+# $((1<<12))	PM_ABSPATH_USED	# (function): loaded using absolute path
+
+ $((1<<13))	PM_UNIQUE	# remove duplicates
+# $((1<<13))	PM_SELFREF	# Overload when namerefs resolved
+# $((1<<13))	PM_UNALIASED	# (function) do not expand aliases
+
+ $((1<<14))	PM_HIDE		# Special behaviour hidden by local
+# $((1<<14))	PM_CUR_FPATH	# (function): can use $fpath with filename
+ $((1<<15))	PM_HIDEVAL	# Value not shown in `typeset' commands
+# $((1<<15))	PM_WARNNESTED	# (function): non-recursive WARNNESTEDVAR
+ $((1<<16))	PM_TIED		# array tied to colon-path or v.v.
+# $((1<<16))	PM_TAGGED_LOCAL	# (function): non-recursive PM_TAGGED
+
+# Remaining flags do not correspond directly to command line switches
+ $((1<<17))	PM_DONTIMPORT_SUID	# do not import if running setuid
+# $((1<<17))	PM_LOADDIR	# (function) filename gives load directory
+ $((1<<18))	PM_SINGLE	# special can only have a single instance
+# $((1<<18))	PM_NEWREF	# Overload in for-loop namerefs
+# $((1<<18))	PM_ANONYMOUS	# (function) anonymous function
+ $((1<<19))	PM_LOCAL	# this parameter will be made local
+# $((1<<19))	PM_KSHSTORED	# (function) stored in ksh form
+ $((1<<20))	PM_SPECIAL	# special builtin parameter
+# $((1<<20))	PM_ZSHSTORED	# (function) stored in zsh form
+ $((1<<21))	PM_RO_BY_DESIGN	# specials that can be made read-only by user
+##$(((1<<20)|(1<<10)|(1<<21))) PM_READONLY_SPECIAL
+# $((1<<22))	PM_DONTIMPORT	# do not import this variable
+ $((1<<22))	PM_DECLARED	# explicitly named with typeset
+ $((1<<23))	PM_RESTRICTED	# cannot be changed in restricted mode
+ $((1<<24))	PM_UNSET	# has null value
+##$(((1<<22)|(1<<24))) PM_DEFAULTED
+ $((1<<25))	PM_REMOVABLE	# special can be removed from paramtab
+ $((1<<26))	PM_AUTOLOAD	# autoloaded from module
+ $((1<<27))	PM_NORESTORE	# do not restore value of local special
+# $((1<<27))	PM_AUTOALL	# autoload all features in module
+ $((1<<28))	PM_HASHELEM	# is a hash-element
+ $((1<<29))	PM_NAMEDDIR	# has a corresponding nameddirtab entry
+ $((1<<30))	PM_NAMEREF	# pointer to a different parameter
+)
+local -AHPrt chartokens=(
+ mapbase 16
+ $((0x83))	Meta
+ $((0x84))	Pound
+ $((0x85))	String
+ $((0x86))	Hat
+ $((0x87))	Star
+ $((0x88))	Inpar
+ $((0x89))	Inparmath
+ $((0x8a))	Outpar
+ $((0x8b))	Outparmath
+ $((0x8c))	Qstring
+ $((0x8d))	Equals
+ $((0x8e))	Bar
+ $((0x8f))	Inbrace
+ $((0x90))	Outbrace
+ $((0x91))	Inbrack
+ $((0x92))	Outbrack
+ $((0x93))	Tick
+ $((0x94))	Inang
+ $((0x95))	Outang
+ $((0x96))	OutangProc
+ $((0x97))	Quest
+ $((0x98))	Tilde
+ $((0x99))	Qtick
+ $((0x9a))	Comma
+ $((0x9b))	Dash	# Only in patterns
+ $((0x9c))	Bang	# Only in patterns
+ $((0x9d))	Snull
+ $((0x9e))	Dnull
+ $((0x9f))	Bnull
+ $((0xa0))	Bnullkeep
+ $((0xa1))	Nularg
+ $((0xa2))	Marker
+)
+local -AHPrt fdtabletype=(
+ mapbase integer
+ $((0))		FDT_UNUSED
+ $((1))		FDT_INTERNAL
+ $((2))		FDT_EXTERNAL
+ $((3))		FDT_MODULE
+ $((4))		FDT_XTRACE
+ $((5))		FDT_FLOCK
+ $((6))		FDT_FLOCK_EXEC
+ $((7))		FDT_PROC_SUBST
+#$((16))	FDT_SAVED_MASK
+)
+local -AHPrt inputstates=(
+ mapbase 2
+ $((1<<0))	INP_FREE
+ $((1<<1))	INP_ALIAS
+ $((1<<2))	INP_HIST
+ $((1<<3))	INP_CONT
+ $((1<<4))	INP_ALCONT
+ $((1<<5))	INP_HISTCONT
+ $((1<<6))	INP_LINENO
+ $((1<<7))	INP_APPEND
+ $((1<<8))	INP_RAW_KEEP
+)
+local -AHPrt metafytypes=(
+ mapbase integer
+ $((0))	META_REALLOC
+ $((1))	META_USEHEAP
+ $((2))	META_STATIC
+ $((3))	META_DUP
+ $((4))	META_ALLOC
+ $((5))	META_NOALLOC
+ $((6))	META_HEAPDUP
+ $((7))	META_HREALLOC
+)
+local -AHPrt jobtypes=(
+ mapbase 2
+ $((1<<0))	Z_TIMED		# pipeline is being timed
+ $((1<<1))	Z_SYNC		# run this sublist synchronously       (;)
+ $((1<<2))	Z_ASYNC		# run this sublist asynchronously      (&)
+ $((1<<3))	Z_DISOWN	# run this sublist without job control (&|)
+ $((1<<4))	Z_END
+ $((1<<5))	Z_SIMPLE
+)
+local -AHPrt condtypes=(
+ mapbase integer
+ $((0))		COND_NOT
+ $((1))		COND_AND
+ $((2))		COND_OR
+ $((3))		COND_STREQ
+ $((4))		COND_STRDEQ
+ $((5))		COND_STRNEQ
+ $((6))		COND_STRLT
+ $((7))		COND_STRGTR
+ $((8))		COND_NT
+ $((9))		COND_OT
+ $((10))	COND_EF
+ $((11))	COND_EQ
+ $((12))	COND_NE
+ $((13))	COND_LT
+ $((14))	COND_GT
+ $((15))	COND_LE
+ $((16))	COND_GE
+ $((17))	COND_REGEX
+ $((18))	COND_MOD
+ $((19))	COND_MODI
+)
+local -AHPrt wordcodes=(
+ mapbase integer
+ $((0))		WC_END
+ $((1))		WC_LIST
+ $((2))		WC_SUBLIST
+ $((3))		WC_PIPE
+ $((4))		WC_REDIR
+ $((5))		WC_ASSIGN
+#$((5))		WC_SUBLIST_FREE
+ $((6))		WC_SIMPLE
+#$((6))		WC_LIST_FREE
+ $((7))		WC_TYPESET
+ $((8))		WC_SUBSH
+ $((9))		WC_CURSH
+ $((10))	WC_TIMED
+ $((11))	WC_FUNCDEF
+ $((12))	WC_FOR
+ $((13))	WC_SELECT
+ $((14))	WC_WHILE
+ $((15))	WC_REPEAT
+ $((16))	WC_CASE
+ $((17))	WC_IF
+ $((18))	WC_COND
+ $((19))	WC_ARITH
+ $((20))	WC_AUTOFN
+ $((21))	WC_TRY
+ $((22))	WC_COUNT
+)
+local -AHPrt wcsublists=(
+ mapbase 10
+ $((0))		WC_SUBLIST_END
+ $((1))		WC_SUBLIST_AND
+ $((2))		WC_SUBLIST_OR
+ $((4))		WC_SUBLIST_COPROC
+ $((8))		WC_SUBLIST_NOT
+ $((16))	WC_SUBLIST_SIMPLE
+)
+local -AHPrt eprogstates=(
+ mapbase 10
+ $((1))	EF_REAL
+ $((2))	EF_HEAP
+ $((4))	EF_MAP
+ $((8))	EF_RUN
+)
+local -AHPrt builtintypes=(
+ mapbase 2
+ $((1<<1))	BINF_PLUSOPTS	# +xyz legal
+ $((1<<2))	BINF_PRINTOPTS
+ $((1<<3))	BINF_ADDED	# is in the builtins hash table
+ $((1<<4))	BINF_MAGICEQUALS
+ $((1<<5))	BINF_PREFIX
+ $((1<<6))	BINF_DASH
+ $((1<<7))	BINF_BUILTIN
+ $((1<<8))	BINF_COMMAND
+ $((1<<9))	BINF_EXEC
+ $((1<<10))	BINF_NOGLOB
+ $((1<<11))	BINF_PSPECIAL
+ $((1<<12))	BINF_SKIPINVALID	# Treat invalid option as argument
+ $((1<<13))	BINF_KEEPNUM	# `[-+]NUM' can be an option
+ $((1<<14))	BINF_SKIPDASH	# Treat `-' as argument (maybe `+')
+ $((1<<15))	BINF_DASHDASHVALID	# Handle `--' even if SKIPINVALD
+ $((1<<16))	BINF_CLEARENV	# new process started with cleared env
+ $((1<<17))	BINF_AUTOALL	# autoload all features at once
+ $((1<<18))	BINF_HANDLES_OPTS
+ $((1<<19))	BINF_ASSIGN
+)
+local -AHPrt patflags=(
+ mapbase 16
+ $((0x0000))	PAT_HEAPDUP	# Dummy flag for default behavior
+ $((0x0001))	PAT_FILE	# Pattern is a file name
+ $((0x0002))	PAT_FILET	# Pattern is top level file, affects ~
+ $((0x0004))	PAT_ANY	# Match anything (cheap "*")
+ $((0x0008))	PAT_NOANCH	# Not anchored at end
+ $((0x0010))	PAT_NOGLD	# Don't glob dots
+ $((0x0020))	PAT_PURES	# Pattern is a pure string: set internally
+ $((0x0040))	PAT_STATIC	# Don't copy pattern to heap as per default
+ $((0x0080))	PAT_SCAN	# Scanning, so don't try must-match test
+ $((0x0100))	PAT_ZDUP	# Copy pattern in real memory
+ $((0x0200))	PAT_NOTSTART	# Start of string is not real start
+ $((0x0400))	PAT_NOTEND	# End of string is not real end
+ $((0x0800))	PAT_HAS_EXCLUDP	# (internal): top-level path1~path2.
+ $((0x1000))	PAT_LCMATCHUC	# equivalent to setting (#l)
+)
+local -AHPrt patclasses=(
+ mapbase integer
+ $((1))		PP_FIRST
+ $((1))		PP_ALPHA
+ $((2))		PP_ALNUM
+ $((3))		PP_ASCII
+ $((4))		PP_BLANK
+ $((5))		PP_CNTRL
+ $((6))		PP_DIGIT
+ $((7))		PP_GRAPH
+ $((8))		PP_LOWER
+ $((9))		PP_PRINT
+ $((10))	PP_PUNCT
+ $((11))	PP_SPACE
+ $((12))	PP_UPPER
+ $((13))	PP_XDIGIT
+ $((14))	PP_IDENT
+ $((15))	PP_IFS
+ $((16))	PP_IFSSPACE
+ $((17))	PP_WORD
+ $((18))	PP_INCOMPLETE
+ $((19))	PP_INVALID
+ $((19))	PP_LAST
+ $((20))	PP_UNKWN
+ $((21))	PP_RANGE
+)
+local -AHPrt globmodifiers=(
+ mapbase 16
+ $((0x0100))	GF_LCMATCHUC
+ $((0x0200))	GF_IGNCASE
+ $((0x0400))	GF_BACKREF
+ $((0x0800))	GF_MATCHREF
+ $((0x1000))	GF_MULTIBYTE	# Use multibyte if supported by build
+)
+local -AHPrt scanparamflags=(
+ mapbase 2
+ $((1<<0))	SCANPM_WANTVALS	# Return value includes hash values
+ $((1<<1))	SCANPM_WANTKEYS	# Return value includes hash keys
+ $((1<<2))	SCANPM_WANTINDEX # Return value includes array index
+ $((1<<3))	SCANPM_MATCHKEY	# Subscript matched against key
+ $((1<<4))	SCANPM_MATCHVAL	# Subscript matched against value
+ $((1<<5))	SCANPM_MATCHMANY # Subscript matched repeatedly, return all
+ $((1<<6))	SCANPM_ASSIGNING # Assigning whole array/hash
+ $((1<<7))	SCANPM_KEYMATCH	# keys of hash treated as patterns
+ $((1<<8))	SCANPM_DQUOTED	# substitution was double-quoted
+ $((1<<9))	SCANPM_ARRONLY	# value is array but we don't
+ $((1<<10))	SCANPM_CHECKING	# Check if set, no need to create
+ $((1<<11))	SCANPM_NOEXEC	# No command substitutions, etc.
+ $((1<<12))	SCANPM_NONAMESPC # namespace syntax not allowed
+ $((1<<13))	SCANPM_NONAMEREF # named references are not followed
+)
+local -AHPrt substmodifiers=(
+ mapbase 16
+ $((0x0001))	SUB_END	# match end instead of beginning, % or %%
+ $((0x0002))	SUB_LONG	# % or # doubled, get longest match
+ $((0x0004))	SUB_SUBSTR	# match a substring
+ $((0x0008))	SUB_MATCH	# include the matched portion
+ $((0x0010))	SUB_REST	# include the unmatched portion
+ $((0x0020))	SUB_BIND	# index of beginning of string
+ $((0x0040))	SUB_EIND	# index of end of string
+ $((0x0080))	SUB_LEN		# length of match
+ $((0x0100))	SUB_ALL		# match complete string
+ $((0x0200))	SUB_GLOBAL	# global substitution ${..//all/these}
+ $((0x0400))	SUB_DOSUBST	# replacement string needs substituting
+ $((0x0800))	SUB_RETFAIL	# return status 0 if no match
+ $((0x1000))	SUB_START	# force match at start with SUB_END
+ $((0x2000))	SUB_LIST	# no substitution, return list of matches
+ $((0x4000))	SUB_EGLOB	# use extended globbing in patterns
+)
+local -AHPrt printparamflags=(
+ mapbase 2
+ $((1<<0))	PRINT_NAMEONLY
+ $((1<<1))	PRINT_TYPE
+ $((1<<2))	PRINT_LIST
+ $((1<<3))	PRINT_KV_PAIR
+ $((1<<4))	PRINT_INCLUDEVALUE
+ $((1<<5))	PRINT_TYPESET
+ $((1<<6))	PRINT_LINE
+ $((1<<7))	PRINT_POSIX_EXPORT
+ $((1<<8))	PRINT_POSIX_READONLY
+ $((1<<9))	PRINT_WITH_NAMESPACE
+)
+local -AHPrt printwhenceflags=(
+ $((1<<7))	PRINT_WHENCE_CSH
+ $((1<<8))	PRINT_WHENCE_VERBOSE
+ $((1<<9))	PRINT_WHENCE_SIMPLE
+#$((1<<9))	PRINT_WITH_NAMESPACE
+ $((1<<10))	PRINT_WHENCE_FUNCDEF
+ $((1<<11))	PRINT_WHENCE_WORD
+)
+local -AHPrt savehistflags=(
+ mapbase 16
+ $((0x00000001))	HIST_MAKEUNIQUE	# Kill this new entry if not unique
+ $((0x00000002))	HIST_OLD	# Command is already written to disk
+ $((0x00000004))	HIST_READ	# Command was read back from disk
+ $((0x00000008))	HIST_DUP	# Command duplicates a later line
+ $((0x00000010))	HIST_FOREIGN	# Command came from another shell
+ $((0x00000020))	HIST_TMPSTORE	# Kill when user enters another cmd
+ $((0x00000040))	HIST_NOWRITE	# Keep internally but don't write
+)
+local -AHPrt histflags=(
+ mapbase 10
+ $((1))	HISTFLAG_DONE
+ $((2))	HISTFLAG_NOEXEC
+ $((4))	HISTFLAG_RECALL
+ $((8))	HISTFLAG_SETTY
+)
+local -AHPrt histfileflags=(
+ mapbase 16
+ $((0x0001))	HFILE_APPEND
+ $((0x0002))	HFILE_SKIPOLD
+ $((0x0004))	HFILE_SKIPDUPS
+ $((0x0008))	HFILE_SKIPFOREIGN
+ $((0x0010))	HFILE_FAST
+ $((0x0020))	HFILE_NO_REWRITE
+ $((0x8000))	HFILE_USE_OPTIONS
+)
+local -AHPrt modloadflags=(
+ mapbase 2
+ $((1<<0))	MOD_BUSY
+ $((1<<1))	MOD_UNLOAD
+ $((1<<2))	MOD_SETUP
+ $((1<<3))	MOD_LINKED
+ $((1<<4))	MOD_INIT_S
+ $((1<<5))	MOD_INIT_B
+ $((1<<6))	MOD_ALIAS
+)
+local -AHPrt modcondflags=(
+ mapbase 10
+ $((1))	CONDF_INFIX
+ $((2))	CONDF_ADDED
+ $((4))	CONDF_AUTOALL
+)
+local -AHPrt mathfunctypes=(
+ mapbase 10
+ $((1))	MFF_STR
+ $((2))	MFF_ADDED
+ $((4))	MFF_USERFUNC
+ $((8))	MFF_AUTOALL
+)
+local -AHPrt lexflags=(
+ mapbase 16
+ $((0x0001))	LEXFLAGS_ACTIVE
+ $((0x0002))	LEXFLAGS_ZLE
+ $((0x0004))	LEXFLAGS_COMMENTS_KEEP
+ $((0x0008))	LEXFLAGS_COMMENTS_STRIP
+ $((0x0010))	LEXFLAGS_NEWLINE
+)
+local -AHPrt lexstates=(
+ mapbase integer
+ $((0))	IN_NOTHING
+ $((1))	IN_CMD
+ $((2))	IN_MATH
+ $((3))	IN_COND
+ $((4))	IN_ENV
+ $((5))	IN_PAR
+)
+local -AHPrt emulations=(
+ mapbase 2
+ $((1<<1))	EMULATE_CSH	# C shell
+ $((1<<2))	EMULATE_KSH	# Korn shell
+ $((1<<3))	EMULATE_SH	# Bourne shell
+ $((1<<4))	EMULATE_ZSH	# `native' mode
+)
+local -AHPrt terminaltypes=(
+ mapbase 16
+ $((0x01))	TERM_BAD	# terminal has extremely basic capabilities
+ $((0x02))	TERM_UNKNOWN	# unknown terminal type
+ $((0x04))	TERM_NOUP	# terminal has no up capability
+ $((0x08))	TERM_SHORT	# terminal is < 3 lines high
+ $((0x10))	TERM_NARROW	# terminal is < 3 columns wide
+)
+local -AHPrt termcapacts=(
+ mapbase integer
+ $((0))		TCCLEARSCREEN
+ $((1))		TCLEFT
+ $((2))		TCMULTLEFT
+ $((3))		TCRIGHT
+ $((4))		TCMULTRIGHT
+ $((5))		TCUP
+ $((6))		TCMULTUP
+ $((7))		TCDOWN
+ $((8))		TCMULTDOWN
+ $((9))		TCDEL
+ $((10))	TCMULTDEL
+ $((11))	TCINS
+ $((12))	TCMULTINS
+ $((13))	TCCLEAREOD
+ $((14))	TCCLEAREOL
+ $((15))	TCINSLINE
+ $((16))	TCDELLINE
+ $((17))	TCNEXTTAB
+ $((18))	TCBOLDFACEBEG
+ $((19))	TCFAINTBEG
+ $((20))	TCSTANDOUTBEG
+ $((21))	TCUNDERLINEBEG
+ $((22))	TCITALICSBEG
+ $((23))	TCALLATTRSOFF
+ $((24))	TCSTANDOUTEND
+ $((25))	TCUNDERLINEEND
+ $((26))	TCITALICSEND
+ $((27))	TCHORIZPOS
+ $((28))	TCUPCURSOR
+ $((29))	TCDOWNCURSOR
+ $((30))	TCLEFTCURSOR
+ $((31))	TCRIGHTCURSOR
+ $((32))	TCSAVECURSOR
+ $((33))	TCRESTRCURSOR
+ $((34))	TCBACKSPACE
+ $((35))	TCFGCOLOUR
+ $((36))	TCBGCOLOUR
+)
+local -AHPrt cmdstackstates=(
+ mapbase integer
+ $((0))		CS_FOR
+ $((1))		CS_WHILE
+ $((2))		CS_REPEAT
+ $((3))		CS_SELECT
+ $((4))		CS_UNTIL
+ $((5))		CS_IF
+ $((6))		CS_IFTHEN
+ $((7))		CS_ELSE
+ $((8))		CS_ELIF
+ $((9))		CS_MATH
+ $((10))	CS_COND
+ $((11))	CS_CMDOR
+ $((12))	CS_CMDAND
+ $((13))	CS_PIPE
+ $((14))	CS_ERRPIPE
+ $((15))	CS_FOREACH
+ $((16))	CS_CASE
+ $((17))	CS_FUNCDEF
+ $((18))	CS_SUBSH
+ $((19))	CS_CURSH
+ $((20))	CS_ARRAY
+ $((21))	CS_QUOTE
+ $((22))	CS_DQUOTE
+ $((23))	CS_BQUOTE
+ $((24))	CS_CMDSUBST
+ $((25))	CS_MATHSUBST
+ $((26))	CS_ELIFTHEN
+ $((27))	CS_HEREDOC
+ $((28))	CS_HEREDOCD
+ $((29))	CS_BRACE
+ $((30))	CS_BRACEPAR
+ $((31))	CS_ALWAYS
+ $((32))	CS_COUNT
+)
+
+zmodload zsh/parameter
+local seek=${parameters[paramflags]}
+
+if [[ $1 = (|-)-h(|elp) ]]
+then
+  print -u2 Usage:
+  print -u2 "  printdefines [ category ] [ name | value ]"
+  shift
+fi
+
+if [[ -z $1 ]]
+then
+  print -u2 "Choose category:"
+  print -u2 -aC3 -- ${(ok)parameters[(R)$seek]}
+  return 1
+fi
+
+local -a outflag
+
+if [[ -z $parameters[$1] || $parameters[$1] != $seek ]]
+then
+  local -n scan
+  for scan in ${(k)parameters[(R)$seek]}
+  do
+    if [[ -n ${scan[(R)$1]} ]]
+    then
+      local -a hits
+      set -A hits ${${(nk)scan[(R)$~1]}:#mapbase}
+      integer -i ${scan[mapbase]/integer/10} w=${hits[-1]}
+      integer x=${#${scan[mapbase]/integer/}}+2
+      while (($#hits))
+      do
+	if [[ $scan[mapbase] = 2 ]]
+	then
+	  w=${hits[1]}
+	  local +i flag  
+	  if (( w ))
+	  then
+	    printf -v flag '1<<%d\t%s' $((${#w} - x))  $hits[1]
+	  else
+	    printf -v flag '0<<0\t%s' $hits[1]
+	  fi
+	else
+	  integer -i ${scan[mapbase]/integer/10} -Z ${#w} flag=${hits[1]}
+	fi
+	outflag+=($scan[$hits[1]] $flag )
+        shift hits
+      done
+      local +n scan	# ${!scan}
+      print -aC2 -- "--- $scan" --- $outflag
+      local -n scan
+      outflag=()
+    fi
+  done
+  return 0
+fi
+
+local -n ref=$1
+
+if [[ $2 = <-> ]]
+then
+  integer i=$2
+  integer flag
+  if [[ $ref[mapbase] = integer ]]
+  then
+    if (( (i -= ${${ref[$2]:+$2}:-0}) == 0 ))
+    then
+      outflag=($ref[$2])
+    fi
+  else
+    for flag in ${${(nk)ref}:#mapbase}
+    do
+      if (( i == flag || flag > 0 && (i & flag) == flag ))
+      then
+        # print $i $flag
+        outflag+=(${ref[$flag]})
+        (( i -= flag ))
+      fi
+    done
+  fi
+  print $2 ${(j:|:)outflag}
+  if (( i ))
+  then
+    print Unknown $1: $i
+  fi
+else
+  set -- ${${(nk)ref[(R)${~2:-*}]}:#mapbase}
+  integer -i ${ref[mapbase]/integer/10} w=${argv[-1]}
+  integer x=${#${ref[mapbase]/integer/}}+2
+  while ((ARGC))
+  do
+    if [[ $ref[mapbase] = 2 ]]
+    then
+      integer -i 2 w=$1
+      local +i flag
+      if (( w ))
+      then
+	printf -v flag '1<<%d\t%s' $((${#w} - x)) $1
+      else
+	printf -v flag '0<<0\t%s' $1
+      fi
+    else
+      integer -i ${ref[mapbase]/integer/10} -Z ${#w} flag=$1
+    fi
+    outflag+=($ref[$1] $flag )
+    shift
+  done
+  print -aC2 -- $outflag
+fi
diff --git a/Util/ztst-syntax.vim b/Util/ztst-syntax.vim
index 639b9a4ec..42378e7a1 100644
--- a/Util/ztst-syntax.vim
+++ b/Util/ztst-syntax.vim
@@ -36,7 +36,7 @@ syn match  ztstPayload             /^\s.*/ contains=@zsh
 syn match  ztstExitCode            /^\d\+\|^-/                nextgroup=ztstFlags
 syn match  ztstFlags               /[.dDqf]*:/      contained nextgroup=ztstTestName contains=ztstColon
 syn match  ztstColon               /:.\@=/          contained
-syn region ztstTestName            start=// end=/$/ contained 
+syn region ztstTestName            start=// end=/$/ contained contains=@Spell
 
 syn match  ztstInputMarker         /^<.\@=/                   nextgroup=ztstInput
 syn region ztstInput               start=// end=/$/ contained
@@ -54,7 +54,7 @@ syn match  ztstErrputLiteral       /^[?].\@=/                 nextgroup=ztstErrp
 syn region ztstErrput              start=// end=/$/ contained
 
 syn match  ztstFrequentExplanationMarker /^F:/                nextgroup=ztstFrequentExplanation
-syn region ztstFrequentExplanation start=// end=/$/ contained
+syn region ztstFrequentExplanation start=// end=/$/ contained contains=@Spell
 
 syn match  ztstDirective           /^%.*/
 
diff --git a/aclocal.m4 b/aclocal.m4
index c26e2d834..792d533f2 100644
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -2,56 +2,6 @@
 # Copyright (C) 1992, 1994 Free Software Foundation, Inc.
 # Francois Pinard <pinard@iro.umontreal.ca>, 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_COMPILE_IFELSE([AC_LANG_PROGRAM([
-[#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,
diff --git a/aczsh.m4 b/aczsh.m4
index 1209ac614..b31236020 100644
--- a/aczsh.m4
+++ b/aczsh.m4
@@ -44,6 +44,7 @@ AC_DEFUN(zsh_64_BIT_TYPE,
 #include <sys/types.h>
 #endif
 
+int
 main()
 {
   $1 foo = 0; 
@@ -118,7 +119,6 @@ AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS
 AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&AS_MESSAGE_LOG_FD) &&
 AC_TRY_COMMAND($DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&AS_MESSAGE_LOG_FD); then
     AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -146,29 +146,30 @@ char *zsh_gl_sym_addr ;
 #define RTLD_GLOBAL 0
 #endif
 
+int
 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);
+    if(!handle1) return(1);
     handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle2) exit(1);
+    if(!handle2) return(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);
+    if(!sym1 || !sym2) return(1);
+    if(sym1 != sym2) return(1);
     dlclose(handle1);
     handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle1) exit(1);
+    if(!handle1) return(1);
     zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1");
     sym1 = zsh_getaddr1();
-    if(!sym1) exit(1);
-    if(sym1 != sym2) exit(1);
-    exit(0);
+    if(!sym1) return(1);
+    if(sym1 != sym2) return(1);
+    return(0);
 }
 ]])],[zsh_cv_shared_$1=yes],
 [zsh_cv_shared_$1=no],
@@ -200,7 +201,6 @@ AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS
 AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&AS_MESSAGE_LOG_FD) &&
 AC_TRY_COMMAND($DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&AS_MESSAGE_LOG_FD); then
     AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -228,19 +228,19 @@ char *zsh_gl_sym_addr ;
 #define RTLD_GLOBAL 0
 #endif
 
-
+int
 main()
 {
     void *handle1, *handle2;
     int (*fred1)(), (*fred2)();
     handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle1) exit(1);
+    if(!handle1) return(1);
     handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle2) exit(1);
+    if(!handle2) return(1);
     fred1 = (int (*)()) dlsym(handle1, "${us}fred");
     fred2 = (int (*)()) dlsym(handle2, "${us}fred");
-    if(!fred1 || !fred2) exit(1);
-    exit((*fred1)() != 42 || (*fred2)() != 69);
+    if(!fred1 || !fred2) return(1);
+    return((*fred1)() != 42 || (*fred2)() != 69);
 }
 ]])],[zsh_cv_sys_dynamic_clash_ok=yes],
 [zsh_cv_sys_dynamic_clash_ok=no],
@@ -276,7 +276,6 @@ AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS
 AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&AS_MESSAGE_LOG_FD) &&
 AC_TRY_COMMAND($DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&AS_MESSAGE_LOG_FD); then
     AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -304,17 +303,18 @@ char *zsh_gl_sym_addr ;
 #define RTLD_GLOBAL 0
 #endif
 
+int
 main()
 {
     void *handle;
     int (*barneysym)();
     handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle) exit(1);
+    if(!handle) return(1);
     handle = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle) exit(1);
+    if(!handle) return(1);
     barneysym = (int (*)()) dlsym(handle, "${us}barney");
-    if(!barneysym) exit(1);
-    exit((*barneysym)() != 69);
+    if(!barneysym) return(1);
+    return((*barneysym)() != 69);
 }
 ]])],[zsh_cv_sys_dynamic_rtld_global=yes],
 [zsh_cv_sys_dynamic_rtld_global=no],
@@ -346,7 +346,6 @@ AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS
     save_ldflags=$LDFLAGS
     LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS"
     AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -374,15 +373,16 @@ char *zsh_gl_sym_addr ;
 #define RTLD_GLOBAL 0
 #endif
 
+int
 main()
 {
     void *handle;
     int (*barneysym)();
     handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle) exit(1);
+    if(!handle) return(1);
     barneysym = (int (*)()) dlsym(handle, "${us}barney");
-    if(!barneysym) exit(1);
-    exit((*barneysym)() != 69);
+    if(!barneysym) return(1);
+    return((*barneysym)() != 69);
 }
 
 int fred () { return 42; }
@@ -420,7 +420,6 @@ elif
     save_ldflags=$LDFLAGS
     LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS -s"
     AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -448,15 +447,16 @@ char *zsh_gl_sym_addr ;
 #define RTLD_GLOBAL 0
 #endif
 
+int
 main()
 {
     void *handle;
     int (*barneysym)();
     handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle) exit(1);
+    if(!handle) return(1);
     barneysym = (int (*)()) dlsym(handle, "${us}barney");
-    if(!barneysym) exit(1);
-    exit((*barneysym)() != 69);
+    if(!barneysym) return(1);
+    return((*barneysym)() != 69);
 }
 
 int fred () { return 42; }
@@ -488,7 +488,6 @@ echo 'int fred () { return 42; }' > conftest1.c
 if AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AS_MESSAGE_LOG_FD) &&
 AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS -s conftest1.o $LIBS 1>&AS_MESSAGE_LOG_FD); then
     AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -516,15 +515,16 @@ char *zsh_gl_sym_addr ;
 #define RTLD_GLOBAL 0
 #endif
 
+int
 main()
 {
     void *handle;
     int (*fredsym)();
     handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL);
-    if(!handle) exit(1);
+    if(!handle) return(1);
     fredsym = (int (*)()) dlsym(handle, "${us}fred");
-    if(!fredsym) exit(1);
-    exit((*fredsym)() != 42);
+    if(!fredsym) return(1);
+    return((*fredsym)() != 42);
 }
 ]])],[zsh_cv_sys_dynamic_strip_lib=yes],
 [zsh_cv_sys_dynamic_strip_lib=no],
diff --git a/configure.ac b/configure.ac
index 77e381f50..78621042d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -273,11 +273,6 @@ 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]),
@@ -438,7 +433,18 @@ fi],
 
 dnl Do you want to look for pcre support?
 AC_ARG_ENABLE(pcre,
-AS_HELP_STRING([--enable-pcre],[enable the search for the pcre library (may create run-time library dependencies)]))
+AS_HELP_STRING([--enable-pcre],[enable the search for the pcre2 library (may create run-time library dependencies)]))
+
+AC_ARG_VAR(PCRE_CONFIG, [pathname of pcre2-config if it is not in PATH])
+if test "x$enable_pcre" = xyes; then
+  AC_CHECK_PROG([PCRE_CONFIG], pcre2-config, pcre2-config)
+  if test "x$PCRE_CONFIG" = x; then
+    enable_pcre=no
+    AC_MSG_WARN([pcre2-config not found: pcre module is disabled.])
+    AC_MSG_NOTICE(
+      [Set PCRE_CONFIG to pathname of pcre2-config if it is not in PATH.])
+  fi
+fi
 
 dnl Do you want to look for capability support?
 AC_ARG_ENABLE(cap,
@@ -472,7 +478,7 @@ 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 -n "$auto_cflags"; then
   if test "${enable_zsh_debug}" = yes; then
     if test -n "$GCC"; then
       CFLAGS="$CFLAGS -Wall -Wmissing-prototypes -ggdb"
@@ -546,30 +552,6 @@ 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
@@ -582,16 +564,6 @@ 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,
@@ -633,7 +605,12 @@ fi
 
 if test x"$TEXI2HTML" = xtexi2any; then
   TEXI2HTML='texi2any -c TEXI2HTML=1'
+  case `texi2any --version 2>/dev/null | sed -e 's/^.*) *//' -e 1q` in
+    [[1-6]].*) SET_TEXI2ANY_VAR=set_from_init_file ;;
+    *) SET_TEXI2ANY_VAR=texinfo_set_from_init_file ;;
+  esac
 fi
+AC_SUBST(SET_TEXI2ANY_VAR)
 
 case "$LC_PAPER" in
   ??_US*) PAPERSIZE=us ;;
@@ -641,18 +618,6 @@ case "$LC_PAPER" in
 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 ------------------
@@ -660,16 +625,12 @@ AC_HEADER_DIRENT
 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 pcre2-config --cflags may produce 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
+if test "x$enable_pcre" = xyes; then
+  CPPFLAGS="`$PCRE_CONFIG --cflags` $CPPFLAGS"
+  AC_CHECK_HEADERS([pcre2.h],,,[#define PCRE2_CODE_UNIT_WIDTH 8])
 fi
 
 AC_CHECK_HEADERS(sys/time.h sys/times.h sys/select.h termcap.h termio.h \
@@ -678,7 +639,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
@@ -957,12 +918,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 ---------------------
@@ -1046,7 +1001,7 @@ else
   [AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #include <sys/types.h>
 
-main() { return sizeof(off_t) < 8; }
+int 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)
@@ -1056,7 +1011,7 @@ main() { return sizeof(off_t) < 8; }
   [AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #include <sys/types.h>
 
-main() { return sizeof(ino_t) < 8; }
+int 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)
@@ -1299,10 +1254,11 @@ AC_CHECK_FUNCS(strftime strptime mktime timelocal \
 	       select poll \
 	       readlink faccessx fchdir ftruncate \
 	       fstat lstat lchown fchown fchmod \
-	       fseeko ftello \
+	       fpurge fseeko ftello \
 	       mkfifo _mktemp mkstemp \
 	       waitpid wait3 \
 	       sigaction sigblock sighold sigrelse sigsetmask sigprocmask \
+	       sigqueue \
 	       killpg setpgid setpgrp tcsetpgrp tcgetattr nice \
 	       gethostname gethostbyname2 getipnodebyname \
 	       inet_aton inet_pton inet_ntop \
@@ -1323,7 +1279,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 \
@@ -1369,7 +1324,7 @@ zsh_cv_func_realpath_accepts_null,
 #include <stdlib.h>
 #include <limits.h>
 ],[
-exit(!realpath("/", (char*)0));
+return(!realpath("/", (char*)0));
 ])],
 [zsh_cv_func_realpath_accepts_null=yes],
 [zsh_cv_func_realpath_accepts_null=no],
@@ -1378,6 +1333,11 @@ if test x$zsh_cv_func_realpath_accepts_null = xyes; then
   AC_DEFINE(REALPATH_ACCEPTS_NULL)
 fi
 
+if test x$enable_pcre = xyes; then
+  LIBS="`$PCRE_CONFIG --libs8` $LIBS"
+  AC_CHECK_FUNCS(pcre2_compile_8)
+fi
+
 if test x$enable_cap = xyes; then
   AC_CHECK_FUNCS(cap_get_proc)
 fi
@@ -1393,10 +1353,9 @@ AC_CACHE_CHECK(if tgetent accepts NULL,
 zsh_cv_func_tgetent_accepts_null,
 [AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #include <fcntl.h>
-#include <stdlib.h>
 int tgetent(char *, char *);
 char *tgetstr(char *, char **);
-main()
+int main()
 {
     char buf[4096];
     int r1 = tgetent(buf, "vt100");
@@ -1407,7 +1366,7 @@ main()
     	tgetstr("cl", &u);
 	creat("conftest.tgetent", 0640);
     }
-    exit((r1 != r2) || r2 == -1);
+    return((r1 != r2) || r2 == -1);
 }
 ]])],[if test -f conftest.tgetent; then
     zsh_cv_func_tgetent_accepts_null=yes
@@ -1421,10 +1380,9 @@ AC_CACHE_CHECK(if tgetent returns 0 on success,
 zsh_cv_func_tgetent_zero_success,
 [AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #include <fcntl.h>
-#include <stdlib.h>
 int tgetent(char *, char*);
 char *tgetstr(char *, char **);
-main()
+int main()
 {
     char buf[4096];
     int r1 = tgetent(buf, "!@#$%^&*");
@@ -1435,7 +1393,7 @@ main()
     	tgetstr("cl", &u);
 	creat("conftest.tgetent0", 0640);
     }
-    exit(r1 == r2);
+    return(r1 == r2);
 }
 ]])],[if test -f conftest.tgetent0; then
     zsh_cv_func_tgetent_zero_success=yes
@@ -1515,6 +1473,14 @@ else
 zsh_cv_use_xattr=no
 fi])
 
+dnl We don't want to use setenv(3) on El Capitan or older OS X because it
+dnl removes a leading '=' from the value of the environment variable
+AH_TEMPLATE([SETENV_MANGLES_EQUAL],
+[Define to 1 if setenv removes a leading =])
+case $host_os in
+  darwin1[0-5]*) AC_DEFINE(SETENV_MANGLES_EQUAL) ;;
+esac
+
 dnl -------------
 dnl CHECK SIGNALS
 dnl -------------
@@ -1761,27 +1727,27 @@ if test x$zsh_cv_path_term_header != xnone; then
   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_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = (char **)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_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = (char **)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_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = (char **)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_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = (char **)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_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = (char **)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_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = (char **)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
@@ -1861,8 +1827,7 @@ zsh_cv_rlim_t_is_longer,
 #include <sys/time.h>
 #endif
 #include <sys/resource.h>
-#include <stdlib.h>
-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])])
+int main(){struct rlimit r;return(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,
@@ -1872,13 +1837,12 @@ if test x$zsh_cv_rlim_t_is_longer = xyes; then
 #endif
 #include <stdio.h>
 #include <sys/resource.h>
-#include <stdlib.h>
-main() { 
+int main() {
   struct rlimit r;
   char buf[20];
   r.rlim_cur = 0;
   sprintf(buf, "%qd", r.rlim_cur);
-  exit(strcmp(buf, "0"));
+  return(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)
@@ -1895,8 +1859,7 @@ else
 #include <sys/time.h>
 #endif
 #include <sys/resource.h>
-#include <stdlib.h>
-  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])])
+  int main(){struct rlimit r;r.rlim_cur=-1;return(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"
@@ -1972,6 +1935,15 @@ if test x$ac_cv_func_getrusage = xyes; then
 #endif
 #include <sys/resource.h>])
 fi
+dnl On some OSes (only macOS?) ru_maxrss is in bytes (not in kilobytes).
+dnl Solaris uses pages as the unit, but ru_maxrss is set to zero anyway.
+AH_TEMPLATE(RU_MAXRSS_IS_IN_BYTES,
+[Define to 1 if ru_maxrss in struct rusage is in bytes.])
+case "$host_os" in
+  darwin*)
+    AC_DEFINE(RU_MAXRSS_IS_IN_BYTES)
+  ;;
+esac
 
 
 dnl --------------------------------------------
@@ -2003,12 +1975,31 @@ 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,
 [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
+   (exec 3<&0; test -e $zsh_cv_sys_path_dev_fd/3;) && break
  done])
 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 SYMLINK TO THE CURRENT EXECUTABLE IN /proc
+dnl ----------------------------------------------------
+dnl Linux: /proc/self/exe
+dnl NetBSD: /proc/curproc/exe (or /proc/self/exe, but not /proc/curproc/file)
+dnl DragonFly: /proc/curproc/file
+dnl Solaris: /proc/self/path/a.out
+AH_TEMPLATE([PROC_SELF_EXE],
+[Define to the path of the symlink to the current executable file.])
+AC_CACHE_CHECK(for symlink to the current executable in /proc,
+zsh_cv_proc_self_exe,
+[for zsh_cv_proc_self_exe in /proc/self/exe /proc/curproc/exe \
+                             /proc/curproc/file /proc/self/path/a.out no; do
+   test -L $zsh_cv_proc_self_exe && break
+done])
+if test x$zsh_cv_proc_self_exe != xno; then
+  AC_DEFINE_UNQUOTED(PROC_SELF_EXE, "$zsh_cv_proc_self_exe")
+fi
+
 dnl ---------------------------------
 dnl CHECK FOR RFS SUPERROOT DIRECTORY
 dnl ---------------------------------
@@ -2179,9 +2170,8 @@ zsh_cv_sys_fifo,
 #include <fcntl.h>
 #include <signal.h>
 #include <unistd.h>
-#include <stdlib.h>
 #include <sys/stat.h>
-main()
+int main()
 {
     char c;
     int fd;
@@ -2192,18 +2182,18 @@ main()
 #else
     if(mknod("/tmp/fifo$$", 0010600, 0) < 0)
 #endif
-	exit(1);
+	return(1);
     pid = fork();
     if(pid < 0)
-	exit(1);
+	return(1);
     if(pid) {
 	fd = open("/tmp/fifo$$", O_RDONLY);
-	exit(fd < 0 || read(fd, &c, 1) != 1 || c != 'x');
+	return(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);
+    return(ret);
 }
 ]])],[zsh_cv_sys_fifo=yes],[zsh_cv_sys_fifo=no],[zsh_cv_sys_fifo=yes])
 ])
@@ -2281,8 +2271,7 @@ zsh_cv_sys_link,
 [AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #include <unistd.h>
 #include <fcntl.h>
-#include <stdlib.h>
-main()
+int main()
 {
     int ret;
     char *tmpfile, *newfile;
@@ -2291,11 +2280,11 @@ main()
     unlink(tmpfile);
     unlink(newfile);
     if(creat(tmpfile, 0644) < 0)
-	exit(1);
+	return(1);
     ret = link(tmpfile, newfile);
     unlink(tmpfile);
     unlink(newfile);
-    exit(ret<0);
+    return(ret<0);
 }
 ]])],[zsh_cv_sys_link=yes],[zsh_cv_sys_link=no],[zsh_cv_sys_link=yes])])
 AH_TEMPLATE([HAVE_LINK],
@@ -2314,12 +2303,11 @@ zsh_cv_sys_killesrch,
 #include <unistd.h>
 #include <signal.h>
 #include <errno.h>
-#include <stdlib.h>
-main()
+int main()
 {
     int pid = (getpid() + 10000) & 0xffffff;
     while (pid && (kill(pid, 0) == 0 || errno != ESRCH)) pid >>= 1;
-    exit(errno!=ESRCH);
+    return(errno!=ESRCH);
 }
 ]])],[zsh_cv_sys_killesrch=yes],[zsh_cv_sys_killesrch=no],[zsh_cv_sys_killesrch=yes])])
 AH_TEMPLATE([BROKEN_KILL_ESRCH],
@@ -2340,12 +2328,11 @@ if test x$signals_style = xPOSIX_SIGNALS; then
     [AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #include <signal.h>
 #include <unistd.h>
-#include <stdlib.h>
 int child=0;
 void handler(sig)
     int sig;
 {if(sig==SIGCHLD) child=1;}
-main() {
+int main() {
     struct sigaction act;
     sigset_t set;
     int pid, ret;
@@ -2360,7 +2347,7 @@ main() {
     if(pid>0) {
     sigemptyset(&set);
         ret=sigsuspend(&set);
-        exit(child==0);
+        return(child==0);
     }
 }
 ]])],[zsh_cv_sys_sigsuspend=yes],[zsh_cv_sys_sigsuspend=no],[zsh_cv_sys_sigsuspend=yes])])
@@ -2392,15 +2379,14 @@ case "x$zsh_working_tcsetpgrp" in
 #include <sys/types.h>
 #include <unistd.h>
 #include <fcntl.h>
-#include <stdlib.h>
-main() {
+int main() {
     int fd;
     int ret;
     fd=open("/dev/tty", O_RDWR);
-    if (fd < 0) exit(2);
+    if (fd < 0) return(2);
     ret=tcsetpgrp(fd, tcgetpgrp(fd));
-    if (ret < 0) exit(1);
-    exit(0);
+    if (ret < 0) return(1);
+    return(0);
 }
 ]])],[zsh_cv_sys_tcsetpgrp=yes],[
 case $? in
@@ -2440,7 +2426,7 @@ if test x$ac_cv_func_getpwnam = xyes; then
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>
-main() {
+int main() {
     struct passwd *pw1, *pw2;
     char buf[1024], name[1024];
     sprintf(buf, "%d:%d", getpid(), rand());
@@ -2448,7 +2434,7 @@ main() {
     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));
+    return(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
@@ -2767,20 +2753,17 @@ elif test "x$dynamic" = xyes; then
    zsh_cv_sys_elf,
    [AC_RUN_IFELSE([AC_LANG_SOURCE([[/* Test for whether ELF binaries are produced */
 #include <fcntl.h>
-#include <stdlib.h>
 #include <unistd.h>
-main(argc, argv)
-int argc;
-char *argv[];
+int main(int argc, char *argv[])
 {
 	char b[4];
 	int i = open(argv[0],O_RDONLY);
 	if(i == -1) 
-		exit(1); /* fail */
+		return(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) */
+		return(0); /* succeed (yes, it's ELF) */
 	else
-		exit(1); /* fail */
+		return(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
@@ -2916,13 +2899,12 @@ 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 <<EOM
-fred () { }
+void fred () { }
 EOM
     AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest.c 1>&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 <stdio.h>
-#include <stdlib.h>
 #ifdef HPUX10DYNAMIC
 #include <dl.h>
 #define RTLD_LAZY BIND_DEFERRED
@@ -2949,16 +2931,16 @@ char *zsh_gl_sym_addr ;
 
 extern int fred() ;
 
-main()
+int main()
 {
     void * handle ;
     void * symbol ;
     FILE *f=fopen("conftestval", "w");
-    if (!f) exit(1);
+    if (!f) return(1);
     handle = dlopen("./conftest.$DL_EXT", RTLD_LAZY) ;
     if (handle == NULL) {
         fprintf (f, "dlopen failed") ;
-            exit(1);
+            return(1);
     }
     symbol = dlsym(handle, "fred") ;
     if (symbol == NULL) {
@@ -2966,13 +2948,13 @@ main()
         symbol = dlsym(handle, "_fred") ;
         if (symbol == NULL) {
             fprintf (f, "dlsym failed") ;
-                exit(1);
+                return(1);
                 }
         fprintf (f, "yes") ;
     }
     else
         fprintf (f, "no") ;
-    exit(0);
+    return(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