Skip to content

Commit

Permalink
Add C lexer (#815)
Browse files Browse the repository at this point in the history
  • Loading branch information
gandarez authored Aug 18, 2023
1 parent 49b5f8e commit de3a9c2
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 0 deletions.
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>

0 comments on commit de3a9c2

Please sign in to comment.