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.

102 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. ".txt": "nohighlight",
  61. }
  62. )
  63. // NewContext loads highlight map
  64. func NewContext() {
  65. keys := setting.Cfg.Section("highlight.mapping").Keys()
  66. for i := range keys {
  67. highlightMapping[keys[i].Name()] = keys[i].Value()
  68. }
  69. }
  70. // FileNameToHighlightClass returns the best match for highlight class name
  71. // based on the rule of highlight.js.
  72. func FileNameToHighlightClass(fname string) string {
  73. fname = strings.ToLower(fname)
  74. if ignoreFileNames[fname] {
  75. return "nohighlight"
  76. }
  77. if highlightFileNames[fname] {
  78. return fname
  79. }
  80. ext := path.Ext(fname)
  81. if _, ok := highlightExts[ext]; ok {
  82. return ext[1:]
  83. }
  84. name, ok := highlightMapping[ext]
  85. if ok {
  86. return name
  87. }
  88. return ""
  89. }