Search code examples
neovimtreesitter

How to make nvim highlight SQL code in TypeScript files?


Example:

const user = await ctx.pool.one(sql.type(userSchema)`
  UPDATE users
  SET avatar = NULL
  WHERE id = ${currentUser.id}
  RETURNING *
`);

I'm trying to use treesitter injection to do it.

So I've written the following query:

(call_expression
    function: (call_expression
    function: (member_expression
      object: (identifier) @_obj (#eq? @_obj "sql")))
  (template_string) @injection.content 
  (#set! injection.language "sql"))

checked it using treesitter playground (btw, how to run a query inside nvim? Seems that :EditQuery does not exist in an editor, but :InspectTree exists), and placed it here ~/.config/nvim/after/queries/typescript/injections.scm.

But SQL code in typescript files still haven't highlighted. I tried to use (#set! injection.include-children), but it also doesn't work for me.

Treesitter has been installed correctly with the SQL parser. Setup:

require'nvim-treesitter.configs'.setup {
  -- A list of parser names, or "all" (the five listed parsers should always be installed)
  ensure_installed = { "c", "lua", "vim", "vimdoc", "query", "javascript", "typescript", "sql" },

  -- Install parsers synchronously (only applied to `ensure_installed`)
  sync_install = false,

  -- Automatically install missing parsers when entering buffer
  -- Recommendation: set to false if you don't have `tree-sitter` CLI installed locally
  auto_install = true,

  highlight = {
    enable = true,

    -- Setting this to true will run `:h syntax` and tree-sitter at the same time.
    -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
    -- Using this option may slow down your editor, and you may see some duplicate highlights.
    -- Instead of true it can also be a list of languages
    additional_vim_regex_highlighting = false,
  },
}

Solution

  • I've fixed it.

    First, I had to add injection.include-children:

    (call_expression
        function: (call_expression
        function: (member_expression
          object: (identifier) @_obj (#eq? @_obj "sql")))
      (template_string) @injection.content 
      (#set! injection.language "sql")
      (#set! injection.include-children))
    

    Secondly, I placed the file in the wrong place. Seems that the queries directory should be placed in one the following paths:

    :lua print(vim.inspect(vim.api.nvim_list_runtime_paths()))
    

    In my case, I just put queries directory inside ~/.config/nvim (before it was in ~/config/nvim/after).