1 (in-package #:phos/gemtext)
7 (defclass title (element)
8 ((level :initarg :level)))
10 (defclass link (element)
11 ((url :initarg :url)))
13 (defclass item (element)
16 (defclass paragraph (element)
19 (defclass blockquote (element)
22 (defclass verbatim (element)
23 ((alt :initarg :alt)))
25 (defun make-link (url &optional text)
26 (make-instance 'link :url (quri:uri url)
30 "Parse a line into link."
31 (match (cl-ppcre:split "\\s+" s :limit 2)
32 ((list url) (make-instance 'link :url (quri:uri url)))
33 ((list url text) (make-instance 'link :url (quri:uri url)
38 (string-trim '(#\Space #\Tab) (subseq s n)))
40 (uiop:string-prefix-p prfx str)))
41 (cond ((prefix-p "###" s) (make-instance 'title :level 3
43 ((prefix-p "##" s) (make-instance 'title :level 2
45 ((prefix-p "#" s) (make-instance 'title :level 1
47 ((prefix-p "=>" s) (let ((s (strim s 2)))
48 (if (string-equal s "")
49 (make-instance 'paragraph :text "=>")
51 ((prefix-p "* " s) (make-instance 'item :text (strim s 1)))
52 ((prefix-p ">" s) (make-instance 'blockquote :text (strim s 1)))
53 (t (make-instance 'paragraph :text (strim s 0))))))
55 (defmacro markerp (line)
56 `(uiop:string-prefix-p "```" ,line))
59 "Parse gemtext from the stream IN."
61 for line = (read-line in nil)
66 (loop with label = (subseq line 3)
68 for line = (read-line in nil)
70 do (error "non-closed verbatim")
72 return (make-instance 'verbatim
74 :text (format nil "~{~A~%~^~}"
76 do (push line content))
80 (defun parse-string (str)
81 "Parse the string STR as gemtext."
82 (with-input-from-string (s str)
85 (defgeneric unparse (obj stream)
86 (:documentation "Print a textual representation of OBJ onto STREAM."))
88 (defmethod unparse ((l list) stream)
90 (unparse item stream)))
92 (defmethod unparse ((title title) stream)
93 (with-slots (text level) title
96 (format stream " ~a~%" text)))
98 (defmethod unparse ((link link) stream)
99 (with-slots (url text) link
100 (format stream "=> ~a ~a~%" url text)))
102 (defmethod unparse ((item item) stream)
103 (with-slots (text) item
104 (format stream "* ~a~%" text)))
106 (defmethod unparse ((p paragraph) stream)
108 (format stream "~a~%" text)))
110 (defmethod unparse ((v verbatim) stream)
111 (with-slots (alt text) v
112 (format stream "```~a~%~a```~%" alt text)))
114 (defmethod unparse ((b blockquote) stream)
116 (format stream "> ~a~%" text)))
118 (defgeneric line-eq (a b)
119 (:documentation "t if the lines A and B are equals.")
120 (:method-combination and))
122 (defmethod line-eq and ((a element) (b element))
125 (equal (slot-value a 'text)
126 (slot-value b 'text))))
128 (defmethod line-eq and ((a title) (b title))
129 (eq (slot-value a 'level)
130 (slot-value b 'level)))
132 (defmethod line-eq and ((a link) (b link))
133 (quri:uri-equal (slot-value a 'url)
134 (slot-value b 'url)))
136 (defmethod line-eq and ((a verbatim) (b verbatim))
137 (equal (slot-value a 'alt)
138 (slot-value b 'alt)))