Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / ob-gnuplot.el
bloba1546ad5ae2149616029f8bf887c6364e2dda110
1 ;;; ob-gnuplot.el --- Babel Functions for Gnuplot -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Org-Babel support for evaluating gnuplot source code.
28 ;; This differs from most standard languages in that
30 ;; 1) we are generally only going to return results of type "file"
32 ;; 2) we are adding the "file" and "cmdline" header arguments
34 ;;; Requirements:
36 ;; - gnuplot :: http://www.gnuplot.info/
38 ;; - gnuplot-mode :: http://cars9.uchicago.edu/~ravel/software/gnuplot-mode.html
40 ;;; Code:
41 (require 'ob)
42 (eval-when-compile (require 'cl))
44 (declare-function org-time-string-to-time "org" (s &optional buffer pos))
45 (declare-function org-combine-plists "org" (&rest plists))
46 (declare-function orgtbl-to-generic "org-table" (table params))
47 (declare-function gnuplot-mode "ext:gnuplot-mode" ())
48 (declare-function gnuplot-send-string-to-gnuplot "ext:gnuplot-mode" (str txt))
49 (declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot-mode" ())
51 (defvar org-babel-default-header-args:gnuplot
52 '((:results . "file") (:exports . "results") (:session . nil))
53 "Default arguments to use when evaluating a gnuplot source block.")
55 (defvar org-babel-header-args:gnuplot
56 '((title . :any)
57 (lines . :any)
58 (sets . :any)
59 (x-labels . :any)
60 (y-labels . :any)
61 (timefmt . :any)
62 (time-ind . :any)
63 (missing . :any)
64 (term . :any))
65 "Gnuplot specific header args.")
67 (defvar org-babel-gnuplot-timestamp-fmt nil) ; Dynamically scoped.
69 (defvar *org-babel-gnuplot-missing* nil)
71 (defcustom *org-babel-gnuplot-terms*
72 '((eps . "postscript eps"))
73 "List of file extensions and the associated gnuplot terminal."
74 :group 'org-babel
75 :type '(repeat (cons (symbol :tag "File extension")
76 (string :tag "Gnuplot terminal"))))
78 (defun org-babel-gnuplot-process-vars (params)
79 "Extract variables from PARAMS and process the variables.
80 Dumps all vectors into files and returns an association list
81 of variable names and the related value to be used in the gnuplot
82 code."
83 (let ((*org-babel-gnuplot-missing* (cdr (assoc :missing params))))
84 (mapcar
85 (lambda (pair)
86 (cons
87 (car pair) ;; variable name
88 (let* ((val (cdr pair)) ;; variable value
89 (lp (listp val)))
90 (if lp
91 (org-babel-gnuplot-table-to-data
92 (let* ((first (car val))
93 (tablep (or (listp first) (symbolp first))))
94 (if tablep val (mapcar 'list val)))
95 (org-babel-temp-file "gnuplot-") params)
96 val))))
97 (org-babel--get-vars params))))
99 (defun org-babel-expand-body:gnuplot (body params)
100 "Expand BODY according to PARAMS, return the expanded body."
101 (save-window-excursion
102 (let* ((vars (org-babel-gnuplot-process-vars params))
103 (out-file (cdr (assoc :file params)))
104 (prologue (cdr (assoc :prologue params)))
105 (epilogue (cdr (assoc :epilogue params)))
106 (term (or (cdr (assoc :term params))
107 (when out-file
108 (let ((ext (file-name-extension out-file)))
109 (or (cdr (assoc (intern (downcase ext))
110 *org-babel-gnuplot-terms*))
111 ext)))))
112 (title (cdr (assoc :title params)))
113 (lines (cdr (assoc :line params)))
114 (sets (cdr (assoc :set params)))
115 (x-labels (cdr (assoc :xlabels params)))
116 (y-labels (cdr (assoc :ylabels params)))
117 (timefmt (cdr (assoc :timefmt params)))
118 (time-ind (or (cdr (assoc :timeind params))
119 (when timefmt 1)))
120 (add-to-body (lambda (text) (setq body (concat text "\n" body)))))
121 ;; append header argument settings to body
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 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 (assoc :session params)))
173 (result-type (cdr (assoc :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 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
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))
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)))
223 (defun org-babel-variable-assignments:gnuplot (params)
224 "Return list of gnuplot statements assigning the block's variables."
225 (mapcar
226 (lambda (pair) (format "%s = \"%s\"" (car pair) (cdr pair)))
227 (org-babel-gnuplot-process-vars params)))
229 (defvar gnuplot-buffer)
230 (defun org-babel-gnuplot-initiate-session (&optional session _params)
231 "Initiate a gnuplot session.
232 If there is not a current inferior-process-buffer in SESSION
233 then create one. Return the initialized session. The current
234 `gnuplot-mode' doesn't provide support for multiple sessions."
235 (require 'gnuplot)
236 (unless (string= session "none")
237 (save-window-excursion
238 (gnuplot-send-string-to-gnuplot "" "line")
239 gnuplot-buffer)))
241 (defun org-babel-gnuplot-quote-timestamp-field (s)
242 "Convert S from timestamp to Unix time and export to gnuplot."
243 (format-time-string org-babel-gnuplot-timestamp-fmt
244 (org-time-string-to-time s)))
246 (defvar org-table-number-regexp)
247 (defvar org-ts-regexp3)
248 (defun org-babel-gnuplot-quote-tsv-field (s)
249 "Quote S for export to gnuplot."
250 (unless (stringp s)
251 (setq s (format "%s" s)))
252 (if (string-match org-table-number-regexp s) s
253 (if (string-match org-ts-regexp3 s)
254 (org-babel-gnuplot-quote-timestamp-field s)
255 (if (zerop (length s))
256 (or *org-babel-gnuplot-missing* s)
257 (if (string-match "[ \"]" s)
258 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"")
259 "\"")
260 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 (with-temp-file data-file
266 (insert (let ((org-babel-gnuplot-timestamp-fmt
267 (or (plist-get params :timefmt) "%Y-%m-%d-%H:%M:%S")))
268 (orgtbl-to-generic
269 table
270 (org-combine-plists
271 '(:sep "\t" :fmt org-babel-gnuplot-quote-tsv-field)
272 params)))))
273 data-file)
275 (provide 'ob-gnuplot)
279 ;;; ob-gnuplot.el ends here