You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
1.9 KiB

  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. "code.gitea.io/gitea/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]struct{}{
  23. ".arm": {},
  24. ".as": {},
  25. ".sh": {},
  26. ".cs": {},
  27. ".cpp": {},
  28. ".c": {},
  29. ".css": {},
  30. ".cmake": {},
  31. ".bat": {},
  32. ".dart": {},
  33. ".patch": {},
  34. ".elixir": {},
  35. ".erlang": {},
  36. ".go": {},
  37. ".html": {},
  38. ".xml": {},
  39. ".hs": {},
  40. ".ini": {},
  41. ".json": {},
  42. ".java": {},
  43. ".js": {},
  44. ".less": {},
  45. ".lua": {},
  46. ".php": {},
  47. ".py": {},
  48. ".rb": {},
  49. ".scss": {},
  50. ".sql": {},
  51. ".scala": {},
  52. ".swift": {},
  53. ".ts": {},
  54. ".vb": {},
  55. ".yml": {},
  56. ".yaml": {},
  57. }
  58. // Extensions that are not same as highlight classes.
  59. highlightMapping = map[string]string{}
  60. )
  61. // NewContext loads highlight map
  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 _, ok := highlightExts[ext]; ok {
  80. return ext[1:]
  81. }
  82. name, ok := highlightMapping[ext]
  83. if ok {
  84. return name
  85. }
  86. return ""
  87. }