Skip to content

Instantly share code, notes, and snippets.

@joaotavora
Last active December 26, 2015 20:39
Show Gist options
  • Save joaotavora/7210718 to your computer and use it in GitHub Desktop.
Save joaotavora/7210718 to your computer and use it in GitHub Desktop.
cl-discount, basic CL interface to libmarkdown/discount
(ql:quickload :cffi)
;;; Nothing special about the "CFFI-USER" package. We're just
;;; using it as a substitute for your own CL package.
(defpackage :cl-discount
(:use :common-lisp :cffi)
(:nicknames :discount)
(:export #:markdown
#:markdown-to-file))
(in-package :cl-discount)
(define-foreign-library discount
(:unix (:or "libmarkdown.so.2.1.3" "libmarkdown.so.2" "libmarkdown.so"))
(t (:default "libmarkdown")))
(use-foreign-library discount)
(defun markdown-to-file (string pathname)
(let ((fptr (foreign-funcall "fopen"
:string (namestring pathname)
:string "w+"
:pointer))
(doc (foreign-funcall "mkd_string"
:string string
:int (length string)
:int 0
:pointer)))
(foreign-funcall "markdown"
:pointer doc
:pointer fptr
:int 0
:int)
(foreign-funcall "fclose"
:pointer fptr
:int)
(foreign-funcall "mkd_cleanup" :pointer doc :void)))
(defun markdown (string)
(with-foreign-object (text-ptr :pointer)
(let* ((doc (foreign-funcall "mkd_string"
:string string
:int (length string)
:int 0
:pointer))
(compiled? (foreign-funcall "mkd_compile"
:pointer doc
:int 0
:pointer))
(len (foreign-funcall "mkd_document"
:pointer doc
:pointer text-ptr
:int)))
(declare (ignore compiled?))
(prog1 (foreign-string-to-lisp (mem-ref text-ptr :pointer)
:count len)
(foreign-funcall "mkd_cleanup" :pointer doc :void)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment