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.

highlight.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. }