highlight.go 1.9 KB

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