'Highlight C/C++ function declarations and function calls differently in Vim
I am used to the way Sublime Text highlights function declarations vs function calls and am trying to emulate something similar with Vim. There are posts addressing something like this, but they seem to highlight declarations and calls the same way.
int function1() {
function3();
}
int function2()
{
...
}
Here, function1 and function2 should be of one color and function3 should be of another color. I am trying to write regular expressions to match each of these cases and then going from there.
So far, I came up with
syn match cFunDecl "\zs\w\+\ze(.*){"
syn match cFunCall "\zs\w\+\ze(.*);"
These don't really seem to work. Following this approach, I also expect to run into issues with header files where declarations are highlighted as calls but will probably deal with that later.
Solution 1:[1]
This is possible with Neovim and nvim-treesitter. I will note, it's probably also possible with LSP plugins such as vim-lsp-cxx-highlight, but I've found those to be a nightmare to work with.
First of all, you want to create a fork of nvim-treesitter. The reason is that, currently, function calls and declarations are highlighted the same in the c module. That's really easy to change, though. In your fork, go to queries/c/highlights.scm. Lower in the file you should see something like this:
(function_declarator
declarator: (identifier) @function)
That @function bit specifies the colour to use. If you replace it with something else, you can get different highlighting. You can find the list of available captures in CONTRIBUTING.md. For example, I just used @number, so I changed the above code to look like this:
(function_declarator
declarator: (identifier) @number)
Then, you can just install nvim-treesitter from your fork as normal. For me, that meant:
- Adding this to my
~/.vimrc:Plug 'vladh/nvim-treesitter', {'do': ':TSUpdate'} lua <<EOF require'nvim-treesitter.configs'.setup { highlight = { enable = true }, } EOF :PlugInstall:TSInstall c cpp
If everything worked correctly, your function declarations should now be highlighted differently! I also really wanted this feature, and fortunately nvim-treesitter now seems to be stable enough to do this easily.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad-?tefan Harbuz |
