Treesitter and LSP-support for zsh

· Nano Tips for Vim

#zsh #shell #lsp #treesitter

Some people prefer zsh over bash. However, using zsh has the problem that it has far less tooling-support: In contrast to bash, there is no Treesitter parser, no linter, and no LSP for zsh.

Even so, we can still get all that nice tools for zsh as well. Since bash and zsh are very similar, the language syntaxes are mostly identical, so most forms of syntax highlighting, linting, or intellisense that work in bash can in principle also work with zsh – we just have to force those tools to treat zsh files as bash files.

 1-- use bash-treesitter-parser for zsh
 2augroup("zshAsBash", {})
 3autocmd("BufWinEnter", {
 4	group = "zshAsBash",
 5	pattern = {"*.sh", "*.zsh"},
 6	command = "silent! set filetype=sh",
 9-- make bash-lsp work with zsh (nvim builtin-lsp)
11	-- on_attach = ...,
12	-- completion = ...,
13	filetypes = {"sh", "zsh", "bash"},

The goto-linter for shell scripts, shellcheck, can also be forced to work with zsh by passing the argument --shell=bash. (Since shellcheck is integrated in the bash-LSP, and a recent PR added --shell=bash as default option, there is no need to setup shellcheck in vim.)

# Update 2023-11-07

I managed to find a "cleaner" method, namely use vim's vim.filetype.add to tell vim to treat all zsh files as sh files:

 1-- make zsh files recognized as sh for bash-ls & treesitter
 2vim.filetype.add {
 3	extension = {
 4		zsh = "sh",
 5		sh = "sh", -- force sh-files with zsh-shebang to still get sh as filetype
 6	},
 7	filename = {
 8		[".zshrc"] = "sh",
 9		[".zshenv"] = "sh",
10	},