How can I get syntax highlighting for cgo (golang)

huangapple go评论108阅读模式
英文:

How can I get syntax highlighting for cgo (golang)

问题

cgo是用Go语言中的“注释”编写的,这意味着默认情况下会给予注释语法高亮显示。希望能够正确地对golang和C语法进行高亮显示,但仅限于cgo文件。

我希望在Visual Studio Code或ViM中实现这个效果。

如何实现这个效果呢?

英文:

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?

答案1

得分: 3

一种方法是将C代码放在一个头文件中,例如example.h,然后在你的Go程序中使用:

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

打开example.h时,你会得到语法高亮显示。

另外,对于ViM,SyntaxRange插件可以据说可以高亮显示作为Go代码一部分的C代码,但配置可能不太直观。

英文:

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.

答案2

得分: 1

我会说,根据你的编辑器,这个问题可能是不可能的,或者说是毫无意义的困难。

你唯一能区分普通注释块和cgo注释块的方法是,cgo注释块后面紧跟着import "C"。根据你的编辑器的语法高亮分析器的构造方式,它可能能够检测到这一点,也可能不能。

一个可能的部分解决方案是编写一个简化的C语法高亮器的子集,只作用于明显的代码,然后将其应用于所有注释块。这不是一个很好的解决方案,但总比没有好。

祝你好运!

英文:

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!

huangapple
  • 本文由 发表于 2017年7月20日 10:27:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/45204048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定