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

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