highlight.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "github.com/gogits/gogs/modules/setting"
  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. }
  57. // Extensions that are not same as highlight classes.
  58. highlightMapping = map[string]string{
  59. ".txt": "nohighlight",
  60. }
  61. )
  62. func NewContext() {
  63. keys := setting.Cfg.Section("highlight.mapping").Keys()
  64. for i := range keys {
  65. highlightMapping[keys[i].Name()] = keys[i].Value()
  66. }
  67. }
  68. // FileNameToHighlightClass returns the best match for highlight class name
  69. // based on the rule of highlight.js.
  70. func FileNameToHighlightClass(fname string) string {
  71. fname = strings.ToLower(fname)
  72. if ignoreFileNames[fname] {
  73. return "nohighlight"
  74. }
  75. if highlightFileNames[fname] {
  76. return fname
  77. }
  78. ext := path.Ext(fname)
  79. if highlightExts[ext] {
  80. return ext[1:]
  81. }
  82. name, ok := highlightMapping[ext]
  83. if ok {
  84. return name
  85. }
  86. return ""
  87. }