ob-gnuplot.el 11 KB

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