ob-gnuplot.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. ;;; ob-gnuplot.el --- Babel Functions for Gnuplot -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Maintainer: Ihor Radchenko <yantar92@gmail.com>
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: https://orgmode.org
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Org-Babel support for evaluating gnuplot source code.
  20. ;;
  21. ;; This differs from most standard languages in that
  22. ;;
  23. ;; 1) we are generally only going to return results of type "file"
  24. ;;
  25. ;; 2) we are adding the "file" and "cmdline" header arguments
  26. ;;; Requirements:
  27. ;; - gnuplot :: https://www.gnuplot.info/
  28. ;;
  29. ;; - gnuplot-mode :: you can search the web for the latest active one.
  30. ;;; Code:
  31. (require 'ob)
  32. (require 'org-macs)
  33. (declare-function org-time-string-to-time "org" (s))
  34. (declare-function orgtbl-to-generic "org-table" (table params))
  35. (declare-function gnuplot-mode "ext:gnuplot-mode" ())
  36. (declare-function gnuplot-send-string-to-gnuplot "ext:gnuplot-mode" (str txt))
  37. (declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot-mode" ())
  38. (defvar org-babel-temporary-directory)
  39. (defvar org-babel-default-header-args:gnuplot
  40. '((:results . "file") (:exports . "results") (:session . nil))
  41. "Default arguments to use when evaluating a gnuplot source block.")
  42. (defvar org-babel-header-args:gnuplot
  43. '((title . :any)
  44. (lines . :any)
  45. (sets . :any)
  46. (x-labels . :any)
  47. (y-labels . :any)
  48. (timefmt . :any)
  49. (time-ind . :any)
  50. (missing . :any)
  51. (term . :any))
  52. "Gnuplot specific header args.")
  53. (defvar org-babel-gnuplot-timestamp-fmt nil) ; Dynamically scoped.
  54. (defvar *org-babel-gnuplot-missing* nil)
  55. (defcustom *org-babel-gnuplot-terms*
  56. '((eps . "postscript eps"))
  57. "List of file extensions and the associated gnuplot terminal."
  58. :group 'org-babel
  59. :type '(repeat (cons (symbol :tag "File extension")
  60. (string :tag "Gnuplot terminal"))))
  61. (defun org-babel-gnuplot-process-vars (params)
  62. "Extract variables from PARAMS and process the variables.
  63. Dumps all vectors into files and returns an association list
  64. of variable names and the related value to be used in the gnuplot
  65. code."
  66. (let ((*org-babel-gnuplot-missing* (cdr (assq :missing params))))
  67. (mapcar
  68. (lambda (pair)
  69. (cons
  70. (car pair) ;; variable name
  71. (let* ((val (cdr pair)) ;; variable value
  72. (lp (proper-list-p val)))
  73. (if lp
  74. (org-babel-gnuplot-table-to-data
  75. (let* ((first (car val))
  76. (tablep (or (listp first) (symbolp first))))
  77. (if tablep val (mapcar 'list val)))
  78. (org-babel-temp-file "gnuplot-") params)
  79. (if (and (stringp val)
  80. (file-remote-p val) ;; check if val is a remote file
  81. (file-exists-p val)) ;; call to file-exists-p is slow, maybe remove it
  82. (let* ((local-name (concat ;; create a unique filename to avoid multiple downloads
  83. org-babel-temporary-directory
  84. "/gnuplot/"
  85. (file-remote-p val 'host)
  86. (org-babel-local-file-name val))))
  87. (if (and (file-exists-p local-name) ;; only download file if remote is newer
  88. (file-newer-than-file-p local-name val))
  89. local-name
  90. (make-directory (file-name-directory local-name) t)
  91. (copy-file val local-name t)
  92. ))
  93. val
  94. )))))
  95. (org-babel--get-vars params))))
  96. (defun org-babel-expand-body:gnuplot (body params)
  97. "Expand BODY according to PARAMS, return the expanded body."
  98. (save-window-excursion
  99. (let* ((vars (org-babel-gnuplot-process-vars params))
  100. (out-file (cdr (assq :file params)))
  101. (prologue (cdr (assq :prologue params)))
  102. (epilogue (cdr (assq :epilogue params)))
  103. (term (or (cdr (assq :term params))
  104. (when out-file
  105. (let ((ext (file-name-extension out-file)))
  106. (or (cdr (assoc (intern (downcase ext))
  107. *org-babel-gnuplot-terms*))
  108. ext)))))
  109. (title (cdr (assq :title params)))
  110. (lines (cdr (assq :line params)))
  111. (sets (cdr (assq :set params)))
  112. (missing (cdr (assq :missing params)))
  113. (x-labels (cdr (assq :xlabels params)))
  114. (y-labels (cdr (assq :ylabels params)))
  115. (timefmt (cdr (assq :timefmt params)))
  116. (time-ind (or (cdr (assq :timeind params))
  117. (when timefmt 1)))
  118. (directory (and (buffer-file-name)
  119. (file-name-directory (buffer-file-name))))
  120. (add-to-body (lambda (text) (setq body (concat text "\n" body)))))
  121. ;; append header argument settings to body
  122. (when missing (funcall add-to-body (format "set datafile missing '%s'" missing)))
  123. (when title (funcall add-to-body (format "set title '%s'" title)))
  124. (when lines (mapc (lambda (el) (funcall add-to-body el)) lines))
  125. (when sets
  126. (mapc (lambda (el) (funcall add-to-body (format "set %s" el))) sets))
  127. (when x-labels
  128. (funcall add-to-body
  129. (format "set xtics (%s)"
  130. (mapconcat (lambda (pair)
  131. (format "\"%s\" %d"
  132. (cdr pair) (car pair)))
  133. x-labels ", "))))
  134. (when y-labels
  135. (funcall add-to-body
  136. (format "set ytics (%s)"
  137. (mapconcat (lambda (pair)
  138. (format "\"%s\" %d"
  139. (cdr pair) (car pair)))
  140. y-labels ", "))))
  141. (when time-ind
  142. (funcall add-to-body "set xdata time")
  143. (funcall add-to-body (concat "set timefmt \""
  144. (or timefmt
  145. "%Y-%m-%d-%H:%M:%S") "\"")))
  146. (when out-file
  147. ;; set the terminal at the top of the block
  148. (funcall add-to-body (format "set output \"%s\"" out-file))
  149. ;; and close the terminal at the bottom of the block
  150. (setq body (concat body "\nset output\n")))
  151. (when term (funcall add-to-body (format "set term %s" term)))
  152. ;; insert variables into code body: this should happen last
  153. ;; placing the variables at the *top* of the code in case their
  154. ;; values are used later
  155. (funcall add-to-body
  156. (mapconcat #'identity
  157. (org-babel-variable-assignments:gnuplot params)
  158. "\n"))
  159. ;; replace any variable names preceded by '$' with the actual
  160. ;; value of the variable
  161. (mapc (lambda (pair)
  162. (setq body (replace-regexp-in-string
  163. (format "\\$%s" (car pair)) (cdr pair) body)))
  164. vars)
  165. (when prologue (funcall add-to-body prologue))
  166. (when epilogue (setq body (concat body "\n" epilogue)))
  167. ;; Setting the directory needs to be done first so that
  168. ;; subsequent 'output' directive goes to the right place.
  169. (when directory (funcall add-to-body (format "cd '%s'" directory))))
  170. body))
  171. (defun org-babel-execute:gnuplot (body params)
  172. "Execute a block of Gnuplot code.
  173. This function is called by `org-babel-execute-src-block'."
  174. (require 'gnuplot)
  175. (let ((session (cdr (assq :session params)))
  176. (result-type (cdr (assq :results params)))
  177. (body (org-babel-expand-body:gnuplot body params))
  178. output)
  179. (save-window-excursion
  180. ;; evaluate the code body with gnuplot
  181. (if (string= session "none")
  182. (let ((script-file (org-babel-temp-file "gnuplot-script-")))
  183. (with-temp-file script-file
  184. (insert (concat body "\n")))
  185. (message "gnuplot \"%s\"" script-file)
  186. (setq output
  187. (shell-command-to-string
  188. (format
  189. "gnuplot \"%s\""
  190. (org-babel-process-file-name
  191. script-file
  192. (if (member system-type '(cygwin windows-nt ms-dos))
  193. t nil)))))
  194. (message "%s" output))
  195. (with-temp-buffer
  196. (insert (concat body "\n"))
  197. (gnuplot-mode)
  198. (gnuplot-send-buffer-to-gnuplot)))
  199. (if (member "output" (split-string result-type))
  200. output
  201. nil)))) ;; signal that output has already been written to file
  202. (defun org-babel-prep-session:gnuplot (session params)
  203. "Prepare SESSION according to the header arguments in PARAMS."
  204. (let* ((session (org-babel-gnuplot-initiate-session session))
  205. (var-lines (org-babel-variable-assignments:gnuplot params)))
  206. (message "%S" session)
  207. (org-babel-comint-in-buffer session
  208. (dolist (var-line var-lines)
  209. (insert var-line)
  210. (comint-send-input nil t)
  211. (org-babel-comint-wait-for-output session)
  212. (sit-for .1)
  213. (goto-char (point-max))))
  214. session))
  215. (defun org-babel-load-session:gnuplot (session body params)
  216. "Load BODY into SESSION."
  217. (save-window-excursion
  218. (let ((buffer (org-babel-prep-session:gnuplot session params)))
  219. (with-current-buffer buffer
  220. (goto-char (process-mark (get-buffer-process (current-buffer))))
  221. (insert (org-babel-chomp body)))
  222. buffer)))
  223. (defun org-babel-variable-assignments:gnuplot (params)
  224. "Return list of gnuplot statements assigning the block's variables."
  225. (mapcar
  226. (lambda (pair) (format "%s = \"%s\"" (car pair) (cdr pair)))
  227. (org-babel-gnuplot-process-vars params)))
  228. (defvar gnuplot-buffer)
  229. (defun org-babel-gnuplot-initiate-session (&optional session _params)
  230. "Initiate a gnuplot session.
  231. If there is not a current inferior-process-buffer in SESSION
  232. then create one. Return the initialized session. The current
  233. `gnuplot-mode' doesn't provide support for multiple sessions."
  234. (require 'gnuplot)
  235. (unless (string= session "none")
  236. (save-window-excursion
  237. (gnuplot-send-string-to-gnuplot "" "line")
  238. gnuplot-buffer)))
  239. (defun org-babel-gnuplot-quote-timestamp-field (s)
  240. "Convert S from timestamp to Unix time and export to gnuplot."
  241. (format-time-string org-babel-gnuplot-timestamp-fmt
  242. (org-time-string-to-time s)))
  243. (defvar org-table-number-regexp)
  244. (defvar org-ts-regexp3)
  245. (defun org-babel-gnuplot-quote-tsv-field (s)
  246. "Quote S for export to gnuplot."
  247. (unless (stringp s)
  248. (setq s (format "%s" s)))
  249. (if (string-match org-table-number-regexp s) s
  250. (if (string-match org-ts-regexp3 s)
  251. (org-babel-gnuplot-quote-timestamp-field s)
  252. (if (zerop (length s))
  253. (or *org-babel-gnuplot-missing* s)
  254. (if (string-match "[ \"]" s)
  255. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"")
  256. "\"")
  257. s)))))
  258. (defun org-babel-gnuplot-table-to-data (table data-file params)
  259. "Export TABLE to DATA-FILE in a format readable by gnuplot.
  260. Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
  261. (require 'ox-org)
  262. (with-temp-file data-file
  263. (insert (let ((org-babel-gnuplot-timestamp-fmt
  264. (or (plist-get params :timefmt) "%Y-%m-%d-%H:%M:%S")))
  265. (orgtbl-to-generic
  266. table
  267. (org-combine-plists
  268. '( :sep "\t" :fmt org-babel-gnuplot-quote-tsv-field
  269. ;; Two setting below are needed to make :fmt work.
  270. :raw t
  271. :backend ascii)
  272. params)))))
  273. data-file)
  274. (provide 'ob-gnuplot)
  275. ;;; ob-gnuplot.el ends here