Check if Treesitter is enabled in the current buffer

I’m trying to write a function that runs different code depending on whether Treesitter is actively highlighting the current buffer or not. Specifically, I want something like this that falls back to using synId if Treesitter is not enabled. I looked through the Treesitter documentation a bit, but couldn’t find anything like b:treesitter_enabled or vim.treesitter.is_enabled() that I could use to easily test this. A lot of the parsing-related functions that I looked at would automatically enable Treesitter if they were called while it was off, so I wouldn’t be able to just null-check the return values to get my answer.
Sorry if I’m missing something obvious, but is there a simple way to accomplish this? Thanks

Hello, maybe some of the commands you can find in :help nvim-treesitter-commands could give you the information you need. I think :TSModuleInfo has the information you want.

i am not sure it is over complex but
you can use a nvim_ treesitter template

it have on-attach function then you create a variable vim.b.treesitter_enable

nvim-treesitter/playground uses

  local buf = vim.api.nvim_get_current_buf()
  local highlighter = require "vim.treesitter.highlighter"
  if highlighter.active[buf] then
   -- treesitter highlighting is enabled
  end
1 Like

Thanks! I tried it and it works perfectly.
This is my updated code for getting the highlight groups at the cursor

function get_highlights_at_cursor()
    -- source: https://neovim.discourse.group/t/check-if-treesitter-is-enabled-in-the-current-buffer/902/4?u=srithon
    local buf = vim.api.nvim_get_current_buf()
    local highlighter = require "vim.treesitter.highlighter"
    if highlighter.active[buf] then
        -- treesitter highlighting is enabled
        vim.cmd [[TSHighlightCapturesUnderCursor]]
    else
        -- https://stackoverflow.com/questions/6696079/vimrc-causes-error-e10-should-be-followed-by-or
        -- https://stackoverflow.com/a/6696615
        -- you can't use line continuation inside of :execute, so instead we pass multiple arguments that will get concatenated into a single command
        vim.cmd([[echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<']],
            [[. synIDattr(synID(line("."),col("."),0),"name") . "> lo<"]],
            [[. synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"<CR>]])
    end
end