markdown.scm 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. ;;; Copyright © 2018-2021 David Thompson <davet@gnu.org>
  2. ;;;
  3. ;;; This program is free software; you can redistribute it and/or
  4. ;;; modify it under the terms of the GNU General Public License as
  5. ;;; published by the Free Software Foundation; either version 3 of the
  6. ;;; License, or (at your option) any later version.
  7. ;;;
  8. ;;; This program is distributed in the hope that it will be useful,
  9. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. ;;; General Public License for more details.
  12. ;;;
  13. ;;; You should have received a copy of the GNU General Public License
  14. ;;; along with this program. If not, see
  15. ;;; <http://www.gnu.org/licenses/>.
  16. (define-module (markdown)
  17. #:use-module (commonmark)
  18. #:use-module (haunt post)
  19. #:use-module (haunt reader)
  20. #:use-module (highlight)
  21. #:use-module (sxml match)
  22. #:use-module (sxml transform)
  23. #:export (commonmark-reader*))
  24. (define (sxml-identity . args) args)
  25. ;; Markdown doesn't support video, so let's hack around that! Find
  26. ;; <img> tags with a ".webm" source and substitute a <video> tag.
  27. (define (media-hackery . tree)
  28. (sxml-match tree
  29. ((img (@ (src ,src) . ,attrs) . ,body)
  30. (if (string-suffix? ".webm" src)
  31. `(video (@ (src ,src) (controls "true"),@attrs) ,@body)
  32. tree))))
  33. (define %commonmark-rules
  34. `((code . ,highlight-code)
  35. (img . ,media-hackery)
  36. (*text* . ,(lambda (tag str) str))
  37. (*default* . ,sxml-identity)))
  38. (define (post-process-commonmark sxml)
  39. (pre-post-order sxml %commonmark-rules))
  40. (define commonmark-reader*
  41. (make-reader (make-file-extension-matcher "md")
  42. (lambda (file)
  43. (call-with-input-file file
  44. (lambda (port)
  45. (values (read-metadata-headers port)
  46. (post-process-commonmark
  47. (commonmark->sxml port))))))))