ob-gnuplot.el 11 KB

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