ob-gnuplot.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 '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 default-directory)
  119. (add-to-body (lambda (text) (setq body (concat text "\n" body)))))
  120. ;; append header argument settings to body
  121. (when missing (funcall add-to-body (format "set datafile missing '%s'" missing)))
  122. (when title (funcall add-to-body (format "set title '%s'" title)))
  123. (when lines (mapc (lambda (el) (funcall add-to-body el)) lines))
  124. (when sets
  125. (mapc (lambda (el) (funcall add-to-body (format "set %s" el))) sets))
  126. (when x-labels
  127. (funcall add-to-body
  128. (format "set xtics (%s)"
  129. (mapconcat (lambda (pair)
  130. (format "\"%s\" %d"
  131. (cdr pair) (car pair)))
  132. x-labels ", "))))
  133. (when y-labels
  134. (funcall add-to-body
  135. (format "set ytics (%s)"
  136. (mapconcat (lambda (pair)
  137. (format "\"%s\" %d"
  138. (cdr pair) (car pair)))
  139. y-labels ", "))))
  140. (when time-ind
  141. (funcall add-to-body "set xdata time")
  142. (funcall add-to-body (concat "set timefmt \""
  143. (or timefmt
  144. "%Y-%m-%d-%H:%M:%S") "\"")))
  145. (when out-file
  146. ;; set the terminal at the top of the block
  147. (funcall add-to-body (format "set output \"%s\"" out-file))
  148. ;; and close the terminal at the bottom of the block
  149. (setq body (concat body "\nset output\n")))
  150. (when term (funcall add-to-body (format "set term %s" term)))
  151. ;; insert variables into code body: this should happen last
  152. ;; placing the variables at the *top* of the code in case their
  153. ;; values are used later
  154. (funcall add-to-body
  155. (mapconcat #'identity
  156. (org-babel-variable-assignments:gnuplot params)
  157. "\n"))
  158. ;; replace any variable names preceded by '$' with the actual
  159. ;; value of the variable
  160. (mapc (lambda (pair)
  161. (setq body (replace-regexp-in-string
  162. (format "\\$%s" (car pair)) (cdr pair) body)))
  163. vars)
  164. (when prologue (funcall add-to-body prologue))
  165. (when epilogue (setq body (concat body "\n" epilogue)))
  166. ;; Setting the directory needs to be done first so that
  167. ;; subsequent 'output' directive goes to the right place.
  168. (when directory (funcall add-to-body (format "cd '%s'" directory))))
  169. body))
  170. (defun org-babel-execute:gnuplot (body params)
  171. "Execute a block of Gnuplot code.
  172. This function is called by `org-babel-execute-src-block'."
  173. (require 'gnuplot)
  174. (let ((session (cdr (assq :session params)))
  175. (result-type (cdr (assq :results params)))
  176. (body (org-babel-expand-body:gnuplot body params))
  177. output)
  178. (save-window-excursion
  179. ;; evaluate the code body with gnuplot
  180. (if (string= session "none")
  181. (let ((script-file (org-babel-temp-file "gnuplot-script-")))
  182. (with-temp-file script-file
  183. (insert (concat body "\n")))
  184. (message "gnuplot \"%s\"" script-file)
  185. (setq output
  186. (shell-command-to-string
  187. (format
  188. "gnuplot \"%s\""
  189. (org-babel-process-file-name
  190. script-file
  191. (if (member system-type '(cygwin windows-nt ms-dos))
  192. t nil)))))
  193. (message "%s" output))
  194. (with-temp-buffer
  195. (insert (concat body "\n"))
  196. (gnuplot-mode)
  197. (gnuplot-send-buffer-to-gnuplot)))
  198. (if (member "output" (split-string result-type))
  199. output
  200. nil)))) ;; signal that output has already been written to file
  201. (defun org-babel-prep-session:gnuplot (session params)
  202. "Prepare SESSION according to the header arguments in PARAMS."
  203. (let* ((session (org-babel-gnuplot-initiate-session session))
  204. (var-lines (org-babel-variable-assignments:gnuplot params)))
  205. (message "%S" session)
  206. (org-babel-comint-in-buffer session
  207. (dolist (var-line var-lines)
  208. (insert var-line)
  209. (comint-send-input nil t)
  210. (org-babel-comint-wait-for-output session)
  211. (sit-for .1)
  212. (goto-char (point-max))))
  213. session))
  214. (defun org-babel-load-session:gnuplot (session body params)
  215. "Load BODY into SESSION."
  216. (save-window-excursion
  217. (let ((buffer (org-babel-prep-session:gnuplot session params)))
  218. (with-current-buffer buffer
  219. (goto-char (process-mark (get-buffer-process (current-buffer))))
  220. (insert (org-babel-chomp body)))
  221. buffer)))
  222. (defun org-babel-variable-assignments:gnuplot (params)
  223. "Return list of gnuplot statements assigning the block's variables."
  224. (mapcar
  225. (lambda (pair) (format "%s = \"%s\"" (car pair) (cdr pair)))
  226. (org-babel-gnuplot-process-vars params)))
  227. (defvar gnuplot-buffer)
  228. (defun org-babel-gnuplot-initiate-session (&optional session _params)
  229. "Initiate a gnuplot session.
  230. If there is not a current inferior-process-buffer in SESSION
  231. then create one. Return the initialized session. The current
  232. `gnuplot-mode' doesn't provide support for multiple sessions."
  233. (require 'gnuplot)
  234. (unless (string= session "none")
  235. (save-window-excursion
  236. (gnuplot-send-string-to-gnuplot "" "line")
  237. gnuplot-buffer)))
  238. (defun org-babel-gnuplot-quote-timestamp-field (s)
  239. "Convert S from timestamp to Unix time and export to gnuplot."
  240. (format-time-string org-babel-gnuplot-timestamp-fmt
  241. (org-time-string-to-time s)))
  242. (defvar org-table-number-regexp)
  243. (defvar org-ts-regexp3)
  244. (defun org-babel-gnuplot-quote-tsv-field (s)
  245. "Quote S for export to gnuplot."
  246. (unless (stringp s)
  247. (setq s (format "%s" s)))
  248. (if (string-match org-table-number-regexp s) s
  249. (if (string-match org-ts-regexp3 s)
  250. (org-babel-gnuplot-quote-timestamp-field s)
  251. (if (zerop (length s))
  252. (or *org-babel-gnuplot-missing* s)
  253. (if (string-match "[ \"]" s)
  254. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"")
  255. "\"")
  256. s)))))
  257. (defun org-babel-gnuplot-table-to-data (table data-file params)
  258. "Export TABLE to DATA-FILE in a format readable by gnuplot.
  259. Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
  260. (require 'ox-org)
  261. (with-temp-file data-file
  262. (insert (let ((org-babel-gnuplot-timestamp-fmt
  263. (or (plist-get params :timefmt) "%Y-%m-%d-%H:%M:%S")))
  264. (orgtbl-to-generic
  265. table
  266. (org-combine-plists
  267. '( :sep "\t" :fmt org-babel-gnuplot-quote-tsv-field
  268. ;; Two setting below are needed to make :fmt work.
  269. :raw t
  270. :backend ascii)
  271. params)))))
  272. data-file)
  273. (provide 'ob-gnuplot)
  274. ;;; ob-gnuplot.el ends here