Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get syntax highlighting for cgo (golang)

cgo is written in "comments" in go which means by default it's given comment syntax highlighting. It would be nice have proper golang and C syntax highlighting but within cgo files.

package main

// ... C code or #include here ...
import "C"

... Go code here ...

Example

I'd like this for either Visual Studio Code, or ViM.

How can this be achieved?

like image 881
Graham Avatar asked Oct 17 '22 08:10

Graham


2 Answers

One way is to place the C code in a header file, for instance example.h, then in your Go program use:

// #include "example.h"
import "C"

When opening example.h, you get syntax highlighting.

Alternatively, for ViM, the SyntaxRange plugin can supposedly highlight C code that is part of Go code, but it may not be straightforward to configure.

like image 51
Alexander Avatar answered Oct 31 '22 17:10

Alexander


I woul say that, depending on your editor this is somewhere between impossible, and pointlessly difficult.

The only way you can tell the difference between a normal comment block and one used by cgo, is that the cgo block is immediately followed by import "C". Depending on how the syntax highlighting lexer for your editor is constructed it may or may not be able to detect this.

A possible partial solution would be to write a simplified subset of the C highlighter that only effects obvious code, then apply that to all comment blocks. Not a very good solution, but better than nothing.

Good luck!

like image 30
Milo Christiansen Avatar answered Oct 31 '22 15:10

Milo Christiansen