Anurag Kumar Singh
Anurag Kumar Singh

Reputation: 11

How to enable Treesitter syntax highlighting in a Telescope previewer buffer

I am creating a plugin which creates a custom Telescope picker and it has a json preview buffer. I want that buffer to be nicely syntax highlighted using treesitter but its not working. I added following line but it introduces very minimal highight.

This is the code snippet for telescope picker

local function pick_board(json_data)
  local opts = {}
  pickers
      .new(opts, {
        prompt_title = "Boards",
        finder = finders.new_table({
          results = json_data,
          entry_maker = opts.entry_maker or boardentry_maker(opts),
        }),
        attach_mappings = function(prompt_bufnr, _)
          actions.select_default:replace(function()
            actions.close(prompt_bufnr)
            local selection = action_state.get_selected_entry()
            pick_framework(selection["value"]["data"])
          end)
          return true
        end,
        previewer = previewers.new_buffer_previewer({
          title = "Board Info",
          define_preview = function(self, entry, _)
            local json = utils.strsplit(vim.inspect(entry["value"]["data"]), "\n")
            local bufnr = self.state.bufnr
            vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json)
            vim.defer_fn(function()
              vim.api.nvim_buf_set_option(bufnr, 'wrap', true)
              vim.api.nvim_buf_set_option(bufnr, 'linebreak', true)
              vim.api.nvim_buf_set_option(bufnr, 'wrapmargin', 2)
              vim.treesitter.start(bufnr, 'json') -- This added minimal highlight
            end, 0)
          end,
        }),
        sorter = conf.generic_sorter(opts),
      })
      :find()
end

I have specifically added this line

vim.treesitter.start(bufnr, 'json')

The result

You can see following comparison with and without that line Comparison

Treesitter can do way more syntax highlighting when you just open a json file like you can see here

wanted result

What changes should I make in code to make the json preview like that

Upvotes: 1

Views: 207

Answers (0)

Related Questions