解决oh-my-zsh下zsh-syntax-highlighting插件报错的问题

在安装完成oh-my-zsh,并在~/.zshrc配置文件里设置了zsh-syntax-highlighting后,下一步就是执行source ~/.zshrc,以使用插件配置生效。

这时候有可能会报错,内容如下图:

这个问题困扰我很长时间,今天终于解决了。

答案就写在官方的github说明里:

1
2
3
4
5
6
7
**Why must be sourced at the end of the file?**

zsh-syntax-highlighting works by hooking into the Zsh Line Editor (ZLE) and computing syntax highlighting for the command-line buffer as it stands at the time z-sy-h's hook is invoked.

In zsh 5.2 and older, hooks into ZLE by wrapping ZLE widgets. It must be sourced after all custom widgets have been created (i.e., after all calls and after running ) in order to be able to wrap all of them. Widgets created after z-sy-h is sourced will work, but will not update the syntax highlighting.zsh-syntax-highlighting.zshzle -Ncompinit

In zsh newer than 5.8 (not including 5.8 itself), zsh-syntax-highlighting uses the facility to install a hook. Hooks are run in order of registration, therefore, z-sy-h must be sourced (and register its hook) after anything else that adds hooks that modify the command-line buffer.add-zle-hook-widgetzle-line-pre-redraw

简单来说,就是zsh-syntax-highlighting这个插件,必须放在~/.zshrc配置文件的启用插件列表

plugins=(git .... zsh-syntax-highlighting)

的最后面。

也就是说无论你在plugins里启用了多少个插件,zsh-syntax-highlighting必须是最后一个被启用的。

再执行source ~/.zshrc就不会报错了。