5

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?

Alexander
  • 9,737
  • 4
  • 53
  • 59
Graham
  • 13,165
  • 2
  • 16
  • 14
  • You can add cgo file extensions for syntax highlighting in your editor (vim, atom, vscode, etc). What is your editor? – jeevatkm Jul 20 '17 at 02:52
  • What editor are you using that has syntax highlighting for cgo? – Graham Jul 21 '17 at 14:41
  • I'm using atom it does provides syntax highlight for `.go`, `.c`, `.h`, etc. – jeevatkm Jul 21 '17 at 19:34
  • I'm look for _more_ than just `.go` highlighting i'm looking for `cgo` which is c written in comments inside a go file. Example: https://github.com/AlekSi/cgo-by-example/blob/master/main.go#L4 – Graham Jul 22 '17 at 19:46
  • I doubt, you will get one. Mostly syntax highlighter works using file extension in the editor. For `.go` ext it will treat it as go file. Good luck. – jeevatkm Jul 22 '17 at 20:44
  • GoLand (IntelliJ's Go IDE) supports syntax highlighting for cgo C preamble comments (se [here](https://i.imgur.com/ETmrOcn.png)), so, I mean it's not "impossible" like everyone is saying. However I would love it it were available in VSCode since that's what I use for writing go. – Nathan F. Jan 16 '20 at 00:15

2 Answers2

3

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.

Alexander
  • 9,737
  • 4
  • 53
  • 59
1

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!

Milo Christiansen
  • 3,204
  • 2
  • 23
  • 36