Syntax Highlighting For Python Docstrings in Neovim Treesitter

982 Views Asked by At

I'm using Treesitter with Neovim v0.8.2 and Python. With a default configuration of those 3, python docstrings are highlighted as strings, and I'd like to highlight them as comments.

I've tried creating a ~/.config/nvim/after/syntax/python.vim file with

syn region Comment start=/"""/ end=/"""/

and I expected """<things here>""" to be highlighted as comments.

I'm guessing this is because treesitter is disabling syntax highlighting, so on that note has anyone been able to add custom highlighting rules to Treesitter or after it?

1

There are 1 best solutions below

1
On BEST ANSWER

checkout https://github.com/nvim-treesitter/nvim-treesitter/issues/4392

it's quite the read, but you can override how treesitter parses the objects in the document/buffer, can't take credit for the below solution, but should get you where you need to be.

after/queries/python/highlights.scm
 extends

; Module docstring
(module . (expression_statement (string) @comment))

; Class docstring
(class_definition
  body: (block . (expression_statement (string) @comment)))

; Function/method docstring
(function_definition
  body: (block . (expression_statement (string) @comment)))

; Attribute docstring
((expression_statement (assignment)) . (expression_statement (string) @comment))