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.

105 lines
2.0 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. ".erl": {},
  35. ".go": {},
  36. ".html": {},
  37. ".xml": {},
  38. ".hs": {},
  39. ".ini": {},
  40. ".json": {},
  41. ".java": {},
  42. ".js": {},
  43. ".less": {},
  44. ".lua": {},
  45. ".php": {},
  46. ".py": {},
  47. ".rb": {},
  48. ".rs": {},
  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. ".escript": "erlang",
  62. ".ex": "elixir",
  63. ".exs": "elixir",
  64. }
  65. )
  66. // NewContext loads highlight map
  67. func NewContext() {
  68. keys := setting.Cfg.Section("highlight.mapping").Keys()
  69. for i := range keys {
  70. highlightMapping[keys[i].Name()] = keys[i].Value()
  71. }
  72. }
  73. // FileNameToHighlightClass returns the best match for highlight class name
  74. // based on the rule of highlight.js.
  75. func FileNameToHighlightClass(fname string) string {
  76. fname = strings.ToLower(fname)
  77. if ignoreFileNames[fname] {
  78. return "nohighlight"
  79. }
  80. if highlightFileNames[fname] {
  81. return fname
  82. }
  83. ext := path.Ext(fname)
  84. if _, ok := highlightExts[ext]; ok {
  85. return ext[1:]
  86. }
  87. name, ok := highlightMapping[ext]
  88. if ok {
  89. return name
  90. }
  91. return ""
  92. }