Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add C lexer #815

Merged
merged 1 commit into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lexers/c.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package lexers

import (
"regexp"

. "github.com/alecthomas/chroma/v2" // nolint
)

var (
cAnalyserIncludeRe = regexp.MustCompile(`(?m)^\s*#include [<"]`)
cAnalyserIfdefRe = regexp.MustCompile(`(?m)^\s*#ifn?def `)
)

// C lexer.
var C = Register(MustNewXMLLexer(
embedded,
"embedded/c.xml",
).SetConfig(
&Config{
Name: "C",
Aliases: []string{"c"},
Filenames: []string{"*.c", "*.h", "*.idc", "*.x[bp]m"},
MimeTypes: []string{"text/x-chdr", "text/x-csrc", "image/x-xbitmap", "image/x-xpixmap"},
EnsureNL: true,
Priority: 0.1,
},
).SetAnalyser(func(text string) float32 {
if cAnalyserIncludeRe.MatchString(text) {
return 0.1
}

if cAnalyserIfdefRe.MatchString(text) {
return 0.1
}

return 0
}))
44 changes: 44 additions & 0 deletions lexers/c_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package lexers_test

import (
"io/ioutil"
"testing"

"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/lexers"

"github.com/alecthomas/assert/v2"
)

func TestC_AnalyseText(t *testing.T) {
tests := map[string]struct {
Filepath string
Expected float32
}{
"include": {
Filepath: "testdata/c_include.c",
Expected: 0.1,
},
"ifdef": {
Filepath: "testdata/c_ifdef.c",
Expected: 0.1,
},
"ifndef": {
Filepath: "testdata/c_ifndef.c",
Expected: 0.1,
},
}

for name, test := range tests {
test := test
t.Run(name, func(t *testing.T) {
data, err := ioutil.ReadFile(test.Filepath)
assert.NoError(t, err)

analyser, ok := lexers.C.(chroma.Analyser)
assert.True(t, ok)

assert.Equal(t, test.Expected, analyser.AnalyseText(string(data)))
})
}
}
2 changes: 2 additions & 0 deletions lexers/testdata/c_ifdef.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

#ifdef DEBUG
2 changes: 2 additions & 0 deletions lexers/testdata/c_ifndef.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

#ifndef DEBUG
2 changes: 2 additions & 0 deletions lexers/testdata/c_include.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

#include <stdio.h>