+(defun sixel-image-dims (sixel-image)
+ "Compute image width from SIXEL-IMAGE. Return pair (width . height)."
+ (let ((sixels (sixel-image-sixels sixel-image)))
+ (cons
+ (apply #'max (mapcar (lambda (row) (length row)) sixels))
+ (* 6 (length sixels)))))
+
+(defun sixel-image-to-xpm-values (sixel-image)
+ "Produce parameter values component of XPM representation of SIXEL-IMAGE."
+ (let* ((dims (sixel-image-dims sixel-image))
+ (colour-map (sixel-image-colour-map sixel-image))
+ (n-colours (1+ (length colour-map))))
+ (concat "\""
+ (number-to-string (car dims)) " "
+ (number-to-string (cdr dims)) " "
+ (number-to-string n-colours) " 2\"")))
+
+(defun sixel-image-to-xpm-colours (sixel-image)
+ "Produce colour definitions component of XPM representation of SIXEL-IMAGE."
+ (let ((colour-map (sixel-image-colour-map sixel-image)))
+ (concat
+ (string-join
+ (mapcar (lambda (colour)
+ (concat
+ "\""
+ (elt colour 0) " "
+ "c #"
+ (format "%02x%02x%02x"
+ (/ (* 255 (elt colour 1)) 100)
+ (/ (* 255 (elt colour 2)) 100)
+ (/ (* 255 (elt colour 3)) 100))
+ "\""))
+ colour-map)
+ ",\n")
+ ",\n"
+ "\"-- c #000000\"")))
+
+(defun sixel-image-to-xpm-pixels (sixel-image)
+ "Produce pixels component of XPM representation of SIXEL-IMAGE."
+ (concat
+ "\""
+ (string-join
+ (mapcar (lambda (sixel-row)
+ (string-join
+ (mapcar (lambda (i)
+ (string-join
+ (mapcar (lambda (sixel)
+ (let ((pixel (elt sixel i)))
+ (if pixel
+ pixel
+ "--")))
+ sixel-row)))
+ (number-sequence 0 5))
+ "\",\n\""))
+ (sixel-image-sixels sixel-image))
+ "\",\n\"")
+ "\""))
+
+(defun sixel-to-xpm (string)
+ "Return an XPM image representation of the SIXEL graphic encoded in STRING."
+ (let* ((param-string (sixel-get-params string))
+ (data-string (sixel-get-data string))
+ (sixel-image (sixel-pad-rows (sixel-process-data data-string))))
+ (if (string-prefix-p "\eP" string)
+ (concat
+ "/* XPM */"
+ "static char * pixmap[] = {"
+ (sixel-image-to-xpm-values sixel-image) ",\n"
+ (sixel-image-to-xpm-colours sixel-image) ",\n"
+ (sixel-image-to-xpm-pixels sixel-image) "};")
+ (error "Incorrecly formatted sixel string"))))
+
+(defun sixel-render-images-in-buffer ()
+ "Find and render any sixel images in the current buffer."
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward "\eP[[:ascii:]]*\e\\\\" nil t)
+ (let ((sixel-string (match-string 0))
+ (inhibit-read-only t))
+ (delete-region (match-beginning 0)
+ (match-end 0))
+ (insert-image
+ (create-image (sixel-to-xpm sixel-string) 'xpm t))
+ (insert "\n")))))
+
+(defgroup sixel nil
+ "Render sixel images."
+ :group 'multimedia)
+
+(define-minor-mode sixel-mode
+ "A minor mode which renders sixel graphics." nil "sixel" nil
+ (add-hook 'after-change-functions
+ (lambda (start end size)
+ (sixel-render-images-in-buffer)
+ (message "Render complete."))
+ nil t))
+
+;;; sixel.el ends here