highlight.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package highlight
  2. import (
  3. "path"
  4. "strings"
  5. "gogs.io/gogs/internal/conf"
  6. )
  7. var (
  8. // File name should ignore highlight.
  9. ignoreFileNames = map[string]bool{
  10. "license": true,
  11. "copying": true,
  12. }
  13. // File names that are representing highlight classes.
  14. highlightFileNames = map[string]bool{
  15. "cmakelists.txt": true,
  16. "dockerfile": true,
  17. "makefile": true,
  18. }
  19. // Extensions that are same as highlight classes.
  20. highlightExts = map[string]bool{
  21. ".arm": true,
  22. ".as": true,
  23. ".sh": true,
  24. ".cs": true,
  25. ".cpp": true,
  26. ".c": true,
  27. ".css": true,
  28. ".cmake": true,
  29. ".bat": true,
  30. ".dart": true,
  31. ".patch": true,
  32. ".elixir": true,
  33. ".erlang": true,
  34. ".go": true,
  35. ".html": true,
  36. ".xml": true,
  37. ".hs": true,
  38. ".ini": true,
  39. ".json": true,
  40. ".java": true,
  41. ".js": true,
  42. ".less": true,
  43. ".lua": true,
  44. ".php": true,
  45. ".py": true,
  46. ".rb": true,
  47. ".scss": true,
  48. ".sql": true,
  49. ".scala": true,
  50. ".swift": true,
  51. ".ts": true,
  52. ".vb": true,
  53. ".r": true,
  54. ".sas": true,
  55. ".tex": true,
  56. ".yaml": true,
  57. }
  58. // Extensions that are not same as highlight classes.
  59. highlightMapping = map[string]string{
  60. ".txt": "nohighlight",
  61. }
  62. )
  63. func NewContext() {
  64. keys := conf.File.Section("highlight.mapping").Keys()
  65. for i := range keys {
  66. highlightMapping[keys[i].Name()] = keys[i].Value()
  67. }
  68. }
  69. // FileNameToHighlightClass returns the best match for highlight class name
  70. // based on the rule of highlight.js.
  71. func FileNameToHighlightClass(fname string) string {
  72. fname = strings.ToLower(fname)
  73. if ignoreFileNames[fname] {
  74. return "nohighlight"
  75. }
  76. if highlightFileNames[fname] {
  77. return fname
  78. }
  79. ext := path.Ext(fname)
  80. if highlightExts[ext] {
  81. return ext[1:]
  82. }
  83. name, ok := highlightMapping[ext]
  84. if ok {
  85. return name
  86. }
  87. return ""
  88. }