unofficial mirror of emacs-orgmode@gnu.org
 help / color / mirror / Atom feed
1b227d698130a2b662eea89f465df389c1978616 blob 24240 bytes (raw)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
 
;;; org-plot.el --- Support for Plotting from Org -*- lexical-binding: t; -*-

;; Copyright (C) 2008-2020 Free Software Foundation, Inc.
;;
;; Author: Eric Schulte <schulte dot eric at gmail dot com>
;; Keywords: tables, plotting
;; Homepage: https://orgmode.org
;;
;; This file is part of GNU Emacs.
;;
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; Borrows ideas and a couple of lines of code from org-exp.el.

;; Thanks to the Org mailing list for testing and implementation and
;; feature suggestions

;;; Code:

(require 'cl-lib)
(require 'org)
(require 'org-table)

(declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg))
(declare-function gnuplot-mode "ext:gnuplot" ())
(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ())

(defvar org-plot/gnuplot-default-options
  '((:plot-type . 2d)
    (:with . lines)
    (:ind . 0))
  "Default options to gnuplot used by `org-plot/gnuplot'.")

(defvar org-plot-timestamp-fmt nil)

(defun org-plot/add-options-to-plist (p options)
  "Parse an OPTIONS line and set values in the property list P.
Returns the resulting property list."
  (when options
    (let ((op '(("type"      . :plot-type)
		("script"    . :script)
		("line"      . :line)
		("set"       . :set)
		("title"     . :title)
		("ind"       . :ind)
		("deps"      . :deps)
		("with"      . :with)
		("file"      . :file)
		("labels"    . :labels)
		("map"       . :map)
		("timeind"   . :timeind)
		("timefmt"   . :timefmt)
		("min"       . :ymin)
		("max"       . :ymax)
		("ymin"      . :ymin)
		("xmax"      . :xmax)
		("ticks"     . :ticks)
		("trans"     . :transpose)
		("transpose" . :transpose)))
	  (multiples '("set" "line"))
	  (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
	  (start 0))
      (dolist (o op)
	(if (member (car o) multiples) ;; keys with multiple values
	    (while (string-match
		    (concat (regexp-quote (car o)) regexp)
		    options start)
	      (setq start (match-end 0))
	      (setq p (plist-put p (cdr o)
				 (cons (car (read-from-string
					     (match-string 1 options)))
				       (plist-get p (cdr o)))))
	      p)
	  (if (string-match (concat (regexp-quote (car o)) regexp)
			    options)
	      (setq p (plist-put p (cdr o)
				 (car (read-from-string
				       (match-string 1 options))))))))))
  p)

(defun org-plot/goto-nearest-table ()
  "Move the point forward to the beginning of nearest table.
Return value is the point at the beginning of the table."
  (interactive) (move-beginning-of-line 1)
  (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
  (goto-char (org-table-begin)))

(defun org-plot/collect-options (&optional params)
  "Collect options from an org-plot `#+Plot:' line.
Accepts an optional property list PARAMS, to which the options
will be added.  Returns the resulting property list."
  (interactive)
  (let ((line (thing-at-point 'line)))
    (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
	(org-plot/add-options-to-plist params (match-string 1 line))
      params)))

(defun org-plot-quote-timestamp-field (s)
  "Convert field S from timestamp to Unix time and export to gnuplot."
  (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))

(defun org-plot-quote-tsv-field (s)
  "Quote field S for export to gnuplot."
  (if (string-match org-table-number-regexp s) s
    (if (string-match org-ts-regexp3 s)
	(org-plot-quote-timestamp-field s)
      (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))

(defun org-plot/gnuplot-to-data (table data-file params)
  "Export TABLE to DATA-FILE in a format readable by gnuplot.
Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
  (with-temp-file
      data-file
    (setq-local org-plot-timestamp-fmt (or
					(plist-get params :timefmt)
					"%Y-%m-%d-%H:%M:%S"))
    (insert (orgtbl-to-generic
	     table
	     (org-combine-plists
	      '(:sep "\t" :fmt org-plot-quote-tsv-field)
	      params))))
  nil)

(defun org-plot/gnuplot-to-grid-data (table data-file params)
  "Export the data in TABLE to DATA-FILE for gnuplot.
This means in a format appropriate for grid plotting by gnuplot.
PARAMS specifies which columns of TABLE should be plotted as independent
and dependent variables."
  (interactive)
  (let* ((ind (- (plist-get params :ind) 1))
	 (deps (if (plist-member params :deps)
		   (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
		 (let (collector)
		   (dotimes (col (length (nth 0 table)))
		     (setf collector (cons col collector)))
		   collector)))
	 (counter 0)
	 row-vals)
    (when (>= ind 0) ;; collect values of ind col
      (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
			       (cons counter (nth ind row)))
			     table)))
    (when (or deps (>= ind 0)) ;; remove non-plotting columns
      (setf deps (delq ind deps))
      (setf table (mapcar (lambda (row)
			    (dotimes (col (length row))
			      (unless (memq col deps)
				(setf (nth col row) nil)))
			    (delq nil row))
			  table)))
    ;; write table to gnuplot grid datafile format
    (with-temp-file data-file
      (let ((num-rows (length table)) (num-cols (length (nth 0 table)))
	    (gnuplot-row (lambda (col row value)
			   (setf col (+ 1 col)) (setf row (+ 1 row))
			   (format "%f  %f  %f\n%f  %f  %f\n"
				   col (- row 0.5) value ;; lower edge
				   col (+ row 0.5) value))) ;; upper edge
	    front-edge back-edge)
	(dotimes (col num-cols)
	  (dotimes (row num-rows)
	    (setf back-edge
		  (concat back-edge
			  (funcall gnuplot-row (- col 1) row
				   (string-to-number (nth col (nth row table))))))
	    (setf front-edge
		  (concat front-edge
			  (funcall gnuplot-row col row
				   (string-to-number (nth col (nth row table)))))))
	  ;; only insert once per row
	  (insert back-edge) (insert "\n") ;; back edge
	  (insert front-edge) (insert "\n") ;; front edge
	  (setf back-edge "") (setf front-edge ""))))
    row-vals))

(defun org--plot/values-stats (nums &optional hard-min hard-max)
  "From a list of NUMS return a plist containing some rudamentry statistics on the
values, namely regarding the range."
  (let* ((minimum (or hard-min (apply #'min nums)))
	 (maximum (or hard-max (apply #'max nums)))
	 (range (- maximum minimum))
	 (rangeOrder (ceiling (- 1 (log10 range))))
	 (range-factor (expt 10 rangeOrder))
	 (nice-min (/ (float (floor (* minimum range-factor))) range-factor))
	 (nice-max (/ (float (ceiling (* maximum range-factor))) range-factor)))
    `(:min ,minimum :max ,maximum :range ,range
      :range-factor ,range-factor
      :nice-min ,nice-min :nice-max ,nice-max :nice-range ,(- nice-max nice-min))))

(defun org--plot/sensible-tick-num (table &optional hard-min hard-max)
  "From a the values in a TABLE of data, attempt to guess an appropriate number of ticks."
  (let* ((row-data
	  (mapcar (lambda (row) (org--plot/values-stats
			    (mapcar #'string-to-number (cdr row))
			    hard-min
			    hard-max)) table))
	 (row-normalised-ranges (mapcar (lambda (r-data)
					  (let ((val (round (*
							     (plist-get r-data :range-factor)
							     (plist-get r-data :nice-range)))))
					    (if (= (% val 10) 0) (/ val 10) val)))
					row-data))
	 (range-prime-decomposition (mapcar #'org--plot/prime-factors row-normalised-ranges))
	 (weighted-factors (sort (apply #'org--plot/merge-alists #'+ 0
					(mapcar (lambda (factors) (org--plot/item-frequencies factors t))
						range-prime-decomposition))
				 (lambda (a b) (> (cdr a) (cdr b))))))
    (apply #'* (org--plot/nice-frequency-pick weighted-factors))))

(defun org--plot/nice-frequency-pick (frequencies)
  "From a list of frequences, try to sensibly pick a sample of the most frequent."
  ;; TODO this mosly works decently, but counld do with some tweaking to work more consistently.
  (case (length frequencies)
    (1 (list (car (nth 0 frequencies))))
    (2 (if (<= 3 (/ (cdr (nth 0 frequencies))
		    (cdr (nth 1 frequencies))))
	   (make-list 2
		      (car (nth 0 frequencies)))
	 (list (car (nth 0 frequencies))
	       (car (nth 1 frequencies)))))
    (t
     (let* ((total-count (apply #'+ (mapcar #'cdr frequencies)))
	    (n-freq (mapcar (lambda (freq) `(,(car freq) . ,(/ (float (cdr freq)) total-count))) frequencies))
	    (f-pick (list (car (car n-freq))))
	    (1-2-ratio (/ (cdr (nth 0 n-freq))
			  (cdr (nth 1 n-freq))))
	    (2-3-ratio (/ (cdr (nth 1 n-freq))
			  (cdr (nth 2 n-freq))))
	    (1-3-ratio (* 1-2-ratio 2-3-ratio))
	    (1-val (car (nth 0 n-freq)))
	    (2-val (car (nth 1 n-freq)))
	    (3-val (car (nth 2 n-freq))))
       (when (> 1-2-ratio 4) (push 1-val f-pick))
       (when (and (< 1-2-ratio 2-val)
		  (< (* (apply #'* f-pick) 2-val) 30))
	 (push 2-val f-pick))
       (when (and (< 1-3-ratio 3-val)
		  (< (* (apply #'* f-pick) 3-val) 30))
	 (push 3-val f-pick))
       f-pick))))

(defun org--plot/merge-alists (function default alist1 alist2 &rest alists)
  "Using FUNCTION, combine the elements of all given ALISTS. When an element is
only present in one alist, DEFAULT is used as the second argument for the FUNCTION."
  (when (> (length alists) 0)
    (setq alist2 (apply #'org--plot/merge-alists function default alist2 alists)))
  (flet ((keys (alist) (mapcar #'car alist))
	 (lookup (key alist) (or (cdr (assoc key alist)) default)))
    (loop with keys = (union (keys alist1) (keys alist2) :test 'equal)
	  for k in keys collect
	  (cons k (funcall function (lookup k alist1) (lookup k alist2))))))

(defun org--plot/item-frequencies (values &optional normalise)
  "Return an alist indicating the frequency of values in VALUES list."
  (let ((normaliser (if normalise (float (length values)) 1)))
    (cl-loop for (n . m) in (seq-group-by #'identity values)
	     collect (cons n (/ (length m) normaliser)))))

(defun org--plot/prime-factors (value)
  "Return the prime decomposition of VALUE, e.g. for 12, '(3 2 2)"
  (let ((factors '(1)) (i 1))
    (while (/= 1 value)
      (setq i (1+ i))
      (when (eq 0 (% value i))
	(push i factors)
	(setq value (/ value i))
	(setq i (1- i))
	))
    (subseq factors 0 -1)))

(defcustom org-plot/gnuplot-script-preamble ""
  "String or function which provides content to be inserted into the GNUPlot
script before the plot command. Not that this is in addition to, not instead of
other content generated in `org-plot/gnuplot-script'.
If a function, it is called with the plot type as the argument."
  :group 'org-plot
  :type '(choice string function))

(defcustom org-plot/preset-plot-types
  '((2d (lambda (data-file num-cols params plot-str)
	  (let* ((type (plist-get params :plot-type))
		 (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
		 (ind (plist-get params :ind))
		 (deps (if (plist-member params :deps) (plist-get params :deps)))
		 (text-ind (plist-get params :textind))
		 (col-labels (plist-get params :labels))
		 res)
	    (dotimes (col num-cols res)
	      (unless (and (eq type '2d)
			   (or (and ind (equal (1+ col) ind))
			       (and deps (not (member (1+ col) deps)))))
		(setf res
		      (cons
		       (format plot-str data-file
			       (or (and ind (> ind 0)
					(not text-ind)
					(format "%d:" ind)) "")
			       (1+ col)
			       (if text-ind (format ":xticlabel(%d)" ind) "")
			       with
			       (or (nth col col-labels)
				   (format "%d" (1+ col))))
		       res)))))))
    (3d (lambda (data-file num-cols params plot-str)
	  (let* ((type (plist-get params :plot-type))
		 (with (if (eq type 'grid) 'pm3d (plist-get params :with))))
	    (list (format "'%s' matrix with %s title ''"
			  data-file with)))))
    (grid (lambda (data-file num-cols params plot-str)
	    (let* ((type (plist-get params :plot-type))
		   (with (if (eq type 'grid) 'pm3d (plist-get params :with))))
	    (list (format "'%s' with %s title ''"
			  data-file with)))))
    (radar (lambda (data-file num-cols params plot-str)
	     (list (org--plot/radar table params)))))
  "List of plot presets with the type name as the car, and a function
which yeilds plot-lines (a list of strings) as the cdr.
The parameters of `org-plot/gnuplot-script' and PLOT-STR are passed to
that function. i.e. it is called with the following arguments:
  DATA-FILE NUM-COLS PARAMS PLOT-STR"
  :group 'org-plot
  :type '(alist :value-type (symbol group)))

(defvar org--plot/radar-template
  "### spider plot/chart with gnuplot
# also known as: radar chart, web chart, star chart, cobweb chart,
#                radar plot,  web plot,  star plot,  cobweb plot,  etc. ...
set datafile separator ' '
set size square
unset tics
set angles degree
set key bmargin center horizontal
unset border

# Load data and settup
load \"%s\"

# General settings
DataColCount = words($Data[1])-1
AxesCount = |$Data|-HeaderLines
AngleOffset = 90
Max = 1
d=0.1*Max
Direction = -1   # counterclockwise=1, clockwise = -1

# Tic settings
TicCount = %s
TicOffset = 0.1
TicValue(axis,i) = real(i)*(word($Settings[axis],3)-word($Settings[axis],2)) \\
	  / word($Settings[axis],4)+word($Settings[axis],2)
TicLabelPosX(axis,i) = PosX(axis,i/TicCount) + PosY(axis, TicOffset)
TicLabelPosY(axis,i) = PosY(axis,i/TicCount) - PosX(axis, TicOffset)
TicLen = 0.03
TicdX(axis,i) = 0.5*TicLen*cos(alpha(axis)-90)
TicdY(axis,i) = 0.5*TicLen*sin(alpha(axis)-90)

# Label
LabOffset = 0.10
LabX(axis) = PosX(axis+1,Max+2*d) + PosY(axis, LabOffset)
LabY(axis) = PosY($0+1,Max+2*d)

# Functions
alpha(axis) = (axis-1)*Direction*360.0/AxesCount+AngleOffset
PosX(axis,R) = R*cos(alpha(axis))
PosY(axis,R) = R*sin(alpha(axis))
Scale(axis,value) = real(value-word($Settings[axis],2))/(word($Settings[axis],3)-word($Settings[axis],2))

# Spider settings
set style arrow 1 dt 1 lw 1.0 @fgal head filled size 0.06,25     # style for axes
set style arrow 2 dt 2 lw 0.5 @fgal nohead   # style for weblines
set style arrow 3 dt 1 lw 1 @fgal nohead     # style for axis tics
set samples AxesCount
set isosamples TicCount
set urange[1:AxesCount]
set vrange[1:TicCount]
set style fill transparent solid 0.2

set xrange[-Max-4*d:Max+4*d]
set yrange[-Max-4*d:Max+4*d]
plot \\
    '+' u (0):(0):(PosX($0,Max+d)):(PosY($0,Max+d)) w vec as 1 not, \\
    $Data u (LabX($0)): \\
	(LabY($0)):1 every ::HeaderLines w labels center enhanced @fgt not, \\
    for [i=1:DataColCount] $Data u (PosX($0+1,Scale($0+1,column(i+1)))): \\
	(PosY($0+1,Scale($0+1,column(i+1)))) every ::HeaderLines w filledcurves lt i title word($Data[1],i+1), \\
%s
#    '++' u (PosX($1,$2/TicCount)-TicdX($1,$2/TicCount)): \\
#        (PosY($1,$2/TicCount)-TicdY($1,$2/TicCount)): \\
#        (2*TicdX($1,$2/TicCount)):(2*TicdY($1,$2/TicCount)) \\
#        w vec as 3 not, \\
### end of code
")

(defvar org--plot/radar-ticks
  "    '++' u (PosX($1,$2/TicCount)):(PosY($1,$2/TicCount)): \\
	(PosX($1+1,$2/TicCount)-PosX($1,$2/TicCount)):  \\
	(PosY($1+1,$2/TicCount)-PosY($1,$2/TicCount)) w vec as 2 not, \\
    '++' u (TicLabelPosX(%s,$2)):(TicLabelPosY(%s,$2)): \\
	(sprintf('%%g',TicValue(%s,$2))) w labels font ',8' @fgat not")

(defvar org--plot/radar-setup-template
  "# Data
$Data <<HEREHAVESOMEDATA
%s
HEREHAVESOMEDATA
HeaderLines = 1

# Settings for scale and offset adjustments
# axis min max tics axisLabelXoff axisLabelYoff
$Settings <<EOD
%s
EOD
")

(defun org--plot/radar (table params)
  (let* ((data
	  (concat "\"" (s-join "\" \"" (plist-get params :labels)) "\""
		  "\n"
		  (s-join "\n"
			  (mapcar (lambda (row)
				    (format
				     "\"%s\" %s"
				     (car row)
				     (s-join " " (cdr row))))
				  table))))
	 (ticks (or (plist-get params :ticks)
		    (org--plot/sensible-tick-num table
						 (plist-get params :ymin)
						 (plist-get params :ymax))))
	 (settings
	  (s-join "\n"
		  (mapcar (lambda (row)
			    (let ((data (org--plot/values-stats
					 (mapcar #'string-to-number (cdr row)))))
			      (format
			       "\"%s\" %s %s %s"
			       (car row)
			       (or (plist-get params :ymin)
				   (plist-get data :nice-min))
			       (or (plist-get params :ymax)
				   (plist-get data :nice-max))
			       (if (eq ticks 0) 2 ticks)
			       )))
			  table)))
	 (setup-file (make-temp-file "org-plot-setup")))
    (f-write-text (format org--plot/radar-setup-template data settings)
		  'utf-8 setup-file)
    (format org--plot/radar-template
	    setup-file
	    (if (eq ticks 0) 2 ticks)
	    (if (eq ticks 0) ""
	      (apply #'format org--plot/radar-ticks
		     (make-list 3 (if (and (plist-get params :ymin)
					   (plist-get params :ymax))
				      ;; FIXME multi-drawing of tick labels with "1"
				      "1" "$1")))))))

(defcustom org-plot/gnuplot-term-extra ""
  "String or function which provides the extra term options.
E.g. a value of \"size 1050,650\" would cause
\"set term ... size 1050,650\" to be used.
If a function, it is called with the plot type as the argument."
  :group 'org-plot
  :type '(choice string function))

(defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
  "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
NUM-COLS controls the number of columns plotted in a 2-d plot.
Optional argument PREFACE returns only option parameters in a
manner suitable for prepending to a user-specified script."
  (let* ((type (plist-get params :plot-type))
	 (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
	 (sets (plist-get params :set))
	 (lines (plist-get params :line))
	 (map (plist-get params :map))
	 (title (plist-get params :title))
	 (file (plist-get params :file))
	 (ind (plist-get params :ind))
	 (time-ind (plist-get params :timeind))
	 (timefmt (plist-get params :timefmt))
	 (text-ind (plist-get params :textind))
	 (deps (if (plist-member params :deps) (plist-get params :deps)))
	 (col-labels (plist-get params :labels))
	 (x-labels (plist-get params :xlabels))
	 (y-labels (plist-get params :ylabels))
	 (plot-str "'%s' using %s%d%s with %s title '%s'")
	 (plot-cmd (pcase type
		     (`2d "plot")
		     (`3d "splot")
		     (`grid "splot")))
	 (script "reset")
	 ;; ats = add-to-script
	 (ats (lambda (line) (setf script (concat script "\n" line))))
	 plot-lines)


    ;; handle output file, background, and size
    (funcall ats (format "set term %s %s"
			 (if file (file-name-extension file) "GNUTERM")
			 (if (stringp org-plot/gnuplot-term-extra)
			     org-plot/gnuplot-term-extra
			   (org-plot/gnuplot-term-extra type))))
    (when file ; output file
      (funcall ats (format "set output '%s'" file)))

    (funcall ats
	     (if (stringp org-plot/gnuplot-script-preamble)
		 org-plot/gnuplot-script-preamble
	       (org-plot/gnuplot-script-preamble type)))

    (pcase type				; type
      (`2d ())
      (`3d (when map (funcall ats "set map")))
      (`grid (funcall ats (if map "set pm3d map" "set pm3d"))))
    (when title (funcall ats (format "set title '%s'" title))) ; title
    (mapc ats lines)					       ; line
    (dolist (el sets) (funcall ats (format "set %s" el)))      ; set
    ;; Unless specified otherwise, values are TAB separated.
    (unless (string-match-p "^set datafile separator" script)
      (funcall ats "set datafile separator \"\\t\""))
    (when x-labels			; x labels (xtics)
      (funcall ats
	       (format "set xtics (%s)"
		       (mapconcat (lambda (pair)
				    (format "\"%s\" %d" (cdr pair) (car pair)))
				  x-labels ", "))))
    (when y-labels			; y labels (ytics)
      (funcall ats
	       (format "set ytics (%s)"
		       (mapconcat (lambda (pair)
				    (format "\"%s\" %d" (cdr pair) (car pair)))
				  y-labels ", "))))
    (when time-ind			; timestamp index
      (funcall ats "set xdata time")
      (funcall ats (concat "set timefmt \""
			   (or timefmt	; timefmt passed to gnuplot
			       "%Y-%m-%d-%H:%M:%S") "\"")))
    (unless preface
      (let ((type-func (cadr (assoc type org-plot/preset-plot-types))))
	(when type-func
	  (setq plot-lines
		(funcall type-func data-file num-cols params plot-str))))

      (funcall ats
	       (concat plot-cmd " " (mapconcat #'identity
					       (reverse plot-lines)
					       ",\\\n    "))))
    script))

;;-----------------------------------------------------------------------------
;; facade functions
;;;###autoload
(defun org-plot/gnuplot (&optional params)
  "Plot table using gnuplot.  Gnuplot options can be specified with PARAMS.
If not given options will be taken from the +PLOT
line directly before or after the table."
  (interactive)
  (require 'gnuplot)
  (save-window-excursion
    (delete-other-windows)
    (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running
      (with-current-buffer "*gnuplot*"
	(goto-char (point-max))))
    (org-plot/goto-nearest-table)
    ;; Set default options.
    (dolist (pair org-plot/gnuplot-default-options)
      (unless (plist-member params (car pair))
	(setf params (plist-put params (car pair) (cdr pair)))))
    ;; Collect options.
    (save-excursion (while (and (equal 0 (forward-line -1))
				(looking-at "[[:space:]]*#\\+"))
		      (setf params (org-plot/collect-options params))))
    ;; collect table and table information
    (let* ((data-file (make-temp-file "org-plot"))
	   (table (let ((tbl (org-table-to-lisp)))
		    (when (pcase (plist-get params :transpose)
			    ('y   t)
			    ('yes t)
			    ('t   t))
		      (if (not (memq 'hline tbl))
			  (setq tbl (apply #'cl-mapcar #'list tbl))
			;; When present, remove hlines as they can't (currentily) be easily transposed.
			(setq tbl (apply #'cl-mapcar #'list
					 (remove 'hline tbl)))
			(push 'hline (cdr tbl))))
		    tbl))
	   (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table)
			       (nth 0 table)))))
      (run-with-idle-timer 0.1 nil #'delete-file data-file)
      (when (eq (cadr table) 'hline)
	(setf params
	      (plist-put params :labels (car table))) ; headers to labels
	(setf table (delq 'hline (cdr table)))) ; clean non-data from table
      ;; Collect options.
      (save-excursion (while (and (equal 0 (forward-line -1))
				  (looking-at "[[:space:]]*#\\+"))
			(setf params (org-plot/collect-options params))))
      ;; Dump table to datafile (very different for grid).
      (pcase (plist-get params :plot-type)
	(`2d   (org-plot/gnuplot-to-data table data-file params))
	(`3d   (org-plot/gnuplot-to-data table data-file params))
	(`grid (let ((y-labels (org-plot/gnuplot-to-grid-data
				table data-file params)))
		 (when y-labels (plist-put params :ylabels y-labels)))))
      ;; Check type of ind column (timestamp? text?)
      (when (eq `2d (plist-get params :plot-type))
	(let* ((ind (1- (plist-get params :ind)))
	       (ind-column (mapcar (lambda (row) (nth ind row)) table)))
	  (cond ((< ind 0) nil) ; ind is implicit
		((cl-every (lambda (el)
			     (string-match org-ts-regexp3 el))
			   ind-column)
		 (plist-put params :timeind t)) ; ind holds timestamps
		((or (string= (plist-get params :with) "hist")
		     (cl-notevery (lambda (el)
				    (string-match org-table-number-regexp el))
				  ind-column))
		 (plist-put params :textind t))))) ; ind holds text
      ;; Write script.
      (with-temp-buffer
	(if (plist-get params :script)	; user script
	    (progn (insert
		    (org-plot/gnuplot-script data-file num-cols params t))
		   (insert "\n")
		   (insert-file-contents (plist-get params :script))
		   (goto-char (point-min))
		   (while (re-search-forward "\\$datafile" nil t)
		     (replace-match data-file nil nil)))
	  (insert (org-plot/gnuplot-script data-file num-cols params)))
	;; Graph table.
	(gnuplot-mode)
	(gnuplot-send-buffer-to-gnuplot))
      ;; Cleanup.
      (bury-buffer (get-buffer "*gnuplot*")))))

(provide 'org-plot)

;; Local variables:
;; generated-autoload-file: "org-loaddefs.el"
;; End:

;;; org-plot.el ends here
debug log:

solving 1b227d698 ...
found 1b227d698 in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found fd92a12a1 in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found 52422ea2f in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found ed4cea195 in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found 2a9c0f5bd in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found 207f5d4af in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found f8db45273 in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found 6ff633130 in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found c08bc144e in https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/ ||
	https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/
found 0ff96af67 in /path/to/orgmode.git
preparing index
index prepared:
100644 0ff96af670831bf984ada3c843c6ec8d60a76174	lisp/org-plot.el

applying [1/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index 0ff96af67..c08bc144e 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for c08bc144e
index at:
100644 c08bc144e8a4c773daebe0104ad4ae4f58348264	lisp/org-plot.el

applying [2/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index c08bc144e..6ff633130 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for 6ff633130
index at:
100644 6ff633130f27b6a123dbd455186c441cf379246f	lisp/org-plot.el

applying [3/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index 6ff633130..f8db45273 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for f8db45273
index at:
100644 f8db452731944fd12612d41709fa0382f7a3ea2c	lisp/org-plot.el

applying [4/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index f8db45273..207f5d4af 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for 207f5d4af
index at:
100644 207f5d4af0f9e9abdbca10cddb693439f4549aac	lisp/org-plot.el

applying [5/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index 207f5d4af..2a9c0f5bd 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for 2a9c0f5bd
index at:
100644 2a9c0f5bd3fa8edf912ceaacb8ef32dbc487c8e3	lisp/org-plot.el

applying [6/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index 2a9c0f5bd..ed4cea195 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for ed4cea195
index at:
100644 ed4cea1953c6f9d7da3d4c7dc38deb053cedf8e5	lisp/org-plot.el

applying [7/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index ed4cea195..52422ea2f 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for 52422ea2f
index at:
100644 52422ea2fd42e5aa3c7b73780d4827e3db5681b2	lisp/org-plot.el

applying [8/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index 52422ea2f..fd92a12a1 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for fd92a12a1
index at:
100644 fd92a12a17d40d419b123d87deffe06c2b389edd	lisp/org-plot.el

applying [9/18] https://yhetil.org/orgmode/87lffv8oy5.fsf@gmail.com/
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
index fd92a12a1..1b227d698 100644

Checking patch lisp/org-plot.el...
Applied patch lisp/org-plot.el cleanly.

skipping https://yhetil.org/orgmode/87lfhbhfhe.fsf@gmail.com/ for 1b227d698
index at:
100644 1b227d698130a2b662eea89f465df389c1978616	lisp/org-plot.el

unofficial mirror of emacs-orgmode@gnu.org

This inbox may be cloned and mirrored by anyone:

	git clone --mirror https://yhetil.org/orgmode/0 orgmode/git/0.git

	# If you have public-inbox 1.1+ installed, you may
	# initialize and index your mirror using the following commands:
	public-inbox-init -V2 orgmode orgmode/ https://yhetil.org/orgmode \
		emacs-orgmode@gnu.org
	public-inbox-index orgmode

Example config snippet for mirrors.
Newsgroups are available over NNTP:
	nntp://news.yhetil.org/yhetil.emacs.orgmode
	nntp://news.gmane.io/gmane.emacs.orgmode


AGPL code for this site: git clone https://public-inbox.org/public-inbox.git