Sync Org 7.9.2 from the commit tagged "release_7.9.2" in Org's Git repo.
[bpt/emacs.git] / lisp / org / org-plot.el
CommitLineData
006793d0
CD
1;;; org-plot.el --- Support for plotting from Org-mode
2
b73f1974 3;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
006793d0
CD
4;;
5;; Author: Eric Schulte <schulte dot eric at gmail dot com>
6;; Keywords: tables, plotting
7;; Homepage: http://orgmode.org
006793d0
CD
8;;
9;; This file is part of GNU Emacs.
10;;
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.
15
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.
20
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/>.
23
24;;; Commentary:
25
26;; Borrows ideas and a couple of lines of code from org-exp.el.
27
28;; Thanks to the org-mode mailing list for testing and implementation
29;; and feature suggestions
30
31;;; Code:
32(require 'org)
33(require 'org-exp)
34(require 'org-table)
54a0dee5 35(eval-when-compile
006793d0
CD
36 (require 'cl))
37
38(declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg))
39(declare-function gnuplot-mode "ext:gnuplot" ())
40(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ())
41
42(defvar org-plot/gnuplot-default-options
43 '((:plot-type . 2d)
44 (:with . lines)
45 (:ind . 0))
86fbb8ca 46 "Default options to gnuplot used by `org-plot/gnuplot'.")
006793d0 47
93b62de8
CD
48(defvar org-plot-timestamp-fmt nil)
49
006793d0
CD
50(defun org-plot/add-options-to-plist (p options)
51 "Parse an OPTIONS line and set values in the property list P.
52Returns the resulting property list."
53 (let (o)
54 (when options
93b62de8
CD
55 (let ((op '(("type" . :plot-type)
56 ("script" . :script)
57 ("line" . :line)
58 ("set" . :set)
59 ("title" . :title)
60 ("ind" . :ind)
61 ("deps" . :deps)
62 ("with" . :with)
63 ("file" . :file)
64 ("labels" . :labels)
65 ("map" . :map)
c8d0cf5c 66 ("timeind" . :timeind)
33306645 67 ("timefmt" . :timefmt)))
006793d0
CD
68 (multiples '("set" "line"))
69 (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
70 (start 0)
71 o)
72 (while (setq o (pop op))
73 (if (member (car o) multiples) ;; keys with multiple values
74 (while (string-match
75 (concat (regexp-quote (car o)) regexp)
76 options start)
77 (setq start (match-end 0))
78 (setq p (plist-put p (cdr o)
79 (cons (car (read-from-string
80 (match-string 1 options)))
81 (plist-get p (cdr o)))))
82 p)
83 (if (string-match (concat (regexp-quote (car o)) regexp)
84 options)
85 (setq p (plist-put p (cdr o)
86 (car (read-from-string
87 (match-string 1 options)))))))))))
88 p)
89
90(defun org-plot/goto-nearest-table ()
91 "Move the point forward to the beginning of nearest table.
92Return value is the point at the beginning of the table."
93 (interactive) (move-beginning-of-line 1)
94 (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
95 (goto-char (org-table-begin)))
96
97(defun org-plot/collect-options (&optional params)
98 "Collect options from an org-plot '#+Plot:' line.
99Accepts an optional property list PARAMS, to which the options
100will be added. Returns the resulting property list."
101 (interactive)
102 (let ((line (thing-at-point 'line)))
103 (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
104 (org-plot/add-options-to-plist params (match-string 1 line))
105 params)))
106
93b62de8
CD
107(defun org-plot-quote-timestamp-field (s)
108 "Convert field S from timestamp to Unix time and export to gnuplot."
109 (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))
110
006793d0
CD
111(defun org-plot-quote-tsv-field (s)
112 "Quote field S for export to gnuplot."
113 (if (string-match org-table-number-regexp s) s
93b62de8 114 (if (string-match org-ts-regexp3 s)
33306645 115 (org-plot-quote-timestamp-field s)
93b62de8 116 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))
006793d0
CD
117
118(defun org-plot/gnuplot-to-data (table data-file params)
119 "Export TABLE to DATA-FILE in a format readable by gnuplot.
120Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
121 (with-temp-file
ff4be292 122 data-file
93b62de8
CD
123 (make-local-variable 'org-plot-timestamp-fmt)
124 (setq org-plot-timestamp-fmt (or
33306645
CD
125 (plist-get params :timefmt)
126 "%Y-%m-%d-%H:%M:%S"))
93b62de8 127 (insert (orgtbl-to-generic
33306645
CD
128 table
129 (org-combine-plists
130 '(:sep "\t" :fmt org-plot-quote-tsv-field)
131 params))))
006793d0
CD
132 nil)
133
134(defun org-plot/gnuplot-to-grid-data (table data-file params)
135 "Export the data in TABLE to DATA-FILE for gnuplot.
ed21c5c8 136This means in a format appropriate for grid plotting by gnuplot.
33306645 137PARAMS specifies which columns of TABLE should be plotted as independent
e66ba1df 138and dependant variables."
006793d0
CD
139 (interactive)
140 (let* ((ind (- (plist-get params :ind) 1))
141 (deps (if (plist-member params :deps)
142 (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
143 (let (collector)
144 (dotimes (col (length (first table)))
145 (setf collector (cons col collector)))
146 collector)))
8223b1d2
BG
147 (counter 0)
148 row-vals)
006793d0
CD
149 (when (>= ind 0) ;; collect values of ind col
150 (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
151 (cons counter (nth ind row))) table)))
152 (when (or deps (>= ind 0)) ;; remove non-plotting columns
153 (setf deps (delq ind deps))
154 (setf table (mapcar (lambda (row)
155 (dotimes (col (length row))
156 (unless (memq col deps)
157 (setf (nth col row) nil)))
158 (delq nil row))
159 table)))
160 ;; write table to gnuplot grid datafile format
161 (with-temp-file data-file
162 (let ((num-rows (length table)) (num-cols (length (first table)))
8223b1d2
BG
163 (gnuplot-row (lambda (col row value)
164 (setf col (+ 1 col)) (setf row (+ 1 row))
165 (format "%f %f %f\n%f %f %f\n"
166 col (- row 0.5) value ;; lower edge
167 col (+ row 0.5) value))) ;; upper edge
006793d0 168 front-edge back-edge)
8223b1d2
BG
169 (dotimes (col num-cols)
170 (dotimes (row num-rows)
171 (setf back-edge
172 (concat back-edge
173 (funcall gnuplot-row (- col 1) row
174 (string-to-number (nth col (nth row table))))))
175 (setf front-edge
176 (concat front-edge
177 (funcall gnuplot-row col row
178 (string-to-number (nth col (nth row table)))))))
179 ;; only insert once per row
180 (insert back-edge) (insert "\n") ;; back edge
181 (insert front-edge) (insert "\n") ;; front edge
182 (setf back-edge "") (setf front-edge ""))))
006793d0
CD
183 row-vals))
184
c8d0cf5c 185(defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
006793d0 186 "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
c8d0cf5c
CD
187NUM-COLS controls the number of columns plotted in a 2-d plot.
188Optional argument PREFACE returns only option parameters in a
189manner suitable for prepending to a user-specified script."
006793d0
CD
190 (let* ((type (plist-get params :plot-type))
191 (with (if (equal type 'grid)
192 'pm3d
193 (plist-get params :with)))
194 (sets (plist-get params :set))
195 (lines (plist-get params :line))
196 (map (plist-get params :map))
197 (title (plist-get params :title))
198 (file (plist-get params :file))
199 (ind (plist-get params :ind))
33306645
CD
200 (time-ind (plist-get params :timeind))
201 (timefmt (plist-get params :timefmt))
006793d0
CD
202 (text-ind (plist-get params :textind))
203 (deps (if (plist-member params :deps) (plist-get params :deps)))
204 (col-labels (plist-get params :labels))
205 (x-labels (plist-get params :xlabels))
206 (y-labels (plist-get params :ylabels))
207 (plot-str "'%s' using %s%d%s with %s title '%s'")
208 (plot-cmd (case type
3ab2c837
BG
209 ('2d "plot")
210 ('3d "splot")
211 ('grid "splot")))
8223b1d2
BG
212 (script "reset")
213 ; ats = add-to-script
214 (ats (lambda (line) (setf script (format "%s\n%s" script line))))
215 plot-lines)
216 (when file ;; output file
217 (funcall ats (format "set term %s" (file-name-extension file)))
218 (funcall ats (format "set output '%s'" file)))
219 (case type ;; type
220 ('2d ())
221 ('3d (if map (funcall ats "set map")))
222 ('grid (if map (funcall ats "set pm3d map")
223 (funcall ats "set pm3d"))))
224 (when title (funcall ats (format "set title '%s'" title))) ;; title
225 (when lines (mapc (lambda (el) (funcall ats el)) lines)) ;; line
226 (when sets ;; set
227 (mapc (lambda (el) (funcall ats (format "set %s" el))) sets))
228 (when x-labels ;; x labels (xtics)
229 (funcall ats
230 (format "set xtics (%s)"
231 (mapconcat (lambda (pair)
232 (format "\"%s\" %d" (cdr pair) (car pair)))
233 x-labels ", "))))
234 (when y-labels ;; y labels (ytics)
235 (funcall ats
236 (format "set ytics (%s)"
237 (mapconcat (lambda (pair)
238 (format "\"%s\" %d" (cdr pair) (car pair)))
239 y-labels ", "))))
240 (when time-ind ;; timestamp index
241 (funcall ats "set xdata time")
242 (funcall ats (concat "set timefmt \""
243 (or timefmt ;; timefmt passed to gnuplot
244 "%Y-%m-%d-%H:%M:%S") "\"")))
245 (unless preface
246 (case type ;; plot command
3ab2c837 247 ('2d (dotimes (col num-cols)
006793d0
CD
248 (unless (and (equal type '2d)
249 (or (and ind (equal (+ 1 col) ind))
250 (and deps (not (member (+ 1 col) deps)))))
251 (setf plot-lines
252 (cons
253 (format plot-str data-file
ed21c5c8
CD
254 (or (and ind (> ind 0)
255 (not text-ind)
256 (format "%d:" ind)) "")
006793d0
CD
257 (+ 1 col)
258 (if text-ind (format ":xticlabel(%d)" ind) "")
259 with
260 (or (nth col col-labels) (format "%d" (+ 1 col))))
261 plot-lines)))))
3ab2c837 262 ('3d
006793d0
CD
263 (setq plot-lines (list (format "'%s' matrix with %s title ''"
264 data-file with))))
3ab2c837 265 ('grid
006793d0
CD
266 (setq plot-lines (list (format "'%s' with %s title ''"
267 data-file with)))))
8223b1d2
BG
268 (funcall ats
269 (concat plot-cmd " " (mapconcat 'identity (reverse plot-lines) ",\\\n "))))
270 script))
006793d0
CD
271
272;;-----------------------------------------------------------------------------
273;; facade functions
274;;;###autoload
275(defun org-plot/gnuplot (&optional params)
86fbb8ca 276 "Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
006793d0
CD
277If not given options will be taken from the +PLOT
278line directly before or after the table."
279 (interactive)
280 (require 'gnuplot)
281 (save-window-excursion
282 (delete-other-windows)
283 (when (get-buffer "*gnuplot*") ;; reset *gnuplot* if it already running
81ad75af 284 (with-current-buffer "*gnuplot*"
8bfe682a 285 (goto-char (point-max))
006793d0
CD
286 (gnuplot-delchar-or-maybe-eof nil)))
287 (org-plot/goto-nearest-table)
288 ;; set default options
289 (mapc
290 (lambda (pair)
291 (unless (plist-member params (car pair))
292 (setf params (plist-put params (car pair) (cdr pair)))))
293 org-plot/gnuplot-default-options)
294 ;; collect table and table information
295 (let* ((data-file (make-temp-file "org-plot"))
296 (table (org-table-to-lisp))
297 (num-cols (length (if (eq (first table) 'hline) (second table)
298 (first table)))))
299 (while (equal 'hline (first table)) (setf table (cdr table)))
300 (when (equal (second table) 'hline)
301 (setf params (plist-put params :labels (first table))) ;; headers to labels
302 (setf table (delq 'hline (cdr table)))) ;; clean non-data from table
303 ;; collect options
304 (save-excursion (while (and (equal 0 (forward-line -1))
ed21c5c8 305 (looking-at "[[:space:]]*#\\+"))
006793d0
CD
306 (setf params (org-plot/collect-options params))))
307 ;; dump table to datafile (very different for grid)
308 (case (plist-get params :plot-type)
3ab2c837
BG
309 ('2d (org-plot/gnuplot-to-data table data-file params))
310 ('3d (org-plot/gnuplot-to-data table data-file params))
311 ('grid (let ((y-labels (org-plot/gnuplot-to-grid-data
006793d0
CD
312 table data-file params)))
313 (when y-labels (plist-put params :ylabels y-labels)))))
93b62de8 314 ;; check for timestamp ind column
006793d0 315 (let ((ind (- (plist-get params :ind) 1)))
33306645
CD
316 (when (and (>= ind 0) (equal '2d (plist-get params :plot-type)))
317 (if (= (length
318 (delq 0 (mapcar
006793d0 319 (lambda (el)
93b62de8 320 (if (string-match org-ts-regexp3 el)
006793d0
CD
321 0 1))
322 (mapcar (lambda (row) (nth ind row)) table)))) 0)
93b62de8 323 (plist-put params :timeind t)
33306645 324 ;; check for text ind column
0bd48b37
CD
325 (if (or (string= (plist-get params :with) "hist")
326 (> (length
327 (delq 0 (mapcar
328 (lambda (el)
329 (if (string-match org-table-number-regexp el)
330 0 1))
331 (mapcar (lambda (row) (nth ind row)) table)))) 0))
33306645 332 (plist-put params :textind t)))))
006793d0
CD
333 ;; write script
334 (with-temp-buffer
335 (if (plist-get params :script) ;; user script
c8d0cf5c
CD
336 (progn (insert
337 (org-plot/gnuplot-script data-file num-cols params t))
338 (insert "\n")
339 (insert-file-contents (plist-get params :script))
340 (goto-char (point-min))
341 (while (re-search-forward "$datafile" nil t)
342 (replace-match data-file nil nil)))
006793d0
CD
343 (insert
344 (org-plot/gnuplot-script data-file num-cols params)))
345 ;; graph table
346 (gnuplot-mode)
347 (gnuplot-send-buffer-to-gnuplot))
348 ;; cleanup
93b62de8 349 (bury-buffer (get-buffer "*gnuplot*"))
c8d0cf5c 350 (run-with-idle-timer 0.1 nil (lambda () (delete-file data-file))))))
006793d0
CD
351
352(provide 'org-plot)
353
354;;; org-plot.el ends here