ob-gnuplot.el 11 KB

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