github.com/xyproto/orbiton/v2@v2.65.12-0.20240516144430-e10a419274ec/test/commenthighlight_go (about)

     1  package main
     2  
     3  import (
     4      "image/color"
     5      "os"
     6      "log"
     7      "regexp"
     8  
     9      "github.com/fogleman/gg"
    10  )
    11  
    12  var (
    13      keywords   = `(\bfunc\b|\bif\b|\belse\b|\bfor\b|\breturn\b|\bstruct\b|\benum\b|\bmatch\b|\buse\b|\bmod\b|\bconst\b|\bpub\b)`
    14      strings    = `(".*?"|'.*?'|` + "`" + `.*?` + "`" + `)`
    15      comments   = `(//.*|/\*.*?\*/|#![.*\[]|#\s.*|\bpackage\b)`
    16      whitespace = `(\s+)`
    17  )
    18  
    19  var (
    20      colorKeyword    = color.RGBA{255, 0, 0, 255}
    21      colorString     = color.RGBA{0, 255, 0, 255}
    22      colorComment    = color.RGBA{0, 0, 255, 255}
    23      colorNormal     = color.RGBA{255, 255, 255, 255}
    24      colorWhitespace = color.RGBA{0, 0, 0, 0}
    25  )
    26  
    27  func main() {
    28      data, err := os.ReadFile("input.txt") // Replace with your source file
    29      if err != nil {
    30          log.Fatal(err)
    31      }
    32  
    33      content := string(data)
    34      dc := gg.NewContext(800, 1000)
    35      dc.SetRGB(0.15, 0.15, 0.15)
    36      dc.Clear()
    37  
    38      fontPath := "path/to/your/font.ttf"
    39      if err := dc.LoadFontFace(fontPath, 16); err != nil {
    40          log.Fatalf("Failed to load font: %v", err)
    41      }
    42  
    43      combinedRegex := regexp.MustCompile(keywords + "|" + strings + "|" + comments + "|" + whitespace)
    44      tokens := combinedRegex.FindAllStringSubmatch(content, -1)
    45  
    46      x, y := 10.0, 20.0
    47      for _, token := range tokens {
    48          // Determine the color
    49          var col color.RGBA
    50          switch {
    51          case token[1] != "": // keyword
    52              col = colorKeyword
    53          case token[2] != "": // string
    54              col = colorString
    55          case token[3] != "": // comment
    56              col = colorComment
    57          case token[4] != "": // whitespace
    58              col = colorWhitespace
    59          default:
    60              col = colorNormal
    61          }
    62  
    63          dc.SetColor(col)
    64          dc.DrawString(token[0], x, y)
    65          width, _ := dc.MeasureString(token[0])
    66          x += width
    67      }
    68  
    69      dc.SavePNG("output.png")
    70      log.Println("Image saved as output.png")
    71  }