How to get treesitter parser based on filetype if parser name differs?

I am trying to get my c# parser by using vim.treesitter.get_parser. I can do this fine if I use lang="c_sharp", but not if I set lang="cs".

It’s hard to figure out how to retrieve this mapping dynamically. When looking at the documentation it seems like it should be using filetype, and not parser name:

Lua module: vim.treesitter                               *lua-treesitter-core*


get_parser({bufnr}, {lang}, {opts})                             *get_parser()*
                Gets the parser for this bufnr / ft combination.

                If needed this will create the parser. Unconditionally attach
                the provided callback

                Parameters: 
                    {bufnr}  The buffer the parser should be tied to
                    {lang}   The filetype of this parser
                    {opts}   Options object to pass to the created language
                             tree

                Return: 
                    The parser

Especially when looking at the short description it is even more misguiding:

    parser = vim.treesitter.get_parser(bufnr, lang)

 `bufnr=0` can be used for current buffer. `lang` will default to 'filetype'.
Currently, the parser will be retained for the lifetime of a buffer but this
is subject to change. A plugin should keep a reference to the parser object as
long as it wants incremental updates.

as filetype refers to the actual file type, i. e. cs in my case.

It’s available in the filetype_to_parsername table in nvim-treesitter:

print(require("nvim-treesitter.parsers").filetype_to_parsername["cs"])
1 Like

Thanks. Sorry for the late reply, this post got hidden and I found a solution in the meantime.

Actually, a slightly different solution, as there seems to be a method in addition to the field you refer:

require("nvim-treesitter.parsers").ft_to_lang("cs")

Seen in action here: Adds generic mapping of filetype to ts parser name by MikaelElkiaer · Pull Request #89 · danymat/neogen · GitHub

1 Like