highlight.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. "dockerfile": true,
  19. "makefile": true,
  20. }
  21. // Extensions that are same as highlight classes.
  22. highlightExts = map[string]bool{
  23. ".arm": true,
  24. ".as": true,
  25. ".sh": true,
  26. ".cs": true,
  27. ".cpp": true,
  28. ".c": true,
  29. ".css": true,
  30. ".cmake": true,
  31. ".bat": true,
  32. ".dart": true,
  33. ".patch": true,
  34. ".elixir": true,
  35. ".erlang": true,
  36. ".go": true,
  37. ".html": true,
  38. ".xml": true,
  39. ".hs": true,
  40. ".ini": true,
  41. ".json": true,
  42. ".java": true,
  43. ".js": true,
  44. ".less": true,
  45. ".lua": true,
  46. ".php": true,
  47. ".py": true,
  48. ".rb": true,
  49. ".scss": true,
  50. ".sql": true,
  51. ".scala": true,
  52. ".swift": true,
  53. ".ts": true,
  54. ".vb": true,
  55. }
  56. // Extensions that are not same as highlight classes.
  57. highlightMapping = map[string]string{
  58. ".txt": "nohighlight",
  59. }
  60. )
  61. func NewContext() {
  62. keys := setting.Cfg.Section("highlight.mapping").Keys()
  63. for i := range keys {
  64. highlightMapping[keys[i].Name()] = keys[i].Value()
  65. }
  66. }
  67. // FileNameToHighlightClass returns the best match for highlight class name
  68. // based on the rule of highlight.js.
  69. func FileNameToHighlightClass(fname string) string {
  70. fname = strings.ToLower(fname)
  71. if ignoreFileNames[fname] {
  72. return "nohighlight"
  73. }
  74. if highlightFileNames[fname] {
  75. return fname
  76. }
  77. ext := path.Ext(fname)
  78. if highlightExts[ext] {
  79. return ext[1:]
  80. }
  81. name, ok := highlightMapping[ext]
  82. if ok {
  83. return name
  84. }
  85. return ""
  86. }