highlight.go 2.0 KB

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