config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

ob-gnuplot.el (12731B)


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