code-highlighting.rkt 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #lang racket
  2. (require pollen/unstable/pygments
  3. "utils/list-operations.rkt")
  4. (provide highlight-code-xexprs)
  5. ;; replaces (pre ([class "brush: lang"]) ....) with pygmentized code xexpr
  6. (define (highlight-code-xexprs list-of-xexprs)
  7. ;; define known languages
  8. (define KNOWN-LANGUAGES
  9. (list "python"
  10. "racket"
  11. "html"
  12. "css"
  13. "javascript"
  14. "erlang"
  15. "rust"
  16. "bash"
  17. "shell"
  18. "sh"))
  19. ;; check if it matches for a single language's match expression
  20. ;; if it mathces any language, return that language's name as a symbol
  21. (define (get-matching-language an-xexpr)
  22. (define (get-brush-language an-xexpr)
  23. (match an-xexpr
  24. [`(pre ([class ,brush-lang]) (code () ,code-text ...)) brush-lang]
  25. [_ #f]))
  26. (define (extract-lang-from-brush-lang brush-lang)
  27. (and brush-lang
  28. (list-ref (regexp-match #rx"brush: ([^ ]+)\\s*"
  29. brush-lang)
  30. 1)))
  31. (let* ([matched-lang (extract-lang-from-brush-lang (get-brush-language an-xexpr))]
  32. [in-known-languages (member matched-lang KNOWN-LANGUAGES)])
  33. (and in-known-languages (car in-known-languages))))
  34. (define (get-code-text-from-xexpr an-xexpr)
  35. (match an-xexpr
  36. [`(pre ([class ,brush-lang]) (code () ,code-text ...)) code-text]
  37. [_ ""]))
  38. ;; replace code in an xexpr with highlightable code
  39. ;; TODO: What happens if the code is in a lower level of the xexpr?
  40. (define (replace-code-in-single-xexpr an-xexpr)
  41. (let ([matching-language (get-matching-language an-xexpr)])
  42. (cond [matching-language (displayln (format "found code of language ~a" matching-language))
  43. (code-highlight matching-language
  44. (get-code-text-from-xexpr an-xexpr))]
  45. [else an-xexpr])))
  46. ;; apply the check to all xexpr
  47. (apply-filtered* get-matching-language
  48. replace-code-in-single-xexpr
  49. list-of-xexprs)
  50. #;(map replace-code-in-single-xexpr list-of-xexprs))
  51. (define (code-highlight language code)
  52. (let ([lines-of-code (string-join code "")])
  53. ;;(displayln (highlight language lines-of-code))
  54. (highlight language lines-of-code)))