ob-gnuplot.el 11 KB

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