Ediff: add some missing documentation
[emacs.git] / lisp / org / org-table.el
blob8dc648eaecdb5886d09f97c01ab59194b0fc4d77
1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
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 <https://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the table editor and spreadsheet for Org mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
35 ;;; Code:
37 (require 'cl-lib)
38 (require 'org)
40 (declare-function org-element-at-point "org-element" ())
41 (declare-function org-element-contents "org-element" (element))
42 (declare-function org-element-extract-element "org-element" (element))
43 (declare-function org-element-interpret-data "org-element" (data))
44 (declare-function org-element-lineage "org-element"
45 (blob &optional types with-self))
46 (declare-function org-element-map "org-element"
47 (data types fun
48 &optional info first-match no-recursion with-affiliated))
49 (declare-function org-element-parse-buffer "org-element"
50 (&optional granularity visible-only))
51 (declare-function org-element-property "org-element" (property element))
52 (declare-function org-element-type "org-element" (element))
54 (declare-function org-export-create-backend "ox" (&rest rest) t)
55 (declare-function org-export-data-with-backend "ox" (data backend info))
56 (declare-function org-export-filter-apply-functions "ox"
57 (filters value info))
58 (declare-function org-export-first-sibling-p "ox" (blob info))
59 (declare-function org-export-get-backend "ox" (name))
60 (declare-function org-export-get-environment "ox"
61 (&optional backend subtreep ext-plist))
62 (declare-function org-export-install-filters "ox" (info))
63 (declare-function org-export-table-has-special-column-p "ox" (table))
64 (declare-function org-export-table-row-is-special-p "ox" (table-row info))
66 (declare-function calc-eval "calc" (str &optional separator &rest args))
68 (defvar constants-unit-system)
69 (defvar org-element-use-cache)
70 (defvar org-export-filters-alist)
71 (defvar org-table-follow-field-mode)
72 (defvar orgtbl-mode) ; defined below
73 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
74 (defvar sort-fold-case)
76 (defvar orgtbl-after-send-table-hook nil
77 "Hook for functions attaching to `C-c C-c', if the table is sent.
78 This can be used to add additional functionality after the table is sent
79 to the receiver position, otherwise, if table is not sent, the functions
80 are not run.")
82 (defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
84 (defcustom orgtbl-optimized t
85 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
87 In the optimized version, the table editor takes over all simple keys that
88 normally just insert a character. In tables, the characters are inserted
89 in a way to minimize disturbing the table structure (i.e. in overwrite mode
90 for empty fields). Outside tables, the correct binding of the keys is
91 restored.
93 Changing this variable requires a restart of Emacs to become
94 effective."
95 :group 'org-table
96 :type 'boolean)
98 (defcustom orgtbl-radio-table-templates
99 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
100 % END RECEIVE ORGTBL %n
101 \\begin{comment}
102 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
103 | | |
104 \\end{comment}\n")
105 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
106 @c END RECEIVE ORGTBL %n
107 @ignore
108 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
109 | | |
110 @end ignore\n")
111 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
112 <!-- END RECEIVE ORGTBL %n -->
113 <!--
114 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
115 | | |
116 -->\n")
117 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
118 #+ END RECEIVE ORGTBL %n
120 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
121 | | |
123 "Templates for radio tables in different major modes.
124 Each template must define lines that will be treated as a comment and that
125 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
126 lines where \"%n\" will be replaced with the name of the table during
127 insertion of the template. The transformed table will later be inserted
128 between these lines.
130 The template should also contain a minimal table in a multiline comment.
131 If multiline comments are not possible in the buffer language,
132 you can pack it into a string that will not be used when the code
133 is compiled or executed. Above the table will you need a line with
134 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
135 convert the table into a data structure useful in the
136 language of the buffer. Check the manual for the section on
137 \"Translator functions\", and more generally check out
138 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
140 All occurrences of %n in a template will be replaced with the name of the
141 table, obtained by prompting the user."
142 :group 'org-table
143 :type '(repeat
144 (list (symbol :tag "Major mode")
145 (string :tag "Format"))))
147 (defgroup org-table-settings nil
148 "Settings for tables in Org mode."
149 :tag "Org Table Settings"
150 :group 'org-table)
152 (defcustom org-table-default-size "5x2"
153 "The default size for newly created tables, Columns x Rows."
154 :group 'org-table-settings
155 :type 'string)
157 (defcustom org-table-number-regexp
158 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
159 "Regular expression for recognizing numbers in table columns.
160 If a table column contains mostly numbers, it will be aligned to the
161 right. If not, it will be aligned to the left.
163 The default value of this option is a regular expression which allows
164 anything which looks remotely like a number as used in scientific
165 context. For example, all of the following will be considered a
166 number:
167 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
169 Other options offered by the customize interface are more restrictive."
170 :group 'org-table-settings
171 :type '(choice
172 (const :tag "Positive Integers"
173 "^[0-9]+$")
174 (const :tag "Integers"
175 "^[-+]?[0-9]+$")
176 (const :tag "Floating Point Numbers"
177 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
178 (const :tag "Floating Point Number or Integer"
179 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
180 (const :tag "Exponential, Floating point, Integer"
181 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
182 (const :tag "Very General Number-Like, including hex and Calc radix"
183 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
184 (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
185 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
186 (string :tag "Regexp:")))
188 (defcustom org-table-number-fraction 0.5
189 "Fraction of numbers in a column required to make the column align right.
190 In a column all non-white fields are considered. If at least
191 this fraction of fields is matched by `org-table-number-regexp',
192 alignment to the right border applies."
193 :group 'org-table-settings
194 :type 'number)
196 (defgroup org-table-editing nil
197 "Behavior of tables during editing in Org mode."
198 :tag "Org Table Editing"
199 :group 'org-table)
201 (defcustom org-table-automatic-realign t
202 "Non-nil means automatically re-align table when pressing TAB or RETURN.
203 When nil, aligning is only done with `\\[org-table-align]', or after column
204 removal/insertion."
205 :group 'org-table-editing
206 :type 'boolean)
208 (defcustom org-table-auto-blank-field t
209 "Non-nil means automatically blank table field when starting to type into it.
210 This only happens when typing immediately after a field motion
211 command (TAB, S-TAB or RET)."
212 :group 'org-table-editing
213 :type 'boolean)
215 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
216 "Non-nil means automatically exit the follow mode.
217 When nil, the follow mode will stay on and be active in any table
218 the cursor enters. Since the table follow filed mode messes with the
219 window configuration, it is not recommended to set this variable to nil,
220 except maybe locally in a special file that has mostly tables with long
221 fields."
222 :group 'org-table
223 :version "24.1"
224 :type 'boolean)
226 (defcustom org-table-fix-formulas-confirm nil
227 "Whether the user should confirm when Org fixes formulas."
228 :group 'org-table-editing
229 :version "24.1"
230 :type '(choice
231 (const :tag "with yes-or-no" yes-or-no-p)
232 (const :tag "with y-or-n" y-or-n-p)
233 (const :tag "no confirmation" nil)))
234 (put 'org-table-fix-formulas-confirm
235 'safe-local-variable
236 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
238 (defcustom org-table-tab-jumps-over-hlines t
239 "Non-nil means tab in the last column of a table with jump over a hline.
240 If a horizontal separator line is following the current line,
241 `org-table-next-field' can either create a new row before that line, or jump
242 over the line. When this option is nil, a new line will be created before
243 this line."
244 :group 'org-table-editing
245 :type 'boolean)
247 (defgroup org-table-calculation nil
248 "Options concerning tables in Org mode."
249 :tag "Org Table Calculation"
250 :group 'org-table)
252 (defcustom org-table-use-standard-references 'from
253 "Non-nil means using table references like B3 instead of @3$2.
254 Possible values are:
255 nil never use them
256 from accept as input, do not present for editing
257 t accept as input and present for editing"
258 :group 'org-table-calculation
259 :type '(choice
260 (const :tag "Never, don't even check user input for them" nil)
261 (const :tag "Always, both as user input, and when editing" t)
262 (const :tag "Convert user input, don't offer during editing" from)))
264 (defcustom org-table-copy-increment t
265 "Non-nil means increment when copying current field with \
266 `\\[org-table-copy-down]'."
267 :group 'org-table-calculation
268 :version "26.1"
269 :package-version '(Org . "8.3")
270 :type '(choice
271 (const :tag "Use the difference between the current and the above fields" t)
272 (integer :tag "Use a number" 1)
273 (const :tag "Don't increment the value when copying a field" nil)))
275 (defcustom org-calc-default-modes
276 '(calc-internal-prec 12
277 calc-float-format (float 8)
278 calc-angle-mode deg
279 calc-prefer-frac nil
280 calc-symbolic-mode nil
281 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
282 calc-display-working-message t
284 "List with Calc mode settings for use in `calc-eval' for table formulas.
285 The list must contain alternating symbols (Calc modes variables and values).
286 Don't remove any of the default settings, just change the values. Org mode
287 relies on the variables to be present in the list."
288 :group 'org-table-calculation
289 :type 'plist)
291 (defcustom org-table-duration-custom-format 'hours
292 "Format for the output of calc computations like $1+$2;t.
293 The default value is `hours', and will output the results as a
294 number of hours. Other allowed values are `seconds', `minutes' and
295 `days', and the output will be a fraction of seconds, minutes or
296 days. `hh:mm' selects to use hours and minutes, ignoring seconds.
297 The `U' flag in a table formula will select this specific format for
298 a single formula."
299 :group 'org-table-calculation
300 :version "24.1"
301 :type '(choice (symbol :tag "Seconds" 'seconds)
302 (symbol :tag "Minutes" 'minutes)
303 (symbol :tag "Hours " 'hours)
304 (symbol :tag "Days " 'days)
305 (symbol :tag "HH:MM " 'hh:mm)))
307 (defcustom org-table-duration-hour-zero-padding t
308 "Non-nil means hours in table duration computations should be zero-padded.
309 So this is about 08:32:34 versus 8:33:34."
310 :group 'org-table-calculation
311 :version "26.1"
312 :package-version '(Org . "9.1")
313 :type 'boolean
314 :safe #'booleanp)
316 (defcustom org-table-formula-field-format "%s"
317 "Format for fields which contain the result of a formula.
318 For example, using \"~%s~\" will display the result within tilde
319 characters. Beware that modifying the display can prevent the
320 field from being used in another formula."
321 :group 'org-table-settings
322 :version "24.1"
323 :type 'string)
325 (defcustom org-table-formula-evaluate-inline t
326 "Non-nil means TAB and RET evaluate a formula in current table field.
327 If the current field starts with an equal sign, it is assumed to be a formula
328 which should be evaluated as described in the manual and in the documentation
329 string of the command `org-table-eval-formula'. This feature requires the
330 Emacs calc package.
331 When this variable is nil, formula calculation is only available through
332 the command `\\[org-table-eval-formula]'."
333 :group 'org-table-calculation
334 :type 'boolean)
336 (defcustom org-table-formula-use-constants t
337 "Non-nil means interpret constants in formulas in tables.
338 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
339 by the value given in `org-table-formula-constants', or by a value obtained
340 from the `constants.el' package."
341 :group 'org-table-calculation
342 :type 'boolean)
344 (defcustom org-table-formula-constants nil
345 "Alist with constant names and values, for use in table formulas.
346 The car of each element is a name of a constant, without the `$' before it.
347 The cdr is the value as a string. For example, if you'd like to use the
348 speed of light in a formula, you would configure
350 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
352 and then use it in an equation like `$1*$c'.
354 Constants can also be defined on a per-file basis using a line like
356 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
357 :group 'org-table-calculation
358 :type '(repeat
359 (cons (string :tag "name")
360 (string :tag "value"))))
362 (defcustom org-table-allow-automatic-line-recalculation t
363 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
364 \\<org-mode-map>\
365 Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
366 are pressed in the line."
367 :group 'org-table-calculation
368 :type 'boolean)
370 (defcustom org-table-relative-ref-may-cross-hline t
371 "Non-nil means relative formula references may cross hlines.
372 Here are the allowed values:
374 nil Relative references may not cross hlines. They will reference the
375 field next to the hline instead. Coming from below, the reference
376 will be to the field below the hline. Coming from above, it will be
377 to the field above.
378 t Relative references may cross hlines.
379 error An attempt to cross a hline will throw an error.
381 It is probably good to never set this variable to nil, for the sake of
382 portability of tables."
383 :group 'org-table-calculation
384 :type '(choice
385 (const :tag "Allow to cross" t)
386 (const :tag "Stick to hline" nil)
387 (const :tag "Error on attempt to cross" error)))
389 (defcustom org-table-formula-create-columns nil
390 "Non-nil means that evaluation of a field formula can add new
391 columns if an out-of-bounds field is being set."
392 :group 'org-table-calculation
393 :version "26.1"
394 :package-version '(Org . "8.3")
395 :type '(choice
396 (const :tag "Setting an out-of-bounds field generates an error (default)" nil)
397 (const :tag "Setting an out-of-bounds field silently adds columns as needed" t)
398 (const :tag "Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn)
399 (const :tag "When setting an out-of-bounds field, the user is prompted" prompt)))
401 (defgroup org-table-import-export nil
402 "Options concerning table import and export in Org mode."
403 :tag "Org Table Import Export"
404 :group 'org-table)
406 (defcustom org-table-export-default-format "orgtbl-to-tsv"
407 "Default export parameters for `org-table-export'.
408 These can be overridden for a specific table by setting the
409 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
410 radio tables for the different export transformations and
411 available parameters."
412 :group 'org-table-import-export
413 :type 'string)
415 (defcustom org-table-convert-region-max-lines 999
416 "Max lines that `org-table-convert-region' will attempt to process.
418 The function can be slow on larger regions; this safety feature
419 prevents it from hanging emacs."
420 :group 'org-table-import-export
421 :type 'integer
422 :version "26.1"
423 :package-version '(Org . "8.3"))
425 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
426 "Regexp matching a line marked for automatic recalculation.")
428 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
429 "Regexp matching a line marked for recalculation.")
431 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
432 "Regexp matching a line marked for calculation.")
434 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
435 "Regexp matching any line outside an Org table.")
437 (defvar org-table-last-highlighted-reference nil)
439 (defvar org-table-formula-history nil)
441 (defvar org-table-column-names nil
442 "Alist with column names, derived from the `!' line.
443 This variable is initialized with `org-table-analyze'.")
445 (defvar org-table-column-name-regexp nil
446 "Regular expression matching the current column names.
447 This variable is initialized with `org-table-analyze'.")
449 (defvar org-table-local-parameters nil
450 "Alist with parameter names, derived from the `$' line.
451 This variable is initialized with `org-table-analyze'.")
453 (defvar org-table-named-field-locations nil
454 "Alist with locations of named fields.
455 Associations follow the pattern (NAME LINE COLUMN) where
456 NAME is the name of the field as a string,
457 LINE is the number of lines from the beginning of the table,
458 COLUMN is the column of the field, as an integer.
459 This variable is initialized with `org-table-analyze'.")
461 (defvar org-table-current-line-types nil
462 "Table row types in current table.
463 This variable is initialized with `org-table-analyze'.")
465 (defvar org-table-current-begin-pos nil
466 "Current table begin position, as a marker.
467 This variable is initialized with `org-table-analyze'.")
469 (defvar org-table-current-ncol nil
470 "Number of columns in current table.
471 This variable is initialized with `org-table-analyze'.")
473 (defvar org-table-dlines nil
474 "Vector of data line line numbers in the current table.
475 Line numbers are counted from the beginning of the table. This
476 variable is initialized with `org-table-analyze'.")
478 (defvar org-table-hlines nil
479 "Vector of hline line numbers in the current table.
480 Line numbers are counted from the beginning of the table. This
481 variable is initialized with `org-table-analyze'.")
483 (defconst org-table-range-regexp
484 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
485 ;; 1 2 3 4 5
486 "Regular expression for matching ranges in formulas.")
488 (defconst org-table-range-regexp2
489 (concat
490 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
491 "\\.\\."
492 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
493 "Match a range for reference display.")
495 (defconst org-table-translate-regexp
496 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
497 "Match a reference that needs translation, for reference display.")
499 (defmacro org-table-save-field (&rest body)
500 "Save current field; execute BODY; restore field.
501 Field is restored even in case of abnormal exit."
502 (declare (debug (body)))
503 (org-with-gensyms (line column)
504 `(let ((,line (copy-marker (line-beginning-position)))
505 (,column (org-table-current-column)))
506 (unwind-protect
507 (progn ,@body)
508 (goto-char ,line)
509 (org-table-goto-column ,column)
510 (set-marker ,line nil)))))
512 ;;;###autoload
513 (defun org-table-create-with-table.el ()
514 "Use the table.el package to insert a new table.
515 If there is already a table at point, convert between Org tables
516 and table.el tables."
517 (interactive)
518 (require 'table)
519 (cond
520 ((org-at-table.el-p)
521 (if (y-or-n-p "Convert table to Org table? ")
522 (org-table-convert)))
523 ((org-at-table-p)
524 (when (y-or-n-p "Convert table to table.el table? ")
525 (org-table-align)
526 (org-table-convert)))
527 (t (call-interactively 'table-insert))))
529 ;;;###autoload
530 (defun org-table-create-or-convert-from-region (arg)
531 "Convert region to table, or create an empty table.
532 If there is an active region, convert it to a table, using the function
533 `org-table-convert-region'. See the documentation of that function
534 to learn how the prefix argument is interpreted to determine the field
535 separator.
536 If there is no such region, create an empty table with `org-table-create'."
537 (interactive "P")
538 (if (org-region-active-p)
539 (org-table-convert-region (region-beginning) (region-end) arg)
540 (org-table-create arg)))
542 ;;;###autoload
543 (defun org-table-create (&optional size)
544 "Query for a size and insert a table skeleton.
545 SIZE is a string Columns x Rows like for example \"3x2\"."
546 (interactive "P")
547 (unless size
548 (setq size (read-string
549 (concat "Table size Columns x Rows [e.g. "
550 org-table-default-size "]: ")
551 "" nil org-table-default-size)))
553 (let* ((pos (point))
554 (indent (make-string (current-column) ?\ ))
555 (split (org-split-string size " *x *"))
556 (rows (string-to-number (nth 1 split)))
557 (columns (string-to-number (car split)))
558 (line (concat (apply 'concat indent "|" (make-list columns " |"))
559 "\n")))
560 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
561 (point-at-bol) (point)))
562 (beginning-of-line 1)
563 (newline))
564 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
565 (dotimes (_ rows) (insert line))
566 (goto-char pos)
567 (if (> rows 1)
568 ;; Insert a hline after the first row.
569 (progn
570 (end-of-line 1)
571 (insert "\n|-")
572 (goto-char pos)))
573 (org-table-align)))
575 ;;;###autoload
576 (defun org-table-convert-region (beg0 end0 &optional separator)
577 "Convert region to a table.
579 The region goes from BEG0 to END0, but these borders will be moved
580 slightly, to make sure a beginning of line in the first line is included.
582 SEPARATOR specifies the field separator in the lines. It can have the
583 following values:
585 (4) Use the comma as a field separator
586 (16) Use a TAB as field separator
587 (64) Prompt for a regular expression as field separator
588 integer When a number, use that many spaces, or a TAB, as field separator
589 regexp When a regular expression, use it to match the separator
590 nil When nil, the command tries to be smart and figure out the
591 separator in the following way:
592 - when each line contains a TAB, assume TAB-separated material
593 - when each line contains a comma, assume CSV material
594 - else, assume one or more SPACE characters as separator."
595 (interactive "r\nP")
596 (let* ((beg (min beg0 end0))
597 (end (max beg0 end0))
599 (if (> (count-lines beg end) org-table-convert-region-max-lines)
600 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
601 org-table-convert-region-max-lines)
602 (if (equal separator '(64))
603 (setq separator (read-regexp "Regexp for field separator")))
604 (goto-char beg)
605 (beginning-of-line 1)
606 (setq beg (point-marker))
607 (goto-char end)
608 (if (bolp) (backward-char 1) (end-of-line 1))
609 (setq end (point-marker))
610 ;; Get the right field separator
611 (unless separator
612 (goto-char beg)
613 (setq separator
614 (cond
615 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
616 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
617 (t 1))))
618 (goto-char beg)
619 (if (equal separator '(4))
620 (while (< (point) end)
621 ;; parse the csv stuff
622 (cond
623 ((looking-at "^") (insert "| "))
624 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
625 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
626 (replace-match "\\1")
627 (if (looking-at "\"") (insert "\"")))
628 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
629 ((looking-at "[ \t]*,") (replace-match " | "))
630 (t (beginning-of-line 2))))
631 (setq re (cond
632 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
633 ((equal separator '(16)) "^\\|\t")
634 ((integerp separator)
635 (if (< separator 1)
636 (user-error "Number of spaces in separator must be >= 1")
637 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
638 ((stringp separator)
639 (format "^ *\\|%s" separator))
640 (t (error "This should not happen"))))
641 (while (re-search-forward re end t)
642 (replace-match "| " t t)))
643 (goto-char beg)
644 (org-table-align))))
646 ;;;###autoload
647 (defun org-table-import (file arg)
648 "Import FILE as a table.
649 The file is assumed to be tab-separated. Such files can be produced by most
650 spreadsheet and database applications. If no tabs (at least one per line)
651 are found, lines will be split on whitespace into fields."
652 (interactive "f\nP")
653 (or (bolp) (newline))
654 (let ((beg (point))
655 (pm (point-max)))
656 (insert-file-contents file)
657 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
660 ;;;###autoload
661 (defun org-table-export (&optional file format)
662 "Export table to a file, with configurable format.
663 Such a file can be imported into usual spreadsheet programs.
665 FILE can be the output file name. If not given, it will be taken
666 from a TABLE_EXPORT_FILE property in the current entry or higher
667 up in the hierarchy, or the user will be prompted for a file
668 name. FORMAT can be an export format, of the same kind as it
669 used when `orgtbl-mode' sends a table in a different format.
671 The command suggests a format depending on TABLE_EXPORT_FORMAT,
672 whether it is set locally or up in the hierarchy, then on the
673 extension of the given file name, and finally on the variable
674 `org-table-export-default-format'."
675 (interactive)
676 (unless (org-at-table-p) (user-error "No table at point"))
677 (org-table-align) ; Make sure we have everything we need.
678 (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
679 (unless file
680 (setq file (read-file-name "Export table to: "))
681 (unless (or (not (file-exists-p file))
682 (y-or-n-p (format "Overwrite file %s? " file)))
683 (user-error "File not written")))
684 (when (file-directory-p file)
685 (user-error "This is a directory path, not a file"))
686 (when (and (buffer-file-name (buffer-base-buffer))
687 (file-equal-p
688 (file-truename file)
689 (file-truename (buffer-file-name (buffer-base-buffer)))))
690 (user-error "Please specify a file name that is different from current"))
691 (let ((fileext (concat (file-name-extension file) "$"))
692 (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
693 (unless format
694 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
695 "orgtbl-to-html" "orgtbl-to-generic"
696 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
697 "orgtbl-to-unicode"))
698 (deffmt-readable
699 (replace-regexp-in-string
700 "\t" "\\t"
701 (replace-regexp-in-string
702 "\n" "\\n"
703 (or (car (delq nil
704 (mapcar
705 (lambda (f)
706 (and (string-match-p fileext f) f))
707 formats)))
708 org-table-export-default-format)
709 t t) t t)))
710 (setq format
711 (org-completing-read
712 "Format: " formats nil nil deffmt-readable))))
713 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
714 (let ((transform (intern (match-string 1 format)))
715 (params (and (match-end 2)
716 (read (concat "(" (match-string 2 format) ")"))))
717 (table (org-table-to-lisp
718 (buffer-substring-no-properties
719 (org-table-begin) (org-table-end)))))
720 (unless (fboundp transform)
721 (user-error "No such transformation function %s" transform))
722 (let (buf)
723 (with-current-buffer (find-file-noselect file)
724 (setq buf (current-buffer))
725 (erase-buffer)
726 (fundamental-mode)
727 (insert (funcall transform table params) "\n")
728 (save-buffer))
729 (kill-buffer buf))
730 (message "Export done."))
731 (user-error "TABLE_EXPORT_FORMAT invalid")))))
733 (defvar org-table-aligned-begin-marker (make-marker)
734 "Marker at the beginning of the table last aligned.
735 Used to check if cursor still is in that table, to minimize realignment.")
736 (defvar org-table-aligned-end-marker (make-marker)
737 "Marker at the end of the table last aligned.
738 Used to check if cursor still is in that table, to minimize realignment.")
739 (defvar org-table-last-alignment nil
740 "List of flags for flushright alignment, from the last re-alignment.
741 This is being used to correctly align a single field after TAB or RET.")
742 (defvar org-table-last-column-widths nil
743 "List of max width of fields in each column.
744 This is being used to correctly align a single field after TAB or RET.")
745 (defvar-local org-table-formula-debug nil
746 "Non-nil means debug table formulas.
747 When nil, simply write \"#ERROR\" in corrupted fields.")
748 (defvar-local org-table-overlay-coordinates nil
749 "Overlay coordinates after each align of a table.")
751 (defvar org-last-recalc-line nil)
752 (defvar org-table-do-narrow t) ; for dynamic scoping
753 (defconst org-narrow-column-arrow "=>"
754 "Used as display property in narrowed table columns.")
756 ;;;###autoload
757 (defun org-table-align ()
758 "Align the table at point by aligning all vertical bars."
759 (interactive)
760 (let* ((beg (org-table-begin))
761 (end (copy-marker (org-table-end))))
762 (org-table-save-field
763 ;; Make sure invisible characters in the table are at the right
764 ;; place since column widths take them into account.
765 (font-lock-fontify-region beg end)
766 (move-marker org-table-aligned-begin-marker beg)
767 (move-marker org-table-aligned-end-marker end)
768 (goto-char beg)
769 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
770 ;; Table's rows. Separators are replaced by nil. Trailing
771 ;; spaces are also removed.
772 (lines (mapcar (lambda (l)
773 (and (not (string-match-p "\\`[ \t]*|-" l))
774 (let ((l (org-trim l)))
775 (remove-text-properties
776 0 (length l) '(display t org-cwidth t) l)
777 l)))
778 (org-split-string (buffer-substring beg end) "\n")))
779 ;; Get the data fields by splitting the lines.
780 (fields (mapcar (lambda (l) (org-split-string l " *| *"))
781 (remq nil lines)))
782 ;; Compute number of fields in the longest line. If the
783 ;; table contains no field, create a default table.
784 (maxfields (if fields (apply #'max (mapcar #'length fields))
785 (kill-region beg end)
786 (org-table-create org-table-default-size)
787 (user-error "Empty table - created default table")))
788 ;; A list of empty strings to fill any short rows on output.
789 (emptycells (make-list maxfields ""))
790 lengths typenums)
791 ;; Check for special formatting.
792 (dotimes (i maxfields)
793 (let ((column (mapcar (lambda (x) (or (nth i x) "")) fields))
794 fmax falign)
795 ;; Look for an explicit width or alignment.
796 (when (save-excursion
797 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t)
798 (and org-table-do-narrow
799 (re-search-forward
800 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t))))
801 (catch :exit
802 (dolist (cell column)
803 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell)
804 (when (match-end 1) (setq falign (match-string 1 cell)))
805 (when (and org-table-do-narrow (match-end 2))
806 (setq fmax (string-to-number (match-string 2 cell))))
807 (when (or falign fmax) (throw :exit nil)))))
808 ;; Find fields that are wider than FMAX, and shorten them.
809 (when fmax
810 (dolist (x column)
811 (when (> (string-width x) fmax)
812 (org-add-props x nil
813 'help-echo
814 (concat
815 "Clipped table field, use `\\[org-table-edit-field]' to \
816 edit. Full value is:\n"
817 (substring-no-properties x)))
818 (let ((l (length x))
819 (f1 (min fmax
820 (or (string-match org-bracket-link-regexp x)
821 fmax)))
822 (f2 1))
823 (unless (> f1 1)
824 (user-error
825 "Cannot narrow field starting with wide link \"%s\""
826 (match-string 0 x)))
827 (if (= (org-string-width x) l) (setq f2 f1)
828 (setq f2 1)
829 (while (< (org-string-width (substring x 0 f2)) f1)
830 (cl-incf f2)))
831 (add-text-properties f2 l (list 'org-cwidth t) x)
832 (add-text-properties
833 (if (>= (string-width (substring x (1- f2) f2)) 2) (1- f2)
834 (- f2 2))
836 (list 'display org-narrow-column-arrow)
837 x))))))
838 ;; Get the maximum width for each column
839 (push (or fmax (apply #'max 1 (mapcar #'org-string-width column)))
840 lengths)
841 ;; Get the fraction of numbers among non-empty cells to
842 ;; decide about alignment of the column.
843 (if falign (push (equal (downcase falign) "r") typenums)
844 (let ((cnt 0)
845 (frac 0.0))
846 (dolist (x column)
847 (unless (equal x "")
848 (setq frac
849 (/ (+ (* frac cnt)
850 (if (string-match-p org-table-number-regexp x)
853 (cl-incf cnt)))))
854 (push (>= frac org-table-number-fraction) typenums)))))
855 (setq lengths (nreverse lengths))
856 (setq typenums (nreverse typenums))
857 ;; Store alignment of this table, for later editing of single
858 ;; fields.
859 (setq org-table-last-alignment typenums)
860 (setq org-table-last-column-widths lengths)
861 ;; With invisible characters, `format' does not get the field
862 ;; width right So we need to make these fields wide by hand.
863 ;; Invisible characters may be introduced by fontified links,
864 ;; emphasis, macros or sub/superscripts.
865 (when (or (text-property-any beg end 'invisible 'org-link)
866 (text-property-any beg end 'invisible t))
867 (dotimes (i maxfields)
868 (let ((len (nth i lengths)))
869 (dotimes (j (length fields))
870 (let* ((c (nthcdr i (nth j fields)))
871 (cell (car c)))
872 (when (and
873 (stringp cell)
874 (let ((l (length cell)))
875 (or (text-property-any 0 l 'invisible 'org-link cell)
876 (text-property-any beg end 'invisible t)))
877 (< (org-string-width cell) len))
878 (let ((s (make-string (- len (org-string-width cell)) ?\s)))
879 (setcar c (if (nth i typenums) (concat s cell)
880 (concat cell s))))))))))
882 ;; Compute the formats needed for output of the table.
883 (let ((hfmt (concat indent "|"))
884 (rfmt (concat indent "|"))
885 (rfmt1 " %%%s%ds |")
886 (hfmt1 "-%s-+"))
887 (dolist (l lengths (setq hfmt (concat (substring hfmt 0 -1) "|")))
888 (let ((ty (if (pop typenums) "" "-"))) ; Flush numbers right.
889 (setq rfmt (concat rfmt (format rfmt1 ty l)))
890 (setq hfmt (concat hfmt (format hfmt1 (make-string l ?-))))))
891 ;; Replace modified lines only. Check not only contents, but
892 ;; also columns' width.
893 (dolist (l lines)
894 (let ((line
895 (if l (apply #'format rfmt (append (pop fields) emptycells))
896 hfmt))
897 (previous (buffer-substring (point) (line-end-position))))
898 (if (and (equal previous line)
899 (let ((a 0)
900 (b 0))
901 (while (and (progn
902 (setq a (next-single-property-change
903 a 'org-cwidth previous))
904 (setq b (next-single-property-change
905 b 'org-cwidth line)))
906 (eq a b)))
907 (eq a b)))
908 (forward-line)
909 (insert line "\n")
910 (delete-region (point) (line-beginning-position 2))))))
911 (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
912 (goto-char org-table-aligned-begin-marker)
913 (while (org-hide-wide-columns org-table-aligned-end-marker)))
914 (set-marker end nil)
915 (when org-table-overlay-coordinates (org-table-overlay-coordinates))
916 (setq org-table-may-need-update nil)))))
918 ;;;###autoload
919 (defun org-table-begin (&optional table-type)
920 "Find the beginning of the table and return its position.
921 With a non-nil optional argument TABLE-TYPE, return the beginning
922 of a table.el-type table. This function assumes point is on
923 a table."
924 (cond (table-type
925 (org-element-property :post-affiliated (org-element-at-point)))
926 ((save-excursion
927 (and (re-search-backward org-table-border-regexp nil t)
928 (line-beginning-position 2))))
929 (t (point-min))))
931 ;;;###autoload
932 (defun org-table-end (&optional table-type)
933 "Find the end of the table and return its position.
934 With a non-nil optional argument TABLE-TYPE, return the end of
935 a table.el-type table. This function assumes point is on
936 a table."
937 (save-excursion
938 (cond (table-type
939 (goto-char (org-element-property :end (org-element-at-point)))
940 (skip-chars-backward " \t\n")
941 (line-beginning-position 2))
942 ((re-search-forward org-table-border-regexp nil t)
943 (match-beginning 0))
944 ;; When the line right after the table is the last line in
945 ;; the buffer with trailing spaces but no final newline
946 ;; character, be sure to catch the correct ending at its
947 ;; beginning. In any other case, ending is expected to be
948 ;; at point max.
949 (t (goto-char (point-max))
950 (skip-chars-backward " \t")
951 (if (bolp) (point) (line-end-position))))))
953 ;;;###autoload
954 (defun org-table-justify-field-maybe (&optional new)
955 "Justify the current field, text to left, number to right.
956 Optional argument NEW may specify text to replace the current field content."
957 (cond
958 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
959 ((org-at-table-hline-p))
960 ((and (not new)
961 (or (not (eq (marker-buffer org-table-aligned-begin-marker)
962 (current-buffer)))
963 (< (point) org-table-aligned-begin-marker)
964 (>= (point) org-table-aligned-end-marker)))
965 ;; This is not the same table, force a full re-align.
966 (setq org-table-may-need-update t))
968 ;; Realign the current field, based on previous full realign.
969 (let ((pos (point))
970 (col (org-table-current-column)))
971 (when (> col 0)
972 (skip-chars-backward "^|")
973 (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
974 (setq org-table-may-need-update t)
975 (let* ((numbers? (nth (1- col) org-table-last-alignment))
976 (cell (match-string 0))
977 (field (match-string 1))
978 (len (max 1 (- (org-string-width cell) 3)))
979 (properly-closed? (/= (match-beginning 2) (match-end 2)))
980 (fmt (format (if numbers? " %%%ds %s" " %%-%ds %s")
982 (if properly-closed? "|"
983 (setq org-table-may-need-update t)
984 "")))
985 (new-cell
986 (cond ((not new) (format fmt field))
987 ((<= (org-string-width new) len) (format fmt new))
989 (setq org-table-may-need-update t)
990 (format " %s |" new)))))
991 (unless (equal new-cell cell)
992 (let (org-table-may-need-update)
993 (replace-match new-cell t t)))
994 (goto-char pos))))))))
996 ;;;###autoload
997 (defun org-table-next-field ()
998 "Go to the next field in the current table, creating new lines as needed.
999 Before doing so, re-align the table if necessary."
1000 (interactive)
1001 (org-table-maybe-eval-formula)
1002 (org-table-maybe-recalculate-line)
1003 (if (and org-table-automatic-realign
1004 org-table-may-need-update)
1005 (org-table-align))
1006 (let ((end (org-table-end)))
1007 (if (org-at-table-hline-p)
1008 (end-of-line 1))
1009 (condition-case nil
1010 (progn
1011 (re-search-forward "|" end)
1012 (if (looking-at "[ \t]*$")
1013 (re-search-forward "|" end))
1014 (if (and (looking-at "-")
1015 org-table-tab-jumps-over-hlines
1016 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
1017 (goto-char (match-beginning 1)))
1018 (if (looking-at "-")
1019 (progn
1020 (beginning-of-line 0)
1021 (org-table-insert-row 'below))
1022 (if (looking-at " ") (forward-char 1))))
1023 (error
1024 (org-table-insert-row 'below)))))
1026 ;;;###autoload
1027 (defun org-table-previous-field ()
1028 "Go to the previous field in the table.
1029 Before doing so, re-align the table if necessary."
1030 (interactive)
1031 (org-table-justify-field-maybe)
1032 (org-table-maybe-recalculate-line)
1033 (when (and org-table-automatic-realign
1034 org-table-may-need-update)
1035 (org-table-align))
1036 (when (org-at-table-hline-p)
1037 (end-of-line))
1038 (let ((start (org-table-begin))
1039 (origin (point)))
1040 (condition-case nil
1041 (progn
1042 (search-backward "|" start nil 2)
1043 (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)")
1044 (search-backward "|" start)))
1045 (error
1046 (goto-char origin)
1047 (user-error "Cannot move to previous table field"))))
1048 (when (looking-at "| ?")
1049 (goto-char (match-end 0))))
1051 (defun org-table-beginning-of-field (&optional n)
1052 "Move to the beginning of the current table field.
1053 If already at or before the beginning, move to the beginning of the
1054 previous field.
1055 With numeric argument N, move N-1 fields backward first."
1056 (interactive "p")
1057 (let ((pos (point)))
1058 (while (> n 1)
1059 (setq n (1- n))
1060 (org-table-previous-field))
1061 (if (not (re-search-backward "|" (point-at-bol 0) t))
1062 (user-error "No more table fields before the current")
1063 (goto-char (match-end 0))
1064 (and (looking-at " ") (forward-char 1)))
1065 (if (>= (point) pos) (org-table-beginning-of-field 2))))
1067 (defun org-table-end-of-field (&optional n)
1068 "Move to the end of the current table field.
1069 If already at or after the end, move to the end of the next table field.
1070 With numeric argument N, move N-1 fields forward first."
1071 (interactive "p")
1072 (let ((pos (point)))
1073 (while (> n 1)
1074 (setq n (1- n))
1075 (org-table-next-field))
1076 (when (re-search-forward "|" (point-at-eol 1) t)
1077 (backward-char 1)
1078 (skip-chars-backward " ")
1079 (if (and (equal (char-before (point)) ?|) (looking-at " "))
1080 (forward-char 1)))
1081 (if (<= (point) pos) (org-table-end-of-field 2))))
1083 ;;;###autoload
1084 (defun org-table-next-row ()
1085 "Go to the next row (same column) in the current table.
1086 Before doing so, re-align the table if necessary."
1087 (interactive)
1088 (org-table-maybe-eval-formula)
1089 (org-table-maybe-recalculate-line)
1090 (if (or (looking-at "[ \t]*$")
1091 (save-excursion (skip-chars-backward " \t") (bolp)))
1092 (newline)
1093 (if (and org-table-automatic-realign
1094 org-table-may-need-update)
1095 (org-table-align))
1096 (let ((col (org-table-current-column)))
1097 (beginning-of-line 2)
1098 (if (or (not (org-at-table-p))
1099 (org-at-table-hline-p))
1100 (progn
1101 (beginning-of-line 0)
1102 (org-table-insert-row 'below)))
1103 (org-table-goto-column col)
1104 (skip-chars-backward "^|\n\r")
1105 (if (looking-at " ") (forward-char 1)))))
1107 ;;;###autoload
1108 (defun org-table-copy-down (n)
1109 "Copy the value of the current field one row below.
1111 If the field at the cursor is empty, copy the content of the
1112 nearest non-empty field above. With argument N, use the Nth
1113 non-empty field.
1115 If the current field is not empty, it is copied down to the next
1116 row, and the cursor is moved with it. Therefore, repeating this
1117 command causes the column to be filled row-by-row.
1119 If the variable `org-table-copy-increment' is non-nil and the
1120 field is an integer or a timestamp, it will be incremented while
1121 copying. By default, increment by the difference between the
1122 value in the current field and the one in the field above. To
1123 increment using a fixed integer, set `org-table-copy-increment'
1124 to a number. In the case of a timestamp, increment by days."
1125 (interactive "p")
1126 (let* ((colpos (org-table-current-column))
1127 (col (current-column))
1128 (field (save-excursion (org-table-get-field)))
1129 (field-up (or (save-excursion
1130 (org-table-get (1- (org-table-current-line))
1131 (org-table-current-column))) ""))
1132 (non-empty (string-match "[^ \t]" field))
1133 (non-empty-up (string-match "[^ \t]" field-up))
1134 (beg (org-table-begin))
1135 (orig-n n)
1136 txt txt-up inc)
1137 (org-table-check-inside-data-field)
1138 (if (not non-empty)
1139 (save-excursion
1140 (setq txt
1141 (catch 'exit
1142 (while (progn (beginning-of-line 1)
1143 (re-search-backward org-table-dataline-regexp
1144 beg t))
1145 (org-table-goto-column colpos t)
1146 (if (and (looking-at
1147 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1148 (<= (setq n (1- n)) 0))
1149 (throw 'exit (match-string 1))))))
1150 (setq field-up
1151 (catch 'exit
1152 (while (progn (beginning-of-line 1)
1153 (re-search-backward org-table-dataline-regexp
1154 beg t))
1155 (org-table-goto-column colpos t)
1156 (if (and (looking-at
1157 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1158 (<= (setq n (1- n)) 0))
1159 (throw 'exit (match-string 1))))))
1160 (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
1161 ;; Above field was not empty, go down to the next row
1162 (setq txt (org-trim field))
1163 (org-table-next-row)
1164 (org-table-blank-field))
1165 (if non-empty-up (setq txt-up (org-trim field-up)))
1166 (setq inc (cond
1167 ((numberp org-table-copy-increment) org-table-copy-increment)
1168 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
1169 (string-match org-ts-regexp3 txt))
1170 (- (org-time-string-to-absolute txt)
1171 (org-time-string-to-absolute txt-up)))
1172 ((string-match org-ts-regexp3 txt) 1)
1173 ((string-match "\\([-+]\\)?[0-9]+\\(?:\.[0-9]+\\)?" txt-up)
1174 (- (string-to-number txt)
1175 (string-to-number (match-string 0 txt-up))))
1176 (t 1)))
1177 (t 1)))
1178 (if (not txt)
1179 (user-error "No non-empty field found")
1180 (if (and org-table-copy-increment
1181 (not (equal orig-n 0))
1182 (string-match-p "^[-+^/*0-9eE.]+$" txt)
1183 (< (string-to-number txt) 100000000))
1184 (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
1185 (insert txt)
1186 (org-move-to-column col)
1187 (if (and org-table-copy-increment (org-at-timestamp-p 'lax))
1188 (org-timestamp-up-day inc)
1189 (org-table-maybe-recalculate-line))
1190 (org-table-align)
1191 (org-move-to-column col))))
1193 (defun org-table-check-inside-data-field (&optional noerror)
1194 "Is point inside a table data field?
1195 I.e. not on a hline or before the first or after the last column?
1196 This actually throws an error, so it aborts the current command."
1197 (cond ((and (org-at-table-p)
1198 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1199 (not (org-at-table-hline-p))
1200 (not (looking-at "[ \t]*$"))))
1201 (noerror nil)
1202 (t (user-error "Not in table data field"))))
1204 (defvar org-table-clip nil
1205 "Clipboard for table regions.")
1207 (defun org-table-get (line column)
1208 "Get the field in table line LINE, column COLUMN.
1209 If LINE is larger than the number of data lines in the table, the function
1210 returns nil. However, if COLUMN is too large, we will simply return an
1211 empty string.
1212 If LINE is nil, use the current line.
1213 If COLUMN is nil, use the current column."
1214 (setq column (or column (org-table-current-column)))
1215 (save-excursion
1216 (and (or (not line) (org-table-goto-line line))
1217 (org-trim (org-table-get-field column)))))
1219 (defun org-table-put (line column value &optional align)
1220 "Put VALUE into line LINE, column COLUMN.
1221 When ALIGN is set, also realign the table."
1222 (setq column (or column (org-table-current-column)))
1223 (prog1 (save-excursion
1224 (and (or (not line) (org-table-goto-line line))
1225 (progn (org-table-goto-column column nil 'force) t)
1226 (org-table-get-field column value)))
1227 (and align (org-table-align))))
1229 (defun org-table-current-line ()
1230 "Return the index of the current data line."
1231 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1232 (save-excursion
1233 (goto-char (org-table-begin))
1234 (while (and (re-search-forward org-table-dataline-regexp end t)
1235 (setq cnt (1+ cnt))
1236 (< (point-at-eol) pos))))
1237 cnt))
1239 (defun org-table-goto-line (N)
1240 "Go to the Nth data line in the current table.
1241 Return t when the line exists, nil if it does not exist."
1242 (goto-char (org-table-begin))
1243 (let ((end (org-table-end)) (cnt 0))
1244 (while (and (re-search-forward org-table-dataline-regexp end t)
1245 (< (setq cnt (1+ cnt)) N)))
1246 (= cnt N)))
1248 ;;;###autoload
1249 (defun org-table-blank-field ()
1250 "Blank the current table field or active region."
1251 (interactive)
1252 (org-table-check-inside-data-field)
1253 (if (and (called-interactively-p 'any) (org-region-active-p))
1254 (let (org-table-clip)
1255 (org-table-cut-region (region-beginning) (region-end)))
1256 (skip-chars-backward "^|")
1257 (backward-char 1)
1258 (if (looking-at "|[^|\n]+")
1259 (let* ((pos (match-beginning 0))
1260 (match (match-string 0))
1261 (len (org-string-width match)))
1262 (replace-match (concat "|" (make-string (1- len) ?\ )))
1263 (goto-char (+ 2 pos))
1264 (substring match 1)))))
1266 (defun org-table-get-field (&optional n replace)
1267 "Return the value of the field in column N of current row.
1268 N defaults to current column. If REPLACE is a string, replace
1269 field with this value. The return value is always the old
1270 value."
1271 (when n (org-table-goto-column n))
1272 (skip-chars-backward "^|\n")
1273 (if (or (bolp) (looking-at-p "[ \t]*$"))
1274 ;; Before first column or after last one.
1276 (looking-at "[^|\r\n]*")
1277 (let* ((pos (match-beginning 0))
1278 (val (buffer-substring pos (match-end 0))))
1279 (when replace
1280 (replace-match (if (equal replace "") " " replace) t t))
1281 (goto-char (min (line-end-position) (1+ pos)))
1282 val)))
1284 ;;;###autoload
1285 (defun org-table-field-info (_arg)
1286 "Show info about the current field, and highlight any reference at point."
1287 (interactive "P")
1288 (unless (org-at-table-p) (user-error "Not at a table"))
1289 (org-table-analyze)
1290 (save-excursion
1291 (let* ((pos (point))
1292 (col (org-table-current-column))
1293 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1294 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1295 (line-beginning-position))
1296 col)
1297 org-table-named-field-locations)))
1298 (eql (org-table-expand-lhs-ranges
1299 (mapcar
1300 (lambda (e)
1301 (cons (org-table-formula-handle-first/last-rc (car e))
1302 (cdr e)))
1303 (org-table-get-stored-formulas))))
1304 (dline (org-table-current-dline))
1305 (ref (format "@%d$%d" dline col))
1306 (ref1 (org-table-convert-refs-to-an ref))
1307 ;; Prioritize field formulas over column formulas.
1308 (fequation (or (assoc name eql) (assoc ref eql)))
1309 (cequation (assoc (format "$%d" col) eql))
1310 (eqn (or fequation cequation)))
1311 (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
1312 (when p (setq eqn p)))
1313 (goto-char pos)
1314 (ignore-errors (org-table-show-reference 'local))
1315 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1316 dline col
1317 (if cname (concat " or $" cname) "")
1318 dline col ref1
1319 (if name (concat " or $" name) "")
1320 ;; FIXME: formula info not correct if special table line
1321 (if eqn
1322 (concat ", formula: "
1323 (org-table-formula-to-user
1324 (concat
1325 (if (or (string-prefix-p "$" (car eqn))
1326 (string-prefix-p "@" (car eqn)))
1328 "$")
1329 (car eqn) "=" (cdr eqn))))
1330 "")))))
1332 (defun org-table-current-column ()
1333 "Find out which column we are in."
1334 (interactive)
1335 (save-excursion
1336 (let ((column 0) (pos (point)))
1337 (beginning-of-line)
1338 (while (search-forward "|" pos t) (cl-incf column))
1339 column)))
1341 (defun org-table-current-dline ()
1342 "Find out what table data line we are in.
1343 Only data lines count for this."
1344 (save-excursion
1345 (let ((c 0)
1346 (pos (line-beginning-position)))
1347 (goto-char (org-table-begin))
1348 (while (<= (point) pos)
1349 (when (looking-at org-table-dataline-regexp) (cl-incf c))
1350 (forward-line))
1351 c)))
1353 ;;;###autoload
1354 (defun org-table-goto-column (n &optional on-delim force)
1355 "Move the cursor to the Nth column in the current table line.
1356 With optional argument ON-DELIM, stop with point before the left delimiter
1357 of the field.
1358 If there are less than N fields, just go to after the last delimiter.
1359 However, when FORCE is non-nil, create new columns if necessary."
1360 (interactive "p")
1361 (beginning-of-line 1)
1362 (when (> n 0)
1363 (while (and (> (setq n (1- n)) -1)
1364 (or (search-forward "|" (point-at-eol) t)
1365 (and force
1366 (progn (end-of-line 1)
1367 (skip-chars-backward "^|")
1368 (insert " | ")
1369 t)))))
1370 (when (and force (not (looking-at ".*|")))
1371 (save-excursion (end-of-line 1) (insert " | ")))
1372 (if on-delim
1373 (backward-char 1)
1374 (if (looking-at " ") (forward-char 1)))))
1376 ;;;###autoload
1377 (defun org-table-insert-column ()
1378 "Insert a new column into the table."
1379 (interactive)
1380 (unless (org-at-table-p) (user-error "Not at a table"))
1381 (org-table-find-dataline)
1382 (let* ((col (max 1 (org-table-current-column)))
1383 (beg (org-table-begin))
1384 (end (copy-marker (org-table-end))))
1385 (org-table-save-field
1386 (goto-char beg)
1387 (while (< (point) end)
1388 (unless (org-at-table-hline-p)
1389 (org-table-goto-column col t)
1390 (insert "| "))
1391 (forward-line)))
1392 (set-marker end nil)
1393 (org-table-align)
1394 (when (or (not org-table-fix-formulas-confirm)
1395 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1396 (org-table-fix-formulas "$" nil (1- col) 1)
1397 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1399 (defun org-table-find-dataline ()
1400 "Find a data line in the current table, which is needed for column commands."
1401 (if (and (org-at-table-p)
1402 (not (org-at-table-hline-p)))
1404 (let ((col (current-column))
1405 (end (org-table-end)))
1406 (org-move-to-column col)
1407 (while (and (< (point) end)
1408 (or (not (= (current-column) col))
1409 (org-at-table-hline-p)))
1410 (beginning-of-line 2)
1411 (org-move-to-column col))
1412 (if (and (org-at-table-p)
1413 (not (org-at-table-hline-p)))
1415 (user-error
1416 "Please position cursor in a data line for column operations")))))
1418 (defun org-table-line-to-dline (line &optional above)
1419 "Turn a buffer line number into a data line number.
1421 If there is no data line in this line, return nil.
1423 If there is no matching dline (most likely the reference was
1424 a hline), the first dline below it is used. When ABOVE is
1425 non-nil, the one above is used."
1426 (let ((min 1)
1427 (max (1- (length org-table-dlines))))
1428 (cond ((or (> (aref org-table-dlines min) line)
1429 (< (aref org-table-dlines max) line))
1430 nil)
1431 ((= (aref org-table-dlines max) line) max)
1432 (t (catch 'exit
1433 (while (> (- max min) 1)
1434 (let* ((mean (/ (+ max min) 2))
1435 (v (aref org-table-dlines mean)))
1436 (cond ((= v line) (throw 'exit mean))
1437 ((> v line) (setq max mean))
1438 (t (setq min mean)))))
1439 (if above min max))))))
1441 ;;;###autoload
1442 (defun org-table-delete-column ()
1443 "Delete a column from the table."
1444 (interactive)
1445 (unless (org-at-table-p) (user-error "Not at a table"))
1446 (org-table-find-dataline)
1447 (org-table-check-inside-data-field)
1448 (let ((col (org-table-current-column))
1449 (beg (org-table-begin))
1450 (end (copy-marker (org-table-end))))
1451 (org-table-save-field
1452 (goto-char beg)
1453 (while (< (point) end)
1454 (if (org-at-table-hline-p)
1456 (org-table-goto-column col t)
1457 (and (looking-at "|[^|\n]+|")
1458 (replace-match "|")))
1459 (forward-line)))
1460 (set-marker end nil)
1461 (org-table-goto-column (max 1 (1- col)))
1462 (org-table-align)
1463 (when (or (not org-table-fix-formulas-confirm)
1464 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1465 (org-table-fix-formulas
1466 "$" (list (cons (number-to-string col) "INVALID")) col -1 col)
1467 (org-table-fix-formulas
1468 "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col))))
1470 ;;;###autoload
1471 (defun org-table-move-column-right ()
1472 "Move column to the right."
1473 (interactive)
1474 (org-table-move-column nil))
1475 ;;;###autoload
1476 (defun org-table-move-column-left ()
1477 "Move column to the left."
1478 (interactive)
1479 (org-table-move-column 'left))
1481 ;;;###autoload
1482 (defun org-table-move-column (&optional left)
1483 "Move the current column to the right. With arg LEFT, move to the left."
1484 (interactive "P")
1485 (unless (org-at-table-p) (user-error "Not at a table"))
1486 (org-table-find-dataline)
1487 (org-table-check-inside-data-field)
1488 (let* ((col (org-table-current-column))
1489 (col1 (if left (1- col) col))
1490 (colpos (if left (1- col) (1+ col)))
1491 (beg (org-table-begin))
1492 (end (copy-marker (org-table-end))))
1493 (when (and left (= col 1))
1494 (user-error "Cannot move column further left"))
1495 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1496 (user-error "Cannot move column further right"))
1497 (org-table-save-field
1498 (goto-char beg)
1499 (while (< (point) end)
1500 (unless (org-at-table-hline-p)
1501 (org-table-goto-column col1 t)
1502 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1503 (transpose-regions
1504 (match-beginning 1) (match-end 1)
1505 (match-beginning 2) (match-end 2))))
1506 (forward-line)))
1507 (set-marker end nil)
1508 (org-table-goto-column colpos)
1509 (org-table-align)
1510 (when (or (not org-table-fix-formulas-confirm)
1511 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1512 (org-table-fix-formulas
1513 "$" (list (cons (number-to-string col) (number-to-string colpos))
1514 (cons (number-to-string colpos) (number-to-string col))))
1515 (org-table-fix-formulas
1516 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1517 (cons (number-to-string colpos) (number-to-string col)))))))
1519 ;;;###autoload
1520 (defun org-table-move-row-down ()
1521 "Move table row down."
1522 (interactive)
1523 (org-table-move-row nil))
1524 ;;;###autoload
1525 (defun org-table-move-row-up ()
1526 "Move table row up."
1527 (interactive)
1528 (org-table-move-row 'up))
1530 ;;;###autoload
1531 (defun org-table-move-row (&optional up)
1532 "Move the current table line down. With arg UP, move it up."
1533 (interactive "P")
1534 (let* ((col (current-column))
1535 (pos (point))
1536 (hline1p (save-excursion (beginning-of-line 1)
1537 (looking-at org-table-hline-regexp)))
1538 (dline1 (org-table-current-dline))
1539 (dline2 (+ dline1 (if up -1 1)))
1540 (tonew (if up 0 2))
1541 hline2p)
1542 (when (and up (= (point-min) (line-beginning-position)))
1543 (user-error "Cannot move row further"))
1544 (beginning-of-line tonew)
1545 (when (or (and (not up) (eobp)) (not (org-at-table-p)))
1546 (goto-char pos)
1547 (user-error "Cannot move row further"))
1548 (setq hline2p (looking-at org-table-hline-regexp))
1549 (goto-char pos)
1550 (let ((row (delete-and-extract-region (line-beginning-position)
1551 (line-beginning-position 2))))
1552 (beginning-of-line tonew)
1553 (unless (bolp) (insert "\n")) ;at eob without a newline
1554 (insert row)
1555 (unless (bolp) (insert "\n")) ;missing final newline in ROW
1556 (beginning-of-line 0)
1557 (org-move-to-column col)
1558 (unless (or hline1p hline2p
1559 (not (or (not org-table-fix-formulas-confirm)
1560 (funcall org-table-fix-formulas-confirm
1561 "Fix formulas? "))))
1562 (org-table-fix-formulas
1563 "@" (list
1564 (cons (number-to-string dline1) (number-to-string dline2))
1565 (cons (number-to-string dline2) (number-to-string dline1))))))))
1567 ;;;###autoload
1568 (defun org-table-insert-row (&optional arg)
1569 "Insert a new row above the current line into the table.
1570 With prefix ARG, insert below the current line."
1571 (interactive "P")
1572 (unless (org-at-table-p) (user-error "Not at a table"))
1573 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1574 (new (org-table-clean-line line)))
1575 ;; Fix the first field if necessary
1576 (if (string-match "^[ \t]*| *[#$] *|" line)
1577 (setq new (replace-match (match-string 0 line) t t new)))
1578 (beginning-of-line (if arg 2 1))
1579 ;; Buffer may not end of a newline character, so ensure
1580 ;; (beginning-of-line 2) moves point to a new line.
1581 (unless (bolp) (insert "\n"))
1582 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1583 (beginning-of-line 0)
1584 (re-search-forward "| ?" (line-end-position) t)
1585 (when (or org-table-may-need-update org-table-overlay-coordinates)
1586 (org-table-align))
1587 (when (or (not org-table-fix-formulas-confirm)
1588 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1589 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1591 ;;;###autoload
1592 (defun org-table-insert-hline (&optional above)
1593 "Insert a horizontal-line below the current line into the table.
1594 With prefix ABOVE, insert above the current line."
1595 (interactive "P")
1596 (if (not (org-at-table-p))
1597 (user-error "Not at a table"))
1598 (when (eobp) (insert "\n") (backward-char 1))
1599 (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
1600 (org-table-align))
1601 (let ((line (org-table-clean-line
1602 (buffer-substring (point-at-bol) (point-at-eol))))
1603 (col (current-column)))
1604 (while (string-match "|\\( +\\)|" line)
1605 (setq line (replace-match
1606 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1607 ?-) "|") t t line)))
1608 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1609 (beginning-of-line (if above 1 2))
1610 (insert line "\n")
1611 (beginning-of-line (if above 1 -1))
1612 (org-move-to-column col)
1613 (and org-table-overlay-coordinates (org-table-align))))
1615 ;;;###autoload
1616 (defun org-table-hline-and-move (&optional same-column)
1617 "Insert a hline and move to the row below that line."
1618 (interactive "P")
1619 (let ((col (org-table-current-column)))
1620 (org-table-maybe-eval-formula)
1621 (org-table-maybe-recalculate-line)
1622 (org-table-insert-hline)
1623 (end-of-line 2)
1624 (if (looking-at "\n[ \t]*|-")
1625 (progn (insert "\n|") (org-table-align))
1626 (org-table-next-field))
1627 (if same-column (org-table-goto-column col))))
1629 (defun org-table-clean-line (s)
1630 "Convert a table line S into a string with only \"|\" and space.
1631 In particular, this does handle wide and invisible characters."
1632 (if (string-match "^[ \t]*|-" s)
1633 ;; It's a hline, just map the characters
1634 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1635 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1636 (setq s (replace-match
1637 (concat "|" (make-string (org-string-width (match-string 1 s))
1638 ?\ ) "|")
1639 t t s)))
1642 ;;;###autoload
1643 (defun org-table-kill-row ()
1644 "Delete the current row or horizontal line from the table."
1645 (interactive)
1646 (if (not (org-at-table-p))
1647 (user-error "Not at a table"))
1648 (let ((col (current-column))
1649 (dline (and (not (org-match-line org-table-hline-regexp))
1650 (org-table-current-dline))))
1651 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1652 (if (not (org-at-table-p)) (beginning-of-line 0))
1653 (org-move-to-column col)
1654 (when (and dline
1655 (or (not org-table-fix-formulas-confirm)
1656 (funcall org-table-fix-formulas-confirm "Fix formulas? ")))
1657 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1658 dline -1 dline))))
1660 ;;;###autoload
1661 (defun org-table-sort-lines
1662 (&optional with-case sorting-type getkey-func compare-func interactive?)
1663 "Sort table lines according to the column at point.
1665 The position of point indicates the column to be used for
1666 sorting, and the range of lines is the range between the nearest
1667 horizontal separator lines, or the entire table of no such lines
1668 exist. If point is before the first column, you will be prompted
1669 for the sorting column. If there is an active region, the mark
1670 specifies the first line and the sorting column, while point
1671 should be in the last line to be included into the sorting.
1673 The command then prompts for the sorting type which can be
1674 alphabetically, numerically, or by time (as given in a time stamp
1675 in the field, or as a HH:MM value). Sorting in reverse order is
1676 also possible.
1678 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1680 If SORTING-TYPE is specified when this function is called from a Lisp
1681 program, no prompting will take place. SORTING-TYPE must be a character,
1682 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1683 sorting should be done in reverse order.
1685 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1686 a function to be called to extract the key. It must return a value
1687 that is compatible with COMPARE-FUNC, the function used to compare
1688 entries.
1690 A non-nil value for INTERACTIVE? is used to signal that this
1691 function is being called interactively."
1692 (interactive (list current-prefix-arg nil nil nil t))
1693 (when (org-region-active-p) (goto-char (region-beginning)))
1694 ;; Point must be either within a field or before a data line.
1695 (save-excursion
1696 (skip-chars-backward " \t")
1697 (when (bolp) (search-forward "|" (line-end-position) t))
1698 (org-table-check-inside-data-field))
1699 ;; Set appropriate case sensitivity and column used for sorting.
1700 (let ((column (let ((c (org-table-current-column)))
1701 (cond ((> c 0) c)
1702 (interactive?
1703 (read-number "Use column N for sorting: "))
1704 (t 1))))
1705 (sorting-type
1706 (or sorting-type
1707 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1708 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1709 (save-restriction
1710 ;; Narrow buffer to appropriate sorting area.
1711 (if (org-region-active-p)
1712 (progn (goto-char (region-beginning))
1713 (narrow-to-region
1714 (point)
1715 (save-excursion (goto-char (region-end))
1716 (line-beginning-position 2))))
1717 (let ((start (org-table-begin))
1718 (end (org-table-end)))
1719 (narrow-to-region
1720 (save-excursion
1721 (if (re-search-backward org-table-hline-regexp start t)
1722 (line-beginning-position 2)
1723 start))
1724 (if (save-excursion (re-search-forward org-table-hline-regexp end t))
1725 (match-beginning 0)
1726 end))))
1727 ;; Determine arguments for `sort-subr'. Also record original
1728 ;; position. `org-table-save-field' cannot help here since
1729 ;; sorting is too much destructive.
1730 (let* ((sort-fold-case (not with-case))
1731 (coordinates
1732 (cons (count-lines (point-min) (line-beginning-position))
1733 (current-column)))
1734 (extract-key-from-field
1735 ;; Function to be called on the contents of the field
1736 ;; used for sorting in the current row.
1737 (cl-case sorting-type
1738 ((?n ?N) #'string-to-number)
1739 ((?a ?A) #'org-sort-remove-invisible)
1740 ((?t ?T)
1741 (lambda (f)
1742 (cond ((string-match org-ts-regexp-both f)
1743 (float-time
1744 (org-time-string-to-time (match-string 0 f))))
1745 ((org-duration-p f) (org-duration-to-minutes f))
1746 ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f)
1747 (org-duration-to-minutes (match-string 0 f)))
1748 (t 0))))
1749 ((?f ?F)
1750 (or getkey-func
1751 (and interactive?
1752 (org-read-function "Function for extracting keys: "))
1753 (error "Missing key extractor to sort rows")))
1754 (t (user-error "Invalid sorting type `%c'" sorting-type))))
1755 (predicate
1756 (cl-case sorting-type
1757 ((?n ?N ?t ?T) #'<)
1758 ((?a ?A) #'string<)
1759 ((?f ?F)
1760 (or compare-func
1761 (and interactive?
1762 (org-read-function
1763 (concat "Function for comparing keys "
1764 "(empty for default `sort-subr' predicate): ")
1765 'allow-empty)))))))
1766 (goto-char (point-min))
1767 (sort-subr (memq sorting-type '(?A ?N ?T ?F))
1768 (lambda ()
1769 (forward-line)
1770 (while (and (not (eobp))
1771 (not (looking-at org-table-dataline-regexp)))
1772 (forward-line)))
1773 #'end-of-line
1774 (lambda ()
1775 (funcall extract-key-from-field
1776 (org-trim (org-table-get-field column))))
1778 predicate)
1779 ;; Move back to initial field.
1780 (forward-line (car coordinates))
1781 (move-to-column (cdr coordinates))))))
1783 ;;;###autoload
1784 (defun org-table-cut-region (beg end)
1785 "Copy region in table to the clipboard and blank all relevant fields.
1786 If there is no active region, use just the field at point."
1787 (interactive (list
1788 (if (org-region-active-p) (region-beginning) (point))
1789 (if (org-region-active-p) (region-end) (point))))
1790 (org-table-copy-region beg end 'cut))
1792 ;;;###autoload
1793 (defun org-table-copy-region (beg end &optional cut)
1794 "Copy rectangular region in table to clipboard.
1795 A special clipboard is used which can only be accessed
1796 with `org-table-paste-rectangle'."
1797 (interactive (list
1798 (if (org-region-active-p) (region-beginning) (point))
1799 (if (org-region-active-p) (region-end) (point))
1800 current-prefix-arg))
1801 (goto-char (min beg end))
1802 (org-table-check-inside-data-field)
1803 (let ((beg (line-beginning-position))
1804 (c01 (org-table-current-column))
1805 region)
1806 (goto-char (max beg end))
1807 (org-table-check-inside-data-field)
1808 (let* ((end (copy-marker (line-end-position)))
1809 (c02 (org-table-current-column))
1810 (column-start (min c01 c02))
1811 (column-end (max c01 c02))
1812 (column-number (1+ (- column-end column-start)))
1813 (rpl (and cut " ")))
1814 (goto-char beg)
1815 (while (< (point) end)
1816 (unless (org-at-table-hline-p)
1817 ;; Collect every cell between COLUMN-START and COLUMN-END.
1818 (let (cols)
1819 (dotimes (c column-number)
1820 (push (org-table-get-field (+ c column-start) rpl) cols))
1821 (push (nreverse cols) region)))
1822 (forward-line))
1823 (set-marker end nil))
1824 (when cut (org-table-align))
1825 (setq org-table-clip (nreverse region))))
1827 ;;;###autoload
1828 (defun org-table-paste-rectangle ()
1829 "Paste a rectangular region into a table.
1830 The upper right corner ends up in the current field. All involved fields
1831 will be overwritten. If the rectangle does not fit into the present table,
1832 the table is enlarged as needed. The process ignores horizontal separator
1833 lines."
1834 (interactive)
1835 (unless (consp org-table-clip)
1836 (user-error "First cut/copy a region to paste!"))
1837 (org-table-check-inside-data-field)
1838 (let* ((column (org-table-current-column))
1839 (org-table-automatic-realign nil))
1840 (org-table-save-field
1841 (dolist (row org-table-clip)
1842 (while (org-at-table-hline-p) (forward-line))
1843 ;; If we left the table, create a new row.
1844 (when (and (bolp) (not (looking-at "[ \t]*|")))
1845 (end-of-line 0)
1846 (org-table-next-field))
1847 (let ((c column))
1848 (dolist (field row)
1849 (org-table-goto-column c nil 'force)
1850 (org-table-get-field nil field)
1851 (cl-incf c)))
1852 (forward-line)))
1853 (org-table-align)))
1855 ;;;###autoload
1856 (defun org-table-convert ()
1857 "Convert from `org-mode' table to table.el and back.
1858 Obviously, this only works within limits. When an Org table is converted
1859 to table.el, all horizontal separator lines get lost, because table.el uses
1860 these as cell boundaries and has no notion of horizontal lines. A table.el
1861 table can be converted to an Org table only if it does not do row or column
1862 spanning. Multiline cells will become multiple cells. Beware, Org mode
1863 does not test if the table can be successfully converted - it blindly
1864 applies a recipe that works for simple tables."
1865 (interactive)
1866 (require 'table)
1867 (if (org-at-table.el-p)
1868 ;; convert to Org table
1869 (let ((beg (copy-marker (org-table-begin t)))
1870 (end (copy-marker (org-table-end t))))
1871 (table-unrecognize-region beg end)
1872 (goto-char beg)
1873 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1874 (replace-match ""))
1875 (goto-char beg))
1876 (if (org-at-table-p)
1877 ;; convert to table.el table
1878 (let ((beg (copy-marker (org-table-begin)))
1879 (end (copy-marker (org-table-end))))
1880 ;; first, get rid of all horizontal lines
1881 (goto-char beg)
1882 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1883 (replace-match ""))
1884 ;; insert a hline before first
1885 (goto-char beg)
1886 (org-table-insert-hline 'above)
1887 (beginning-of-line -1)
1888 ;; insert a hline after each line
1889 (while (progn (beginning-of-line 3) (< (point) end))
1890 (org-table-insert-hline))
1891 (goto-char beg)
1892 (setq end (move-marker end (org-table-end)))
1893 ;; replace "+" at beginning and ending of hlines
1894 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1895 (replace-match "\\1+-"))
1896 (goto-char beg)
1897 (while (re-search-forward "-|[ \t]*$" end t)
1898 (replace-match "-+"))
1899 (goto-char beg)))))
1901 (defun org-table-transpose-table-at-point ()
1902 "Transpose Org table at point and eliminate hlines.
1903 So a table like
1905 | 1 | 2 | 4 | 5 |
1906 |---+---+---+---|
1907 | a | b | c | d |
1908 | e | f | g | h |
1910 will be transposed as
1912 | 1 | a | e |
1913 | 2 | b | f |
1914 | 4 | c | g |
1915 | 5 | d | h |
1917 Note that horizontal lines disappear."
1918 (interactive)
1919 (let* ((table (delete 'hline (org-table-to-lisp)))
1920 (dline_old (org-table-current-line))
1921 (col_old (org-table-current-column))
1922 (contents (mapcar (lambda (_)
1923 (let ((tp table))
1924 (mapcar
1925 (lambda (_)
1926 (prog1
1927 (pop (car tp))
1928 (setq tp (cdr tp))))
1929 table)))
1930 (car table))))
1931 (goto-char (org-table-begin))
1932 (re-search-forward "|")
1933 (backward-char)
1934 (delete-region (point) (org-table-end))
1935 (insert (mapconcat
1936 (lambda(x)
1937 (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1938 contents ""))
1939 (org-table-goto-line col_old)
1940 (org-table-goto-column dline_old))
1941 (org-table-align))
1943 ;;;###autoload
1944 (defun org-table-wrap-region (arg)
1945 "Wrap several fields in a column like a paragraph.
1946 This is useful if you'd like to spread the contents of a field over several
1947 lines, in order to keep the table compact.
1949 If there is an active region, and both point and mark are in the same column,
1950 the text in the column is wrapped to minimum width for the given number of
1951 lines. Generally, this makes the table more compact. A prefix ARG may be
1952 used to change the number of desired lines. For example, \
1953 `C-2 \\[org-table-wrap-region]'
1954 formats the selected text to two lines. If the region was longer than two
1955 lines, the remaining lines remain empty. A negative prefix argument reduces
1956 the current number of lines by that amount. The wrapped text is pasted back
1957 into the table. If you formatted it to more lines than it was before, fields
1958 further down in the table get overwritten - so you might need to make space in
1959 the table first.
1961 If there is no region, the current field is split at the cursor position and
1962 the text fragment to the right of the cursor is prepended to the field one
1963 line down.
1965 If there is no region, but you specify a prefix ARG, the current field gets
1966 blank, and the content is appended to the field above."
1967 (interactive "P")
1968 (org-table-check-inside-data-field)
1969 (if (org-region-active-p)
1970 ;; There is a region: fill as a paragraph.
1971 (let ((start (region-beginning)))
1972 (org-table-cut-region (region-beginning) (region-end))
1973 (when (> (length (car org-table-clip)) 1)
1974 (user-error "Region must be limited to single column"))
1975 (let ((nlines (cond ((not arg) (length org-table-clip))
1976 ((< arg 1) (+ (length org-table-clip) arg))
1977 (t arg))))
1978 (setq org-table-clip
1979 (mapcar #'list
1980 (org-wrap (mapconcat #'car org-table-clip " ")
1982 nlines))))
1983 (goto-char start)
1984 (org-table-paste-rectangle))
1985 ;; No region, split the current field at point.
1986 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1987 (skip-chars-forward "^\r\n|"))
1988 (cond
1989 (arg ; Combine with field above.
1990 (let ((s (org-table-blank-field))
1991 (col (org-table-current-column)))
1992 (forward-line -1)
1993 (while (org-at-table-hline-p) (forward-line -1))
1994 (org-table-goto-column col)
1995 (skip-chars-forward "^|")
1996 (skip-chars-backward " ")
1997 (insert " " (org-trim s))
1998 (org-table-align)))
1999 ((looking-at "\\([^|]+\\)+|") ; Split field.
2000 (let ((s (match-string 1)))
2001 (replace-match " |")
2002 (goto-char (match-beginning 0))
2003 (org-table-next-row)
2004 (insert (org-trim s) " ")
2005 (org-table-align)))
2006 (t (org-table-next-row)))))
2008 (defvar org-field-marker nil)
2010 ;;;###autoload
2011 (defun org-table-edit-field (arg)
2012 "Edit table field in a different window.
2013 This is mainly useful for fields that contain hidden parts.
2015 When called with a `\\[universal-argument]' prefix, just make the full field
2016 visible so that it can be edited in place.
2018 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2019 toggle `org-table-follow-field-mode'."
2020 (interactive "P")
2021 (unless (org-at-table-p) (user-error "Not at a table"))
2022 (cond
2023 ((equal arg '(16))
2024 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
2025 (arg
2026 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2027 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2028 (remove-text-properties b e '(org-cwidth t invisible t
2029 display t intangible t))
2030 (if (and (boundp 'font-lock-mode) font-lock-mode)
2031 (font-lock-fontify-block))))
2033 (let ((pos (point-marker))
2034 (coord
2035 (if (eq org-table-use-standard-references t)
2036 (concat (org-number-to-letters (org-table-current-column))
2037 (int-to-string (org-table-current-dline)))
2038 (concat "@" (int-to-string (org-table-current-dline))
2039 "$" (int-to-string (org-table-current-column)))))
2040 (field (org-table-get-field))
2041 (cw (current-window-configuration))
2043 (goto-char pos)
2044 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2045 (when (and (local-variable-p 'org-field-marker)
2046 (markerp org-field-marker))
2047 (move-marker org-field-marker nil))
2048 (erase-buffer)
2049 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
2050 (let ((org-inhibit-startup t)) (org-mode))
2051 (auto-fill-mode -1)
2052 (setq truncate-lines nil)
2053 (setq word-wrap t)
2054 (goto-char (setq p (point-max)))
2055 (insert (org-trim field))
2056 (remove-text-properties p (point-max)
2057 '(invisible t org-cwidth t display t
2058 intangible t))
2059 (goto-char p)
2060 (setq-local org-finish-function 'org-table-finish-edit-field)
2061 (setq-local org-window-configuration cw)
2062 (setq-local org-field-marker pos)
2063 (message "Edit and finish with C-c C-c")))))
2065 (defun org-table-finish-edit-field ()
2066 "Finish editing a table data field.
2067 Remove all newline characters, insert the result into the table, realign
2068 the table and kill the editing buffer."
2069 (let ((pos org-field-marker)
2070 (cw org-window-configuration)
2071 (cb (current-buffer))
2072 text)
2073 (goto-char (point-min))
2074 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
2075 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
2076 (replace-match " "))
2077 (setq text (org-trim (buffer-string)))
2078 (set-window-configuration cw)
2079 (kill-buffer cb)
2080 (select-window (get-buffer-window (marker-buffer pos)))
2081 (goto-char pos)
2082 (move-marker pos nil)
2083 (org-table-check-inside-data-field)
2084 (org-table-get-field nil text)
2085 (org-table-align)
2086 (message "New field value inserted")))
2088 (define-minor-mode org-table-follow-field-mode
2089 "Minor mode to make the table field editor window follow the cursor.
2090 When this mode is active, the field editor window will always show the
2091 current field. The mode exits automatically when the cursor leaves the
2092 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2093 nil " TblFollow" nil
2094 (if org-table-follow-field-mode
2095 (add-hook 'post-command-hook 'org-table-follow-fields-with-editor
2096 'append 'local)
2097 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
2098 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2099 (win (and buf (get-buffer-window buf))))
2100 (when win (delete-window win))
2101 (when buf
2102 (with-current-buffer buf
2103 (move-marker org-field-marker nil))
2104 (kill-buffer buf)))))
2106 (defun org-table-follow-fields-with-editor ()
2107 (if (and org-table-exit-follow-field-mode-when-leaving-table
2108 (not (org-at-table-p)))
2109 ;; We have left the table, exit the follow mode
2110 (org-table-follow-field-mode -1)
2111 (when (org-table-check-inside-data-field 'noerror)
2112 (let ((win (selected-window)))
2113 (org-table-edit-field nil)
2114 (org-fit-window-to-buffer)
2115 (select-window win)))))
2117 (defvar org-timecnt) ; dynamically scoped parameter
2119 ;;;###autoload
2120 (defun org-table-sum (&optional beg end nlast)
2121 "Sum numbers in region of current table column.
2122 The result will be displayed in the echo area, and will be available
2123 as kill to be inserted with \\[yank].
2125 If there is an active region, it is interpreted as a rectangle and all
2126 numbers in that rectangle will be summed. If there is no active
2127 region and point is located in a table column, sum all numbers in that
2128 column.
2130 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2131 numbers are assumed to be times as well (in decimal hours) and the
2132 numbers are added as such.
2134 If NLAST is a number, only the NLAST fields will actually be summed."
2135 (interactive)
2136 (save-excursion
2137 (let (col (org-timecnt 0) diff h m s org-table-clip)
2138 (cond
2139 ((and beg end)) ; beg and end given explicitly
2140 ((org-region-active-p)
2141 (setq beg (region-beginning) end (region-end)))
2143 (setq col (org-table-current-column))
2144 (goto-char (org-table-begin))
2145 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2146 (user-error "No table data"))
2147 (org-table-goto-column col)
2148 (setq beg (point))
2149 (goto-char (org-table-end))
2150 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2151 (user-error "No table data"))
2152 (org-table-goto-column col)
2153 (setq end (point))))
2154 (let* ((items (apply 'append (org-table-copy-region beg end)))
2155 (items1 (cond ((not nlast) items)
2156 ((>= nlast (length items)) items)
2157 (t (setq items (reverse items))
2158 (setcdr (nthcdr (1- nlast) items) nil)
2159 (nreverse items))))
2160 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2161 items1)))
2162 (res (apply '+ numbers))
2163 (sres (if (= org-timecnt 0)
2164 (number-to-string res)
2165 (setq diff (* 3600 res)
2166 h (floor (/ diff 3600)) diff (mod diff 3600)
2167 m (floor (/ diff 60)) diff (mod diff 60)
2168 s diff)
2169 (format "%.0f:%02.0f:%02.0f" h m s))))
2170 (kill-new sres)
2171 (when (called-interactively-p 'interactive)
2172 (message "%s" (substitute-command-keys
2173 (format "Sum of %d items: %-20s \
2174 \(\\[yank] will insert result into buffer)" (length numbers) sres))))
2175 sres))))
2177 (defun org-table-get-number-for-summing (s)
2178 (let (n)
2179 (if (string-match "^ *|? *" s)
2180 (setq s (replace-match "" nil nil s)))
2181 (if (string-match " *|? *$" s)
2182 (setq s (replace-match "" nil nil s)))
2183 (setq n (string-to-number s))
2184 (cond
2185 ((and (string-match "0" s)
2186 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2187 ((string-match "\\`[ \t]+\\'" s) nil)
2188 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2189 (let ((h (string-to-number (or (match-string 1 s) "0")))
2190 (m (string-to-number (or (match-string 2 s) "0")))
2191 (s (string-to-number (or (match-string 4 s) "0"))))
2192 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2193 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2194 ((equal n 0) nil)
2195 (t n))))
2197 (defun org-table-current-field-formula (&optional key noerror)
2198 "Return the formula active for the current field.
2200 Assumes that table is already analyzed. If KEY is given, return
2201 the key to this formula. Otherwise return the formula preceded
2202 with \"=\" or \":=\"."
2203 (let* ((line (count-lines org-table-current-begin-pos
2204 (line-beginning-position)))
2205 (row (org-table-line-to-dline line)))
2206 (cond
2207 (row
2208 (let* ((col (org-table-current-column))
2209 (name (car (rassoc (list line col)
2210 org-table-named-field-locations)))
2211 (scol (format "$%d" col))
2212 (ref (format "@%d$%d" (org-table-current-dline) col))
2213 (stored-list (org-table-get-stored-formulas noerror))
2214 (ass (or (assoc name stored-list)
2215 (assoc ref stored-list)
2216 (assoc scol stored-list))))
2217 (cond (key (car ass))
2218 (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=")
2219 (cdr ass))))))
2220 (noerror nil)
2221 (t (error "No formula active for the current field")))))
2223 (defun org-table-get-formula (&optional equation named)
2224 "Read a formula from the minibuffer, offer stored formula as default.
2225 When NAMED is non-nil, look for a named equation."
2226 (let* ((stored-list (org-table-get-stored-formulas))
2227 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2228 (line-beginning-position))
2229 (org-table-current-column))
2230 org-table-named-field-locations)))
2231 (ref (format "@%d$%d"
2232 (org-table-current-dline)
2233 (org-table-current-column)))
2234 (scol (cond
2235 ((not named) (format "$%d" (org-table-current-column)))
2236 ((and name (not (string-match "\\`LR[0-9]+\\'" name))) name)
2237 (t ref)))
2238 (name (or name ref))
2239 (org-table-may-need-update nil)
2240 (stored (cdr (assoc scol stored-list)))
2241 (eq (cond
2242 ((and stored equation (string-match-p "^ *=? *$" equation))
2243 stored)
2244 ((stringp equation)
2245 equation)
2246 (t (org-table-formula-from-user
2247 (read-string
2248 (org-table-formula-to-user
2249 (format "%s formula %s="
2250 (if named "Field" "Column")
2251 scol))
2252 (if stored (org-table-formula-to-user stored) "")
2253 'org-table-formula-history
2254 )))))
2255 mustsave)
2256 (when (not (string-match "\\S-" eq))
2257 ;; remove formula
2258 (setq stored-list (delq (assoc scol stored-list) stored-list))
2259 (org-table-store-formulas stored-list)
2260 (user-error "Formula removed"))
2261 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2262 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2263 (if (and name (not named))
2264 ;; We set the column equation, delete the named one.
2265 (setq stored-list (delq (assoc name stored-list) stored-list)
2266 mustsave t))
2267 (if stored
2268 (setcdr (assoc scol stored-list) eq)
2269 (setq stored-list (cons (cons scol eq) stored-list)))
2270 (if (or mustsave (not (equal stored eq)))
2271 (org-table-store-formulas stored-list))
2272 eq))
2274 (defun org-table-store-formulas (alist &optional location)
2275 "Store the list of formulas below the current table.
2276 If optional argument LOCATION is a buffer position, insert it at
2277 LOCATION instead."
2278 (save-excursion
2279 (if location
2280 (progn (goto-char location) (beginning-of-line))
2281 (goto-char (org-table-end)))
2282 (let ((case-fold-search t))
2283 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2284 (progn
2285 ;; Don't overwrite TBLFM, we might use text properties to
2286 ;; store stuff.
2287 (goto-char (match-beginning 3))
2288 (delete-region (match-beginning 3) (match-end 0)))
2289 (org-indent-line)
2290 (insert (or (match-string 2) "#+TBLFM:")))
2291 (insert " "
2292 (mapconcat (lambda (x) (concat (car x) "=" (cdr x)))
2293 (sort alist #'org-table-formula-less-p)
2294 "::")
2295 "\n"))))
2297 (defsubst org-table-formula-make-cmp-string (a)
2298 (when (string-match "\\`$[<>]" a)
2299 (let ((arrow (string-to-char (substring a 1))))
2300 ;; Fake a high number to make sure this is sorted at the end.
2301 (setq a (org-table-formula-handle-first/last-rc a))
2302 (setq a (format "$%d" (+ 10000
2303 (if (= arrow ?<) -1000 0)
2304 (string-to-number (substring a 1)))))))
2305 (when (string-match
2306 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2308 (concat
2309 (if (match-end 2)
2310 (format "@%05d" (string-to-number (match-string 2 a))) "")
2311 (if (match-end 4)
2312 (format "$%05d" (string-to-number (match-string 4 a))) "")
2313 (if (match-end 5)
2314 (concat "@@" (match-string 5 a))))))
2316 (defun org-table-formula-less-p (a b)
2317 "Compare two formulas for sorting."
2318 (let ((as (org-table-formula-make-cmp-string (car a)))
2319 (bs (org-table-formula-make-cmp-string (car b))))
2320 (and as bs (string< as bs))))
2322 ;;;###autoload
2323 (defun org-table-get-stored-formulas (&optional noerror location)
2324 "Return an alist with the stored formulas directly after current table.
2325 By default, only return active formulas, i.e., formulas located
2326 on the first line after the table. However, if optional argument
2327 LOCATION is a buffer position, consider the formulas there."
2328 (save-excursion
2329 (if location
2330 (progn (goto-char location) (beginning-of-line))
2331 (goto-char (org-table-end)))
2332 (let ((case-fold-search t))
2333 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2334 (let ((strings (org-split-string (match-string-no-properties 2)
2335 " *:: *"))
2336 eq-alist seen)
2337 (dolist (string strings (nreverse eq-alist))
2338 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2339 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2340 string)
2341 (let ((lhs
2342 (let ((m (match-string 1 string)))
2343 (cond
2344 ((not (match-end 2)) m)
2345 ;; Is it a column reference?
2346 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m) m)
2347 ;; Since named columns are not possible in
2348 ;; LHS, assume this is a named field.
2349 (t (match-string 2 string)))))
2350 (rhs (match-string 3 string)))
2351 (push (cons lhs rhs) eq-alist)
2352 (cond
2353 ((not (member lhs seen)) (push lhs seen))
2354 (noerror
2355 (message
2356 "Double definition `%s=' in TBLFM line, please fix by hand"
2357 lhs)
2358 (ding)
2359 (sit-for 2))
2361 (user-error
2362 "Double definition `%s=' in TBLFM line, please fix by hand"
2363 lhs)))))))))))
2365 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2366 "Modify the equations after the table structure has been edited.
2367 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2368 For all numbers larger than LIMIT, shift them by DELTA."
2369 (save-excursion
2370 (goto-char (org-table-end))
2371 (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2372 (let ((msg "The formulas in #+TBLFM have been updated")
2373 (re (concat key "\\([0-9]+\\)"))
2374 (re2
2375 (when remove
2376 (if (or (equal key "$") (equal key "$LR"))
2377 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2378 (regexp-quote key) remove)
2379 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2380 s n a)
2381 (when remove
2382 (while (re-search-forward re2 (point-at-eol) t)
2383 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2384 (if (equal (char-before (match-beginning 0)) ?.)
2385 (user-error
2386 "Change makes TBLFM term %s invalid, use undo to recover"
2387 (match-string 0))
2388 (replace-match "")))))
2389 (while (re-search-forward re (point-at-eol) t)
2390 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2391 (setq s (match-string 1) n (string-to-number s))
2392 (cond
2393 ((setq a (assoc s replace))
2394 (replace-match (concat key (cdr a)) t t)
2395 (message msg))
2396 ((and limit (> n limit))
2397 (replace-match (concat key (int-to-string (+ n delta))) t t)
2398 (message msg))))))
2399 (forward-line))))
2401 ;;;###autoload
2402 (defun org-table-maybe-eval-formula ()
2403 "Check if the current field starts with \"=\" or \":=\".
2404 If yes, store the formula and apply it."
2405 ;; We already know we are in a table. Get field will only return a formula
2406 ;; when appropriate. It might return a separator line, but no problem.
2407 (when org-table-formula-evaluate-inline
2408 (let* ((field (org-trim (or (org-table-get-field) "")))
2409 named eq)
2410 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2411 (setq named (equal (string-to-char field) ?:)
2412 eq (match-string 1 field))
2413 (org-table-eval-formula (and named '(4))
2414 (org-table-formula-from-user eq))))))
2416 (defvar org-recalc-commands nil
2417 "List of commands triggering the recalculation of a line.
2418 Will be filled automatically during use.")
2420 (defvar org-recalc-marks
2421 '((" " . "Unmarked: no special line, no automatic recalculation")
2422 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2423 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2424 ("!" . "Column name definition line. Reference in formula as $name.")
2425 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2426 ("_" . "Names for values in row below this one.")
2427 ("^" . "Names for values in row above this one.")))
2429 ;;;###autoload
2430 (defun org-table-rotate-recalc-marks (&optional newchar)
2431 "Rotate the recalculation mark in the first column.
2432 If in any row, the first field is not consistent with a mark,
2433 insert a new column for the markers.
2434 When there is an active region, change all the lines in the region,
2435 after prompting for the marking character.
2436 After each change, a message will be displayed indicating the meaning
2437 of the new mark."
2438 (interactive)
2439 (unless (org-at-table-p) (user-error "Not at a table"))
2440 (let* ((region (org-region-active-p))
2441 (l1 (and region
2442 (save-excursion (goto-char (region-beginning))
2443 (copy-marker (line-beginning-position)))))
2444 (l2 (and region
2445 (save-excursion (goto-char (region-end))
2446 (copy-marker (line-beginning-position)))))
2447 (l (copy-marker (line-beginning-position)))
2448 (col (org-table-current-column))
2449 (newchar (if region
2450 (char-to-string
2451 (read-char-exclusive
2452 "Change region to what mark? Type # * ! $ or SPC: "))
2453 newchar))
2454 (no-special-column
2455 (save-excursion
2456 (goto-char (org-table-begin))
2457 (re-search-forward
2458 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
2459 (when (and newchar (not (assoc newchar org-recalc-marks)))
2460 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2461 newchar))
2462 (when l1 (goto-char l1))
2463 (save-excursion
2464 (beginning-of-line)
2465 (unless (looking-at org-table-dataline-regexp)
2466 (user-error "Not at a table data line")))
2467 (when no-special-column
2468 (org-table-goto-column 1)
2469 (org-table-insert-column))
2470 (let ((previous-line-end (line-end-position))
2471 (newchar
2472 (save-excursion
2473 (beginning-of-line)
2474 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2475 (newchar)
2476 (t (cadr (member (match-string 1)
2477 (append (mapcar #'car org-recalc-marks)
2478 '(" ")))))))))
2479 ;; Rotate mark in first row.
2480 (org-table-get-field 1 (format " %s " newchar))
2481 ;; Rotate marks in additional rows if a region is active.
2482 (when region
2483 (save-excursion
2484 (forward-line)
2485 (while (<= (point) l2)
2486 (when (looking-at org-table-dataline-regexp)
2487 (org-table-get-field 1 (format " %s " newchar)))
2488 (forward-line))))
2489 ;; Only align if rotation actually changed lines' length.
2490 (when (/= previous-line-end (line-end-position)) (org-table-align)))
2491 (goto-char l)
2492 (org-table-goto-column (if no-special-column (1+ col) col))
2493 (when l1 (set-marker l1 nil))
2494 (when l2 (set-marker l2 nil))
2495 (set-marker l nil)
2496 (when (called-interactively-p 'interactive)
2497 (message "%s" (cdr (assoc newchar org-recalc-marks))))))
2499 ;;;###autoload
2500 (defun org-table-analyze ()
2501 "Analyze table at point and store results.
2503 This function sets up the following dynamically scoped variables:
2505 `org-table-column-name-regexp',
2506 `org-table-column-names',
2507 `org-table-current-begin-pos',
2508 `org-table-current-line-types',
2509 `org-table-current-ncol',
2510 `org-table-dlines',
2511 `org-table-hlines',
2512 `org-table-local-parameters',
2513 `org-table-named-field-locations'."
2514 (let ((beg (org-table-begin))
2515 (end (org-table-end)))
2516 (save-excursion
2517 (goto-char beg)
2518 ;; Extract column names.
2519 (setq org-table-column-names nil)
2520 (when (save-excursion
2521 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
2522 (let ((c 1))
2523 (dolist (name (org-split-string (match-string 1) " *| *"))
2524 (cl-incf c)
2525 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
2526 (push (cons name (int-to-string c)) org-table-column-names)))))
2527 (setq org-table-column-names (nreverse org-table-column-names))
2528 (setq org-table-column-name-regexp
2529 (format "\\$\\(%s\\)\\>"
2530 (regexp-opt (mapcar #'car org-table-column-names) t)))
2531 ;; Extract local parameters.
2532 (setq org-table-local-parameters nil)
2533 (save-excursion
2534 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2535 (dolist (field (org-split-string (match-string 1) " *| *"))
2536 (when (string-match
2537 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2538 (push (cons (match-string 1 field) (match-string 2 field))
2539 org-table-local-parameters)))))
2540 ;; Update named fields locations. We minimize `count-lines'
2541 ;; processing by storing last known number of lines in LAST.
2542 (setq org-table-named-field-locations nil)
2543 (save-excursion
2544 (let ((last (cons (point) 0)))
2545 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2546 (let ((c (match-string 1))
2547 (fields (org-split-string (match-string 2) " *| *")))
2548 (save-excursion
2549 (forward-line (if (equal c "_") 1 -1))
2550 (let ((fields1
2551 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2552 (org-split-string (match-string 1) " *| *")))
2553 (line (cl-incf (cdr last) (count-lines (car last) (point))))
2554 (col 1))
2555 (setcar last (point)) ; Update last known position.
2556 (while (and fields fields1)
2557 (let ((field (pop fields))
2558 (v (pop fields1)))
2559 (cl-incf col)
2560 (when (and (stringp field)
2561 (stringp v)
2562 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2563 field))
2564 (push (cons field v) org-table-local-parameters)
2565 (push (list field line col)
2566 org-table-named-field-locations))))))))))
2567 ;; Re-use existing markers when possible.
2568 (if (markerp org-table-current-begin-pos)
2569 (move-marker org-table-current-begin-pos (point))
2570 (setq org-table-current-begin-pos (point-marker)))
2571 ;; Analyze the line types.
2572 (let ((l 0) hlines dlines types)
2573 (while (looking-at "[ \t]*|\\(-\\)?")
2574 (push (if (match-end 1) 'hline 'dline) types)
2575 (if (match-end 1) (push l hlines) (push l dlines))
2576 (forward-line)
2577 (cl-incf l))
2578 (push 'hline types) ; Add an imaginary extra hline to the end.
2579 (setq org-table-current-line-types (apply #'vector (nreverse types)))
2580 (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
2581 (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
2582 ;; Get the number of columns from the first data line in table.
2583 (goto-char beg)
2584 (forward-line (aref org-table-dlines 1))
2585 (let* ((fields
2586 (org-split-string
2587 (buffer-substring (line-beginning-position) (line-end-position))
2588 "[ \t]*|[ \t]*"))
2589 (nfields (length fields))
2590 al al2)
2591 (setq org-table-current-ncol nfields)
2592 (let ((last-dline
2593 (aref org-table-dlines (1- (length org-table-dlines)))))
2594 (dotimes (i nfields)
2595 (let ((column (1+ i)))
2596 (push (list (format "LR%d" column) last-dline column) al)
2597 (push (cons (format "LR%d" column) (nth i fields)) al2))))
2598 (setq org-table-named-field-locations
2599 (append org-table-named-field-locations al))
2600 (setq org-table-local-parameters
2601 (append org-table-local-parameters al2))))))
2603 (defun org-table-goto-field (ref &optional create-column-p)
2604 "Move point to a specific field in the current table.
2606 REF is either the name of a field its absolute reference, as
2607 a string. No column is created unless CREATE-COLUMN-P is
2608 non-nil. If it is a function, it is called with the column
2609 number as its argument as is used as a predicate to know if the
2610 column can be created.
2612 This function assumes the table is already analyzed (i.e., using
2613 `org-table-analyze')."
2614 (let* ((coordinates
2615 (cond
2616 ((cdr (assoc ref org-table-named-field-locations)))
2617 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
2618 (list (condition-case nil
2619 (aref org-table-dlines
2620 (string-to-number (match-string 1 ref)))
2621 (error (user-error "Invalid row number in %s" ref)))
2622 (string-to-number (match-string 2 ref))))
2623 (t (user-error "Unknown field: %s" ref))))
2624 (line (car coordinates))
2625 (column (nth 1 coordinates))
2626 (create-new-column (if (functionp create-column-p)
2627 (funcall create-column-p column)
2628 create-column-p)))
2629 (when coordinates
2630 (goto-char org-table-current-begin-pos)
2631 (forward-line line)
2632 (org-table-goto-column column nil create-new-column))))
2634 ;;;###autoload
2635 (defun org-table-maybe-recalculate-line ()
2636 "Recompute the current line if marked for it, and if we haven't just done it."
2637 (interactive)
2638 (and org-table-allow-automatic-line-recalculation
2639 (not (and (memq last-command org-recalc-commands)
2640 (eq org-last-recalc-line (line-beginning-position))))
2641 (save-excursion (beginning-of-line 1)
2642 (looking-at org-table-auto-recalculate-regexp))
2643 (org-table-recalculate) t))
2645 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2646 (defsubst org-set-calc-mode (var &optional value)
2647 (if (stringp var)
2648 (setq var (assoc var '(("D" calc-angle-mode deg)
2649 ("R" calc-angle-mode rad)
2650 ("F" calc-prefer-frac t)
2651 ("S" calc-symbolic-mode t)))
2652 value (nth 2 var) var (nth 1 var)))
2653 (if (memq var org-tbl-calc-modes)
2654 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2655 (cons var (cons value org-tbl-calc-modes)))
2656 org-tbl-calc-modes)
2658 ;;;###autoload
2659 (defun org-table-eval-formula (&optional arg equation
2660 suppress-align suppress-const
2661 suppress-store suppress-analysis)
2662 "Replace the table field value at the cursor by the result of a calculation.
2664 In a table, this command replaces the value in the current field with the
2665 result of a formula. It also installs the formula as the \"current\" column
2666 formula, by storing it in a special line below the table. When called
2667 with a `\\[universal-argument]' prefix the formula is installed as a \
2668 field formula.
2670 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2671 insert the active equation for the field
2672 back into the current field, so that it can be edited there. This is \
2673 useful
2674 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2675 check the referenced fields.
2677 When called, the command first prompts for a formula, which is read in
2678 the minibuffer. Previously entered formulas are available through the
2679 history list, and the last used formula is offered as a default.
2680 These stored formulas are adapted correctly when moving, inserting, or
2681 deleting columns with the corresponding commands.
2683 The formula can be any algebraic expression understood by the Calc package.
2684 For details, see the Org mode manual.
2686 This function can also be called from Lisp programs and offers
2687 additional arguments: EQUATION can be the formula to apply. If this
2688 argument is given, the user will not be prompted.
2690 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2691 unnecessary aligns.
2693 SUPPRESS-CONST suppresses the interpretation of constants in the
2694 formula, assuming that this has been done already outside the
2695 function.
2697 SUPPRESS-STORE means the formula should not be stored, either
2698 because it is already stored, or because it is a modified
2699 equation that should not overwrite the stored one.
2701 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2702 location of point."
2703 (interactive "P")
2704 (unless suppress-analysis
2705 (org-table-check-inside-data-field)
2706 (org-table-analyze))
2707 (if (equal arg '(16))
2708 (let ((eq (org-table-current-field-formula)))
2709 (org-table-get-field nil eq)
2710 (org-table-align)
2711 (setq org-table-may-need-update t))
2712 (let* (fields
2713 (ndown (if (integerp arg) arg 1))
2714 (org-table-automatic-realign nil)
2715 (case-fold-search nil)
2716 (down (> ndown 1))
2717 (formula (if (and equation suppress-store)
2718 equation
2719 (org-table-get-formula equation (equal arg '(4)))))
2720 (n0 (org-table-current-column))
2721 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2722 (numbers nil) ; was a variable, now fixed default
2723 (keep-empty nil)
2724 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2725 duration duration-output-format)
2726 ;; Parse the format string. Since we have a lot of modes, this is
2727 ;; a lot of work. However, I think calc still uses most of the time.
2728 (if (string-match ";" formula)
2729 (let ((tmp (org-split-string formula ";")))
2730 (setq formula (car tmp)
2731 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2732 (nth 1 tmp)))
2733 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2734 (setq c (string-to-char (match-string 1 fmt))
2735 n (string-to-number (match-string 2 fmt)))
2736 (if (= c ?p)
2737 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2738 (setq org-tbl-calc-modes
2739 (org-set-calc-mode
2740 'calc-float-format
2741 (list (cdr (assoc c '((?n . float) (?f . fix)
2742 (?s . sci) (?e . eng))))
2743 n))))
2744 (setq fmt (replace-match "" t t fmt)))
2745 (if (string-match "[tTU]" fmt)
2746 (let ((ff (match-string 0 fmt)))
2747 (setq duration t numbers t
2748 duration-output-format
2749 (cond ((equal ff "T") nil)
2750 ((equal ff "t") org-table-duration-custom-format)
2751 ((equal ff "U") 'hh:mm))
2752 fmt (replace-match "" t t fmt))))
2753 (if (string-match "N" fmt)
2754 (setq numbers t
2755 fmt (replace-match "" t t fmt)))
2756 (if (string-match "L" fmt)
2757 (setq literal t
2758 fmt (replace-match "" t t fmt)))
2759 (if (string-match "E" fmt)
2760 (setq keep-empty t
2761 fmt (replace-match "" t t fmt)))
2762 (while (string-match "[DRFS]" fmt)
2763 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2764 (setq fmt (replace-match "" t t fmt)))
2765 (unless (string-match "\\S-" fmt)
2766 (setq fmt nil))))
2767 (when (and (not suppress-const) org-table-formula-use-constants)
2768 (setq formula (org-table-formula-substitute-names formula)))
2769 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2770 (setq formula (org-table-formula-handle-first/last-rc formula))
2771 (while (> ndown 0)
2772 (setq fields (org-split-string
2773 (org-trim
2774 (buffer-substring-no-properties
2775 (line-beginning-position) (line-end-position)))
2776 " *| *"))
2777 ;; replace fields with duration values if relevant
2778 (if duration
2779 (setq fields
2780 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2781 fields)))
2782 (if (eq numbers t)
2783 (setq fields (mapcar
2784 (lambda (x)
2785 (if (string-match "\\S-" x)
2786 (number-to-string (string-to-number x))
2788 fields)))
2789 (setq ndown (1- ndown))
2790 (setq form (copy-sequence formula)
2791 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2792 (if (and lispp literal) (setq lispp 'literal))
2794 ;; Insert row and column number of formula result field
2795 (while (string-match "[@$]#" form)
2796 (setq form
2797 (replace-match
2798 (format "%d"
2799 (save-match-data
2800 (if (equal (substring form (match-beginning 0)
2801 (1+ (match-beginning 0)))
2802 "@")
2803 (org-table-current-dline)
2804 (org-table-current-column))))
2805 t t form)))
2807 ;; Check for old vertical references
2808 (org-table--error-on-old-row-references form)
2809 ;; Insert remote references
2810 (setq form (org-table-remote-reference-indirection form))
2811 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2812 (setq form
2813 (replace-match
2814 (save-match-data
2815 (org-table-make-reference
2816 (let ((rmtrng (org-table-get-remote-range
2817 (match-string 1 form) (match-string 2 form))))
2818 (if duration
2819 (if (listp rmtrng)
2820 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2821 (org-table-time-string-to-seconds rmtrng))
2822 rmtrng))
2823 keep-empty numbers lispp))
2824 t t form)))
2825 ;; Insert complex ranges
2826 (while (and (string-match org-table-range-regexp form)
2827 (> (length (match-string 0 form)) 1))
2828 (setq formrg
2829 (save-match-data
2830 (org-table-get-range
2831 (match-string 0 form) org-table-current-begin-pos n0)))
2832 (setq formrpl
2833 (save-match-data
2834 (org-table-make-reference
2835 ;; possibly handle durations
2836 (if duration
2837 (if (listp formrg)
2838 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2839 (org-table-time-string-to-seconds formrg))
2840 formrg)
2841 keep-empty numbers lispp)))
2842 (if (not (save-match-data
2843 (string-match (regexp-quote form) formrpl)))
2844 (setq form (replace-match formrpl t t form))
2845 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2846 ;; Insert simple ranges, i.e. included in the current row.
2847 (while (string-match
2848 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2849 form)
2850 (setq form
2851 (replace-match
2852 (save-match-data
2853 (org-table-make-reference
2854 (cl-subseq fields
2855 (+ (if (match-end 2) n0 0)
2856 (string-to-number (match-string 1 form))
2858 (+ (if (match-end 4) n0 0)
2859 (string-to-number (match-string 3 form))))
2860 keep-empty numbers lispp))
2861 t t form)))
2862 (setq form0 form)
2863 ;; Insert the references to fields in same row
2864 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2865 (setq n (+ (string-to-number (match-string 1 form))
2866 (if (match-end 2) n0 0))
2867 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2868 formrpl (save-match-data
2869 (org-table-make-reference
2870 x keep-empty numbers lispp)))
2871 (when (or (not x)
2872 (save-match-data
2873 (string-match (regexp-quote formula) formrpl)))
2874 (user-error "Invalid field specifier \"%s\""
2875 (match-string 0 form)))
2876 (setq form (replace-match formrpl t t form)))
2878 (if lispp
2879 (setq ev (condition-case nil
2880 (eval (eval (read form)))
2881 (error "#ERROR"))
2882 ev (if (numberp ev) (number-to-string ev) ev)
2883 ev (if duration (org-table-time-seconds-to-string
2884 (string-to-number ev)
2885 duration-output-format) ev))
2887 ;; Use <...> time-stamps so that Calc can handle them.
2888 (setq form
2889 (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form))
2890 ;; Internationalize local time-stamps by setting locale to
2891 ;; "C".
2892 (setq form
2893 (replace-regexp-in-string
2894 org-ts-regexp
2895 (lambda (ts)
2896 (let ((system-time-locale "C"))
2897 (format-time-string
2898 (org-time-stamp-format
2899 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2900 (apply #'encode-time
2901 (save-match-data (org-parse-time-string ts))))))
2902 form t t))
2904 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2905 form
2906 (calc-eval (cons form org-tbl-calc-modes)
2907 (when (and (not keep-empty) numbers) 'num)))
2908 ev (if duration (org-table-time-seconds-to-string
2909 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2910 (string-to-number (org-table-time-string-to-seconds ev))
2911 (string-to-number ev))
2912 duration-output-format)
2913 ev)))
2915 (when org-table-formula-debug
2916 (with-output-to-temp-buffer "*Substitution History*"
2917 (princ (format "Substitution history of formula
2918 Orig: %s
2919 $xyz-> %s
2920 @r$c-> %s
2921 $1-> %s\n" orig formula form0 form))
2922 (if (consp ev)
2923 (princ (format " %s^\nError: %s"
2924 (make-string (car ev) ?\-) (nth 1 ev)))
2925 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2926 ev (or fmt "NONE")
2927 (if fmt (format fmt (string-to-number ev)) ev)))))
2928 (setq bw (get-buffer-window "*Substitution History*"))
2929 (org-fit-window-to-buffer bw)
2930 (unless (and (called-interactively-p 'any) (not ndown))
2931 (unless (let (inhibit-redisplay)
2932 (y-or-n-p "Debugging Formula. Continue to next? "))
2933 (org-table-align)
2934 (user-error "Abort"))
2935 (delete-window bw)
2936 (message "")))
2937 (when (consp ev) (setq fmt nil ev "#ERROR"))
2938 (org-table-justify-field-maybe
2939 (format org-table-formula-field-format
2940 (cond
2941 ((not (stringp ev)) ev)
2942 (fmt (format fmt (string-to-number ev)))
2943 ;; Replace any active time stamp in the result with
2944 ;; an inactive one. Dates in tables are likely
2945 ;; piece of regular data, not meant to appear in the
2946 ;; agenda.
2947 (t (replace-regexp-in-string org-ts-regexp "[\\1]" ev)))))
2948 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2949 (call-interactively 'org-return)
2950 (setq ndown 0)))
2951 (and down (org-table-maybe-recalculate-line))
2952 (or suppress-align (and org-table-may-need-update
2953 (org-table-align))))))
2955 (defun org-table-put-field-property (prop value)
2956 (save-excursion
2957 (put-text-property (progn (skip-chars-backward "^|") (point))
2958 (progn (skip-chars-forward "^|") (point))
2959 prop value)))
2961 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2962 "Get a calc vector from a column, according to descriptor DESC.
2964 Optional arguments TBEG and COL can give the beginning of the table and
2965 the current column, to avoid unnecessary parsing.
2967 HIGHLIGHT means just highlight the range.
2969 When CORNERS-ONLY is set, only return the corners of the range as
2970 a list (line1 column1 line2 column2) where line1 and line2 are
2971 line numbers relative to beginning of table, or TBEG, and column1
2972 and column2 are table column numbers."
2973 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
2974 (replace-regexp-in-string "\\$" "@0$" desc)
2975 desc))
2976 (col (or col (org-table-current-column)))
2977 (tbeg (or tbeg (org-table-begin)))
2978 (thisline (count-lines tbeg (line-beginning-position))))
2979 (unless (string-match org-table-range-regexp desc)
2980 (user-error "Invalid table range specifier `%s'" desc))
2981 (let ((rangep (match-end 3))
2982 (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
2983 (or (save-match-data
2984 (and (org-string-nw-p r)
2985 (org-table--descriptor-line r thisline)))
2986 thisline)))
2987 (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
2988 (or (save-match-data
2989 (and (org-string-nw-p r)
2990 (org-table--descriptor-line r thisline)))
2991 thisline)))
2992 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
2993 (if (or (not c) (= (string-to-number c) 0)) col
2994 (+ (string-to-number c)
2995 (if (memq (string-to-char c) '(?- ?+)) col 0)))))
2996 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
2997 (if (or (not c) (= (string-to-number c) 0)) col
2998 (+ (string-to-number c)
2999 (if (memq (string-to-char c) '(?- ?+)) col 0))))))
3000 (save-excursion
3001 (if (and (not corners-only)
3002 (or (not rangep) (and (= r1 r2) (= c1 c2))))
3003 ;; Just one field.
3004 (progn
3005 (forward-line (- r1 thisline))
3006 (while (not (looking-at org-table-dataline-regexp))
3007 (forward-line))
3008 (prog1 (org-trim (org-table-get-field c1))
3009 (when highlight (org-table-highlight-rectangle))))
3010 ;; A range, return a vector. First sort the numbers to get
3011 ;; a regular rectangle.
3012 (let ((first-row (min r1 r2))
3013 (last-row (max r1 r2))
3014 (first-column (min c1 c2))
3015 (last-column (max c1 c2)))
3016 (if corners-only (list first-row first-column last-row last-column)
3017 ;; Copy the range values into a list.
3018 (forward-line (- first-row thisline))
3019 (while (not (looking-at org-table-dataline-regexp))
3020 (forward-line)
3021 (cl-incf first-row))
3022 (org-table-goto-column first-column)
3023 (let ((beg (point)))
3024 (forward-line (- last-row first-row))
3025 (while (not (looking-at org-table-dataline-regexp))
3026 (forward-line -1))
3027 (org-table-goto-column last-column)
3028 (let ((end (point)))
3029 (when highlight
3030 (org-table-highlight-rectangle
3031 beg (progn (skip-chars-forward "^|\n") (point))))
3032 ;; Return string representation of calc vector.
3033 (mapcar #'org-trim
3034 (apply #'append
3035 (org-table-copy-region beg end))))))))))))
3037 (defun org-table--descriptor-line (desc cline)
3038 "Return relative line number corresponding to descriptor DESC.
3039 The cursor is currently in relative line number CLINE."
3040 (if (string-match "\\`[0-9]+\\'" desc)
3041 (aref org-table-dlines (string-to-number desc))
3042 (when (or (not (string-match
3043 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3044 ;; 1 2 3 4 5 6
3045 desc))
3046 (and (not (match-end 3)) (not (match-end 6)))
3047 (and (match-end 3) (match-end 6) (not (match-end 5))))
3048 (user-error "Invalid row descriptor `%s'" desc))
3049 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3050 (hdir (match-string 2 desc))
3051 (odir (match-string 5 desc))
3052 (on (and (match-end 6) (string-to-number (match-string 6 desc))))
3053 (rel (and (match-end 6)
3054 (or (and (match-end 1) (not (match-end 3)))
3055 (match-end 5)))))
3056 (when (and hn (not hdir))
3057 (setq cline 0)
3058 (setq hdir "+")
3059 (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn)))
3060 (when (and (not hn) on (not odir)) (user-error "Should never happen"))
3061 (when hn
3062 (setq cline
3063 (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
3064 (when on
3065 (setq cline
3066 (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
3067 cline)))
3069 (defun org-table--row-type (type n i backwards relative desc)
3070 "Return relative line of Nth row with type TYPE.
3071 Search starts from relative line I. When BACKWARDS in non-nil,
3072 look before I. When RELATIVE is non-nil, the reference is
3073 relative. DESC is the original descriptor that started the
3074 search, as a string."
3075 (let ((l (length org-table-current-line-types)))
3076 (catch :exit
3077 (dotimes (_ n)
3078 (while (and (cl-incf i (if backwards -1 1))
3079 (>= i 0)
3080 (< i l)
3081 (not (eq (aref org-table-current-line-types i) type))
3082 ;; We are going to cross a hline. Check if this is
3083 ;; an authorized move.
3084 (cond
3085 ((not relative))
3086 ((not (eq (aref org-table-current-line-types i) 'hline)))
3087 ((eq org-table-relative-ref-may-cross-hline t))
3088 ((eq org-table-relative-ref-may-cross-hline 'error)
3089 (user-error "Row descriptor %s crosses hline" desc))
3090 (t (cl-decf i (if backwards -1 1)) ; Step back.
3091 (throw :exit nil)))))))
3092 (cond ((or (< i 0) (>= i l))
3093 (user-error "Row descriptor %s leads outside table" desc))
3094 ;; The last hline doesn't exist. Instead, point to last row
3095 ;; in table.
3096 ((= i (1- l)) (1- i))
3097 (t i))))
3099 (defun org-table--error-on-old-row-references (s)
3100 (when (string-match "&[-+0-9I]" s)
3101 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3103 (defun org-table-make-reference (elements keep-empty numbers lispp)
3104 "Convert list ELEMENTS to something appropriate to insert into formula.
3105 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3106 NUMBERS indicates that everything should be converted to numbers.
3107 LISPP non-nil means to return something appropriate for a Lisp
3108 list, `literal' is for the format specifier L."
3109 ;; Calc nan (not a number) is used for the conversion of the empty
3110 ;; field to a reference for several reasons: (i) It is accepted in a
3111 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3112 ;; (ii) In a single field (not in range) it can be distinguished
3113 ;; from "(nan)" which is the reference made from a single field
3114 ;; containing "nan".
3115 (if (stringp elements)
3116 ;; field reference
3117 (if lispp
3118 (if (eq lispp 'literal)
3119 elements
3120 (if (and (eq elements "") (not keep-empty))
3122 (prin1-to-string
3123 (if numbers (string-to-number elements) elements))))
3124 (if (string-match "\\S-" elements)
3125 (progn
3126 (when numbers (setq elements (number-to-string
3127 (string-to-number elements))))
3128 (concat "(" elements ")"))
3129 (if (or (not keep-empty) numbers) "(0)" "nan")))
3130 ;; range reference
3131 (unless keep-empty
3132 (setq elements
3133 (delq nil
3134 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3135 elements))))
3136 (setq elements (or elements '())) ; if delq returns nil then we need '()
3137 (if lispp
3138 (mapconcat
3139 (lambda (x)
3140 (if (eq lispp 'literal)
3142 (prin1-to-string (if numbers (string-to-number x) x))))
3143 elements " ")
3144 (concat "[" (mapconcat
3145 (lambda (x)
3146 (if (string-match "\\S-" x)
3147 (if numbers
3148 (number-to-string (string-to-number x))
3150 (if (or (not keep-empty) numbers) "0" "nan")))
3151 elements
3152 ",") "]"))))
3154 (defun org-table-message-once-per-second (t1 &rest args)
3155 "If there has been more than one second since T1, display message.
3156 ARGS are passed as arguments to the `message' function. Returns
3157 current time if a message is printed, otherwise returns T1. If
3158 T1 is nil, always messages."
3159 (let ((curtime (current-time)))
3160 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3161 (progn (apply 'message args)
3162 curtime)
3163 t1)))
3165 ;;;###autoload
3166 (defun org-table-recalculate (&optional all noalign)
3167 "Recalculate the current table line by applying all stored formulas.
3169 With prefix arg ALL, do this for all lines in the table.
3171 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3172 if ALL is the symbol `iterate',
3173 recompute the table until it no longer changes.
3175 If NOALIGN is not nil, do not re-align the table after the computations
3176 are done. This is typically used internally to save time, if it is
3177 known that the table will be realigned a little later anyway."
3178 (interactive "P")
3179 (unless (memq this-command org-recalc-commands)
3180 (push this-command org-recalc-commands))
3181 (unless (org-at-table-p) (user-error "Not at a table"))
3182 (if (or (eq all 'iterate) (equal all '(16)))
3183 (org-table-iterate)
3184 (org-table-analyze)
3185 (let* ((eqlist (sort (org-table-get-stored-formulas)
3186 (lambda (a b) (string< (car a) (car b)))))
3187 (inhibit-redisplay (not debug-on-error))
3188 (line-re org-table-dataline-regexp)
3189 (log-first-time (current-time))
3190 (log-last-time log-first-time)
3191 (cnt 0)
3192 beg end eqlcol eqlfield)
3193 ;; Insert constants in all formulas.
3194 (when eqlist
3195 (org-table-save-field
3196 ;; Expand equations, then split the equation list between
3197 ;; column formulas and field formulas.
3198 (dolist (eq eqlist)
3199 (let* ((rhs (org-table-formula-substitute-names
3200 (org-table-formula-handle-first/last-rc (cdr eq))))
3201 (old-lhs (car eq))
3202 (lhs
3203 (org-table-formula-handle-first/last-rc
3204 (cond
3205 ((string-match "\\`@-?I+" old-lhs)
3206 (user-error "Can't assign to hline relative reference"))
3207 ((string-match "\\`$[<>]" old-lhs)
3208 (let ((new (org-table-formula-handle-first/last-rc
3209 old-lhs)))
3210 (when (assoc new eqlist)
3211 (user-error "\"%s=\" formula tries to overwrite \
3212 existing formula for column %s"
3213 old-lhs
3214 new))
3215 new))
3216 (t old-lhs)))))
3217 (if (string-match-p "\\`\\$[0-9]+\\'" lhs)
3218 (push (cons lhs rhs) eqlcol)
3219 (push (cons lhs rhs) eqlfield))))
3220 (setq eqlcol (nreverse eqlcol))
3221 ;; Expand ranges in lhs of formulas
3222 (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
3223 ;; Get the correct line range to process.
3224 (if all
3225 (progn
3226 (setq end (copy-marker (org-table-end)))
3227 (goto-char (setq beg org-table-current-begin-pos))
3228 (cond
3229 ((re-search-forward org-table-calculate-mark-regexp end t)
3230 ;; This is a table with marked lines, compute selected
3231 ;; lines.
3232 (setq line-re org-table-recalculate-regexp))
3233 ;; Move forward to the first non-header line.
3234 ((and (re-search-forward org-table-dataline-regexp end t)
3235 (re-search-forward org-table-hline-regexp end t)
3236 (re-search-forward org-table-dataline-regexp end t))
3237 (setq beg (match-beginning 0)))
3238 ;; Just leave BEG at the start of the table.
3239 (t nil)))
3240 (setq beg (line-beginning-position)
3241 end (copy-marker (line-beginning-position 2))))
3242 (goto-char beg)
3243 ;; Mark named fields untouchable. Also check if several
3244 ;; field/range formulas try to set the same field.
3245 (remove-text-properties beg end '(org-untouchable t))
3246 (let ((current-line (count-lines org-table-current-begin-pos
3247 (line-beginning-position)))
3248 seen-fields)
3249 (dolist (eq eqlfield)
3250 (let* ((name (car eq))
3251 (location (assoc name org-table-named-field-locations))
3252 (eq-line (or (nth 1 location)
3253 (and (string-match "\\`@\\([0-9]+\\)" name)
3254 (aref org-table-dlines
3255 (string-to-number
3256 (match-string 1 name))))))
3257 (reference
3258 (if location
3259 ;; Turn field coordinates associated to NAME
3260 ;; into an absolute reference.
3261 (format "@%d$%d"
3262 (org-table-line-to-dline eq-line)
3263 (nth 2 location))
3264 name)))
3265 (when (member reference seen-fields)
3266 (user-error "Several field/range formulas try to set %s"
3267 reference))
3268 (push reference seen-fields)
3269 (when (or all (eq eq-line current-line))
3270 (org-table-goto-field name)
3271 (org-table-put-field-property :org-untouchable t)))))
3272 ;; Evaluate the column formulas, but skip fields covered by
3273 ;; field formulas.
3274 (goto-char beg)
3275 (while (re-search-forward line-re end t)
3276 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3277 ;; Unprotected line, recalculate.
3278 (cl-incf cnt)
3279 (when all
3280 (setq log-last-time
3281 (org-table-message-once-per-second
3282 log-last-time
3283 "Re-applying formulas to full table...(line %d)" cnt)))
3284 (if (markerp org-last-recalc-line)
3285 (move-marker org-last-recalc-line (line-beginning-position))
3286 (setq org-last-recalc-line
3287 (copy-marker (line-beginning-position))))
3288 (dolist (entry eqlcol)
3289 (goto-char org-last-recalc-line)
3290 (org-table-goto-column
3291 (string-to-number (substring (car entry) 1)) nil 'force)
3292 (unless (get-text-property (point) :org-untouchable)
3293 (org-table-eval-formula
3294 nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
3295 ;; Evaluate the field formulas.
3296 (dolist (eq eqlfield)
3297 (let ((reference (car eq))
3298 (formula (cdr eq)))
3299 (setq log-last-time
3300 (org-table-message-once-per-second
3301 (and all log-last-time)
3302 "Re-applying formula to field: %s" (car eq)))
3303 (org-table-goto-field
3304 reference
3305 ;; Possibly create a new column, as long as
3306 ;; `org-table-formula-create-columns' allows it.
3307 (let ((column-count (progn (end-of-line)
3308 (1- (org-table-current-column)))))
3309 (lambda (column)
3310 (when (> column 1000)
3311 (user-error "Formula column target too large"))
3312 (and (> column column-count)
3313 (or (eq org-table-formula-create-columns t)
3314 (and (eq org-table-formula-create-columns 'warn)
3315 (progn
3316 (org-display-warning
3317 "Out-of-bounds formula added columns")
3319 (and (eq org-table-formula-create-columns 'prompt)
3320 (yes-or-no-p
3321 "Out-of-bounds formula. Add columns? ")))))))
3322 (org-table-eval-formula nil formula t t t t))))
3323 ;; Clean up markers and internal text property.
3324 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3325 (set-marker end nil)
3326 (unless noalign
3327 (when org-table-may-need-update (org-table-align))
3328 (when all
3329 (org-table-message-once-per-second
3330 log-first-time "Re-applying formulas to %d lines... done" cnt)))
3331 (org-table-message-once-per-second
3332 (and all log-first-time) "Re-applying formulas... done")))))
3334 ;;;###autoload
3335 (defun org-table-iterate (&optional arg)
3336 "Recalculate the table until it does not change anymore.
3337 The maximum number of iterations is 10, but you can choose a different value
3338 with the prefix ARG."
3339 (interactive "P")
3340 (let ((imax (if arg (prefix-numeric-value arg) 10))
3341 (i 0)
3342 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3343 thistbl)
3344 (catch 'exit
3345 (while (< i imax)
3346 (setq i (1+ i))
3347 (org-table-recalculate 'all)
3348 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3349 (if (not (string= lasttbl thistbl))
3350 (setq lasttbl thistbl)
3351 (if (> i 1)
3352 (message "Convergence after %d iterations" i)
3353 (message "Table was already stable"))
3354 (throw 'exit t)))
3355 (user-error "No convergence after %d iterations" i))))
3357 ;;;###autoload
3358 (defun org-table-recalculate-buffer-tables ()
3359 "Recalculate all tables in the current buffer."
3360 (interactive)
3361 (org-with-wide-buffer
3362 (org-table-map-tables
3363 (lambda ()
3364 ;; Reason for separate `org-table-align': When repeating
3365 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3366 ;; the way.
3367 (org-table-recalculate t t)
3368 (org-table-align))
3369 t)))
3371 ;;;###autoload
3372 (defun org-table-iterate-buffer-tables ()
3373 "Iterate all tables in the buffer, to converge inter-table dependencies."
3374 (interactive)
3375 (let* ((imax 10)
3376 (i imax)
3377 (checksum (md5 (buffer-string)))
3379 (org-with-wide-buffer
3380 (catch 'exit
3381 (while (> i 0)
3382 (setq i (1- i))
3383 (org-table-map-tables (lambda () (org-table-recalculate t t)) t)
3384 (if (equal checksum (setq c1 (md5 (buffer-string))))
3385 (progn
3386 (org-table-map-tables #'org-table-align t)
3387 (message "Convergence after %d iterations" (- imax i))
3388 (throw 'exit t))
3389 (setq checksum c1)))
3390 (org-table-map-tables #'org-table-align t)
3391 (user-error "No convergence after %d iterations" imax)))))
3393 (defun org-table-calc-current-TBLFM (&optional arg)
3394 "Apply the #+TBLFM in the line at point to the table."
3395 (interactive "P")
3396 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3397 (let ((formula (buffer-substring
3398 (line-beginning-position)
3399 (line-end-position))))
3400 (save-excursion
3401 ;; Insert a temporary formula at right after the table
3402 (goto-char (org-table-TBLFM-begin))
3403 (let ((s (point-marker)))
3404 (insert formula "\n")
3405 (let ((e (point-marker)))
3406 ;; Recalculate the table.
3407 (beginning-of-line 0) ; move to the inserted line
3408 (skip-chars-backward " \r\n\t")
3409 (unwind-protect
3410 (org-call-with-arg #'org-table-recalculate (or arg t))
3411 ;; Delete the formula inserted temporarily.
3412 (delete-region s e)
3413 (set-marker s nil)
3414 (set-marker e nil)))))))
3416 (defun org-table-TBLFM-begin ()
3417 "Find the beginning of the TBLFM lines and return its position.
3418 Return nil when the beginning of TBLFM line was not found."
3419 (save-excursion
3420 (when (progn (forward-line 1)
3421 (re-search-backward org-table-TBLFM-begin-regexp nil t))
3422 (line-beginning-position 2))))
3424 (defun org-table-expand-lhs-ranges (equations)
3425 "Expand list of formulas.
3426 If some of the RHS in the formulas are ranges or a row reference,
3427 expand them to individual field equations for each field. This
3428 function assumes the table is already analyzed (i.e., using
3429 `org-table-analyze')."
3430 (let (res)
3431 (dolist (e equations (nreverse res))
3432 (let ((lhs (car e))
3433 (rhs (cdr e)))
3434 (cond
3435 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
3436 ;; This just refers to one fixed field.
3437 (push e res))
3438 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
3439 ;; This just refers to one fixed named field.
3440 (push e res))
3441 ((string-match-p "\\`\\$[0-9]+\\'" lhs)
3442 ;; Column formulas are treated specially and are not
3443 ;; expanded.
3444 (push e res))
3445 ((string-match "\\`@[0-9]+\\'" lhs)
3446 (dotimes (ic org-table-current-ncol)
3447 (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
3448 rhs)
3449 res)))
3451 (let* ((range (org-table-get-range
3452 lhs org-table-current-begin-pos 1 nil 'corners))
3453 (r1 (org-table-line-to-dline (nth 0 range)))
3454 (c1 (nth 1 range))
3455 (r2 (org-table-line-to-dline (nth 2 range) 'above))
3456 (c2 (nth 3 range)))
3457 (cl-loop for ir from r1 to r2 do
3458 (cl-loop for ic from c1 to c2 do
3459 (push (cons (propertize
3460 (format "@%d$%d" ir ic) :orig-eqn e)
3461 rhs)
3462 res))))))))))
3464 (defun org-table-formula-handle-first/last-rc (s)
3465 "Replace @<, @>, $<, $> with first/last row/column of the table.
3466 So @< and $< will always be replaced with @1 and $1, respectively.
3467 The advantage of these special markers are that structure editing of
3468 the table will not change them, while @1 and $1 will be modified
3469 when a line/row is swapped out of that privileged position. So for
3470 formulas that use a range of rows or columns, it may often be better
3471 to anchor the formula with \"I\" row markers, or to offset from the
3472 borders of the table using the @< @> $< $> makers."
3473 (let (n nmax len char (start 0))
3474 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3475 s start)
3476 (if (match-end 3)
3477 (setq start (match-end 3))
3478 (setq nmax (if (equal (match-string 1 s) "@")
3479 (1- (length org-table-dlines))
3480 org-table-current-ncol)
3481 len (- (match-end 2) (match-beginning 2))
3482 char (string-to-char (match-string 2 s))
3483 n (if (= char ?<)
3485 (- nmax len -1)))
3486 (if (or (< n 1) (> n nmax))
3487 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3488 (match-string 0 s) s))
3489 (setq start (match-beginning 0))
3490 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3493 (defun org-table-formula-substitute-names (f)
3494 "Replace $const with values in string F."
3495 (let ((start 0)
3496 (pp (/= (string-to-char f) ?'))
3497 (duration (string-match-p ";.*[Tt].*\\'" f))
3498 (new (replace-regexp-in-string ; Check for column names.
3499 org-table-column-name-regexp
3500 (lambda (m)
3501 (concat "$" (cdr (assoc (match-string 1 m)
3502 org-table-column-names))))
3503 f t t)))
3504 ;; Parameters and constants.
3505 (while (setq start
3506 (string-match
3507 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3508 new start))
3509 (if (match-end 2) (setq start (match-end 2))
3510 (cl-incf start)
3511 ;; When a duration is expected, convert value on the fly.
3512 (let ((value
3513 (save-match-data
3514 (let ((v (org-table-get-constant (match-string 1 new))))
3515 (if (and (org-string-nw-p v) duration)
3516 (org-table-time-string-to-seconds v)
3517 v)))))
3518 (when value
3519 (setq new (replace-match
3520 (concat (and pp "(") value (and pp ")")) t t new))))))
3521 (if org-table-formula-debug (propertize new :orig-formula f) new)))
3523 (defun org-table-get-constant (const)
3524 "Find the value for a parameter or constant in a formula.
3525 Parameters get priority."
3526 (or (cdr (assoc const org-table-local-parameters))
3527 (cdr (assoc const org-table-formula-constants-local))
3528 (cdr (assoc const org-table-formula-constants))
3529 (and (fboundp 'constants-get) (constants-get const))
3530 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3531 (org-entry-get nil (substring const 5) 'inherit))
3532 "#UNDEFINED_NAME"))
3534 (defvar org-table-fedit-map
3535 (let ((map (make-sparse-keymap)))
3536 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3537 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3538 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3539 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3540 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3541 (org-defkey map "\C-c?" 'org-table-show-reference)
3542 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3543 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3544 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3545 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3546 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3547 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3548 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3549 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3550 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3551 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3552 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3553 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3554 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3555 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3556 map))
3558 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3559 '("Edit-Formulas"
3560 ["Finish and Install" org-table-fedit-finish t]
3561 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3562 ["Abort" org-table-fedit-abort t]
3563 "--"
3564 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3565 ["Complete Lisp Symbol" lisp-complete-symbol t]
3566 "--"
3567 "Shift Reference at Point"
3568 ["Up" org-table-fedit-ref-up t]
3569 ["Down" org-table-fedit-ref-down t]
3570 ["Left" org-table-fedit-ref-left t]
3571 ["Right" org-table-fedit-ref-right t]
3573 "Change Test Row for Column Formulas"
3574 ["Up" org-table-fedit-line-up t]
3575 ["Down" org-table-fedit-line-down t]
3576 "--"
3577 ["Scroll Table Window" org-table-fedit-scroll t]
3578 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3579 ["Show Table Grid" org-table-fedit-toggle-coordinates
3580 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3581 org-table-overlay-coordinates)]
3582 "--"
3583 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3584 :style toggle :selected org-table-buffer-is-an]))
3586 (defvar org-pos)
3587 (defvar org-table--fedit-source nil
3588 "Position of the TBLFM line being edited.")
3590 ;;;###autoload
3591 (defun org-table-edit-formulas ()
3592 "Edit the formulas of the current table in a separate buffer."
3593 (interactive)
3594 (let ((at-tblfm (org-at-TBLFM-p)))
3595 (unless (or at-tblfm (org-at-table-p))
3596 (user-error "Not at a table"))
3597 (save-excursion
3598 ;; Move point within the table before analyzing it.
3599 (when at-tblfm (re-search-backward "^[ \t]*|"))
3600 (org-table-analyze))
3601 (let ((key (org-table-current-field-formula 'key 'noerror))
3602 (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point)))
3603 #'org-table-formula-less-p))
3604 (pos (point-marker))
3605 (source (copy-marker (line-beginning-position)))
3606 (startline 1)
3607 (wc (current-window-configuration))
3608 (sel-win (selected-window))
3609 (titles '((column . "# Column Formulas\n")
3610 (field . "# Field and Range Formulas\n")
3611 (named . "# Named Field Formulas\n"))))
3612 (org-switch-to-buffer-other-window "*Edit Formulas*")
3613 (erase-buffer)
3614 ;; Keep global-font-lock-mode from turning on font-lock-mode
3615 (let ((font-lock-global-modes '(not fundamental-mode)))
3616 (fundamental-mode))
3617 (setq-local font-lock-global-modes (list 'not major-mode))
3618 (setq-local org-pos pos)
3619 (setq-local org-table--fedit-source source)
3620 (setq-local org-window-configuration wc)
3621 (setq-local org-selected-window sel-win)
3622 (use-local-map org-table-fedit-map)
3623 (add-hook 'post-command-hook #'org-table-fedit-post-command t t)
3624 (easy-menu-add org-table-fedit-menu)
3625 (setq startline (org-current-line))
3626 (dolist (entry eql)
3627 (let* ((type (cond
3628 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry))
3629 'column)
3630 ((equal (string-to-char (car entry)) ?@) 'field)
3631 (t 'named)))
3632 (title (assq type titles)))
3633 (when title
3634 (unless (bobp) (insert "\n"))
3635 (insert
3636 (org-add-props (cdr title) nil 'face font-lock-comment-face))
3637 (setq titles (remove title titles)))
3638 (when (equal key (car entry)) (setq startline (org-current-line)))
3639 (let ((s (concat
3640 (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$")
3641 (car entry) " = " (cdr entry) "\n")))
3642 (remove-text-properties 0 (length s) '(face nil) s)
3643 (insert s))))
3644 (when (eq org-table-use-standard-references t)
3645 (org-table-fedit-toggle-ref-type))
3646 (org-goto-line startline)
3647 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3648 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3649 See menu for more commands.")))))
3651 (defun org-table-fedit-post-command ()
3652 (when (not (memq this-command '(lisp-complete-symbol)))
3653 (let ((win (selected-window)))
3654 (save-excursion
3655 (ignore-errors (org-table-show-reference))
3656 (select-window win)))))
3658 (defun org-table-formula-to-user (s)
3659 "Convert a formula from internal to user representation."
3660 (if (eq org-table-use-standard-references t)
3661 (org-table-convert-refs-to-an s)
3664 (defun org-table-formula-from-user (s)
3665 "Convert a formula from user to internal representation."
3666 (if org-table-use-standard-references
3667 (org-table-convert-refs-to-rc s)
3670 (defun org-table-convert-refs-to-rc (s)
3671 "Convert spreadsheet references from A7 to @7$28.
3672 Works for single references, but also for entire formulas and even the
3673 full TBLFM line."
3674 (let ((start 0))
3675 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3676 (cond
3677 ((match-end 3)
3678 ;; format match, just advance
3679 (setq start (match-end 0)))
3680 ((and (> (match-beginning 0) 0)
3681 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3682 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3683 ;; 3.e5 or something like this.
3684 (setq start (match-end 0)))
3685 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3686 ;; (member (match-string 1 s)
3687 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3689 ;; function name, just advance
3690 (setq start (match-end 0)))
3692 (setq start (match-beginning 0)
3693 s (replace-match
3694 (if (equal (match-string 2 s) "&")
3695 (format "$%d" (org-letters-to-number (match-string 1 s)))
3696 (format "@%d$%d"
3697 (string-to-number (match-string 2 s))
3698 (org-letters-to-number (match-string 1 s))))
3699 t t s)))))
3702 (defun org-table-convert-refs-to-an (s)
3703 "Convert spreadsheet references from to @7$28 to AB7.
3704 Works for single references, but also for entire formulas and even the
3705 full TBLFM line."
3706 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3707 (setq s (replace-match
3708 (format "%s%d"
3709 (org-number-to-letters
3710 (string-to-number (match-string 2 s)))
3711 (string-to-number (match-string 1 s)))
3712 t t s)))
3713 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3714 (setq s (replace-match (concat "\\1"
3715 (org-number-to-letters
3716 (string-to-number (match-string 2 s))) "&")
3717 t nil s)))
3720 (defun org-letters-to-number (s)
3721 "Convert a base 26 number represented by letters into an integer.
3722 For example: AB -> 28."
3723 (let ((n 0))
3724 (setq s (upcase s))
3725 (while (> (length s) 0)
3726 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3727 s (substring s 1)))
3730 (defun org-number-to-letters (n)
3731 "Convert an integer into a base 26 number represented by letters.
3732 For example: 28 -> AB."
3733 (let ((s ""))
3734 (while (> n 0)
3735 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3736 n (/ (1- n) 26)))
3739 (defun org-table-time-string-to-seconds (s)
3740 "Convert a time string into numerical duration in seconds.
3741 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3742 If S is a string representing a number, keep this number."
3743 (if (equal s "")
3745 (let (hour minus min sec res)
3746 (cond
3747 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3748 (setq minus (< 0 (length (match-string 1 s)))
3749 hour (string-to-number (match-string 2 s))
3750 min (string-to-number (match-string 3 s))
3751 sec (string-to-number (match-string 4 s)))
3752 (if minus
3753 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3754 (setq res (+ (* hour 3600) (* min 60) sec))))
3755 ((and (not (string-match org-ts-regexp-both s))
3756 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3757 (setq minus (< 0 (length (match-string 1 s)))
3758 hour (string-to-number (match-string 2 s))
3759 min (string-to-number (match-string 3 s)))
3760 (if minus
3761 (setq res (- (+ (* hour 3600) (* min 60))))
3762 (setq res (+ (* hour 3600) (* min 60)))))
3763 (t (setq res (string-to-number s))))
3764 (number-to-string res))))
3766 (defun org-table-time-seconds-to-string (secs &optional output-format)
3767 "Convert a number of seconds to a time string.
3768 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3769 minutes or seconds."
3770 (let* ((secs0 (abs secs))
3771 (res
3772 (cond ((eq output-format 'days)
3773 (format "%.3f" (/ (float secs0) 86400)))
3774 ((eq output-format 'hours)
3775 (format "%.2f" (/ (float secs0) 3600)))
3776 ((eq output-format 'minutes)
3777 (format "%.1f" (/ (float secs0) 60)))
3778 ((eq output-format 'seconds)
3779 (format "%d" secs0))
3780 ((eq output-format 'hh:mm)
3781 ;; Ignore seconds
3782 (substring (format-seconds
3783 (if org-table-duration-hour-zero-padding
3784 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3785 secs0)
3786 0 -3))
3787 (t (format-seconds
3788 (if org-table-duration-hour-zero-padding
3789 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3790 secs0)))))
3791 (if (< secs 0) (concat "-" res) res)))
3793 (defun org-table-fedit-convert-buffer (function)
3794 "Convert all references in this buffer, using FUNCTION."
3795 (let ((origin (copy-marker (line-beginning-position))))
3796 (goto-char (point-min))
3797 (while (not (eobp))
3798 (insert (funcall function (buffer-substring (point) (line-end-position))))
3799 (delete-region (point) (line-end-position))
3800 (forward-line))
3801 (goto-char origin)
3802 (set-marker origin nil)))
3804 (defun org-table-fedit-toggle-ref-type ()
3805 "Convert all references in the buffer from B3 to @3$2 and back."
3806 (interactive)
3807 (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
3808 (org-table-fedit-convert-buffer
3809 (if org-table-buffer-is-an
3810 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3811 (message "Reference type switched to %s"
3812 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3814 (defun org-table-fedit-ref-up ()
3815 "Shift the reference at point one row/hline up."
3816 (interactive)
3817 (org-table-fedit-shift-reference 'up))
3818 (defun org-table-fedit-ref-down ()
3819 "Shift the reference at point one row/hline down."
3820 (interactive)
3821 (org-table-fedit-shift-reference 'down))
3822 (defun org-table-fedit-ref-left ()
3823 "Shift the reference at point one field to the left."
3824 (interactive)
3825 (org-table-fedit-shift-reference 'left))
3826 (defun org-table-fedit-ref-right ()
3827 "Shift the reference at point one field to the right."
3828 (interactive)
3829 (org-table-fedit-shift-reference 'right))
3831 (defun org-table-fedit-shift-reference (dir)
3832 (cond
3833 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3834 (if (memq dir '(left right))
3835 (org-rematch-and-replace 1 (eq dir 'left))
3836 (user-error "Cannot shift reference in this direction")))
3837 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3838 ;; A B3-like reference
3839 (if (memq dir '(up down))
3840 (org-rematch-and-replace 2 (eq dir 'up))
3841 (org-rematch-and-replace 1 (eq dir 'left))))
3842 ((org-in-regexp
3843 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3844 ;; An internal reference
3845 (if (memq dir '(up down))
3846 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3847 (org-rematch-and-replace 5 (eq dir 'left))))))
3849 (defun org-rematch-and-replace (n &optional decr hline)
3850 "Re-match the group N, and replace it with the shifted reference."
3851 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3852 (goto-char (match-beginning n))
3853 (and (looking-at (regexp-quote (match-string n)))
3854 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3855 t t)))
3857 (defun org-table-shift-refpart (ref &optional decr hline)
3858 "Shift a reference part REF.
3859 If DECR is set, decrease the references row/column, else increase.
3860 If HLINE is set, this may be a hline reference, it certainly is not
3861 a translation reference."
3862 (save-match-data
3863 (let* ((sign (string-match "^[-+]" ref)) n)
3865 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3866 (cond
3867 ((and hline (string-match "^I+" ref))
3868 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3869 (setq n (+ n (if decr -1 1)))
3870 (if (= n 0) (setq n (+ n (if decr -1 1))))
3871 (if sign
3872 (setq sign (if (< n 0) "-" "+") n (abs n))
3873 (setq n (max 1 n)))
3874 (concat sign (make-string n ?I)))
3876 ((string-match "^[0-9]+" ref)
3877 (setq n (string-to-number (concat sign ref)))
3878 (setq n (+ n (if decr -1 1)))
3879 (if sign
3880 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3881 (number-to-string (max 1 n))))
3883 ((string-match "^[a-zA-Z]+" ref)
3884 (org-number-to-letters
3885 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3887 (t (user-error "Cannot shift reference"))))))
3889 (defun org-table-fedit-toggle-coordinates ()
3890 "Toggle the display of coordinates in the referenced table."
3891 (interactive)
3892 (let ((pos (marker-position org-pos)))
3893 (with-current-buffer (marker-buffer org-pos)
3894 (save-excursion
3895 (goto-char pos)
3896 (org-table-toggle-coordinate-overlays)))))
3898 (defun org-table-fedit-finish (&optional arg)
3899 "Parse the buffer for formula definitions and install them.
3900 With prefix ARG, apply the new formulas to the table."
3901 (interactive "P")
3902 (org-table-remove-rectangle-highlight)
3903 (when org-table-use-standard-references
3904 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3905 (setq org-table-buffer-is-an nil))
3906 (let ((pos org-pos)
3907 (sel-win org-selected-window)
3908 (source org-table--fedit-source)
3909 eql)
3910 (goto-char (point-min))
3911 (while (re-search-forward
3912 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3913 nil t)
3914 (let ((var (match-string 1))
3915 (form (org-trim (match-string 3))))
3916 (unless (equal form "")
3917 (while (string-match "[ \t]*\n[ \t]*" form)
3918 (setq form (replace-match " " t t form)))
3919 (when (assoc var eql)
3920 (user-error "Double formulas for %s" var))
3921 (push (cons var form) eql))))
3922 (set-window-configuration org-window-configuration)
3923 (select-window sel-win)
3924 (goto-char source)
3925 (org-table-store-formulas eql)
3926 (set-marker pos nil)
3927 (set-marker source nil)
3928 (kill-buffer "*Edit Formulas*")
3929 (if arg
3930 (org-table-recalculate 'all)
3931 (message "New formulas installed - press C-u C-c C-c to apply."))))
3933 (defun org-table-fedit-abort ()
3934 "Abort editing formulas, without installing the changes."
3935 (interactive)
3936 (org-table-remove-rectangle-highlight)
3937 (let ((pos org-pos) (sel-win org-selected-window))
3938 (set-window-configuration org-window-configuration)
3939 (select-window sel-win)
3940 (goto-char pos)
3941 (move-marker pos nil)
3942 (message "Formula editing aborted without installing changes")))
3944 (defun org-table-fedit-lisp-indent ()
3945 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3946 (interactive)
3947 (let ((pos (point)) beg end ind)
3948 (beginning-of-line 1)
3949 (cond
3950 ((looking-at "[ \t]")
3951 (goto-char pos)
3952 (call-interactively 'lisp-indent-line))
3953 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3954 ((not (fboundp 'pp-buffer))
3955 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3956 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3957 (goto-char (- (match-end 0) 2))
3958 (setq beg (point))
3959 (setq ind (make-string (current-column) ?\ ))
3960 (condition-case nil (forward-sexp 1)
3961 (error
3962 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3963 (setq end (point))
3964 (save-restriction
3965 (narrow-to-region beg end)
3966 (if (eq last-command this-command)
3967 (progn
3968 (goto-char (point-min))
3969 (setq this-command nil)
3970 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3971 (replace-match " ")))
3972 (pp-buffer)
3973 (untabify (point-min) (point-max))
3974 (goto-char (1+ (point-min)))
3975 (while (re-search-forward "^." nil t)
3976 (beginning-of-line 1)
3977 (insert ind))
3978 (goto-char (point-max))
3979 (org-delete-backward-char 1)))
3980 (goto-char beg))
3981 (t nil))))
3983 (defvar org-show-positions nil)
3985 (defun org-table-show-reference (&optional local)
3986 "Show the location/value of the $ expression at point.
3987 When LOCAL is non-nil, show references for the table at point."
3988 (interactive)
3989 (org-table-remove-rectangle-highlight)
3990 (when local (org-table-analyze))
3991 (catch 'exit
3992 (let ((pos (if local (point) org-pos))
3993 (face2 'highlight)
3994 (org-inhibit-highlight-removal t)
3995 (win (selected-window))
3996 (org-show-positions nil)
3997 var name e what match dest)
3998 (setq what (cond
3999 ((org-in-regexp "^@[0-9]+[ \t=]")
4000 (setq match (concat (substring (match-string 0) 0 -1)
4001 "$1.."
4002 (substring (match-string 0) 0 -1)
4003 "$100"))
4004 'range)
4005 ((or (org-in-regexp org-table-range-regexp2)
4006 (org-in-regexp org-table-translate-regexp)
4007 (org-in-regexp org-table-range-regexp))
4008 (setq match
4009 (save-match-data
4010 (org-table-convert-refs-to-rc (match-string 0))))
4011 'range)
4012 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
4013 ((org-in-regexp "\\$[0-9]+") 'column)
4014 ((not local) nil)
4015 (t (user-error "No reference at point")))
4016 match (and what (or match (match-string 0))))
4017 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
4018 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
4019 'secondary-selection))
4020 (add-hook 'before-change-functions
4021 #'org-table-remove-rectangle-highlight)
4022 (when (eq what 'name) (setq var (substring match 1)))
4023 (when (eq what 'range)
4024 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
4025 (setq match (org-table-formula-substitute-names match)))
4026 (unless local
4027 (save-excursion
4028 (end-of-line)
4029 (re-search-backward "^\\S-" nil t)
4030 (beginning-of-line)
4031 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4032 \\([0-9]+\\|&\\)\\) *=")
4033 (setq dest
4034 (save-match-data
4035 (org-table-convert-refs-to-rc (match-string 1))))
4036 (org-table-add-rectangle-overlay
4037 (match-beginning 1) (match-end 1) face2))))
4038 (if (and (markerp pos) (marker-buffer pos))
4039 (if (get-buffer-window (marker-buffer pos))
4040 (select-window (get-buffer-window (marker-buffer pos)))
4041 (org-switch-to-buffer-other-window (get-buffer-window
4042 (marker-buffer pos)))))
4043 (goto-char pos)
4044 (org-table-force-dataline)
4045 (let ((table-start
4046 (if local org-table-current-begin-pos (org-table-begin))))
4047 (when dest
4048 (setq name (substring dest 1))
4049 (cond
4050 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
4051 (org-table-goto-field dest))
4052 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4053 dest)
4054 (org-table-goto-field dest))
4055 (t (org-table-goto-column (string-to-number name))))
4056 (move-marker pos (point))
4057 (org-table-highlight-rectangle nil nil face2))
4058 (cond
4059 ((equal dest match))
4060 ((not match))
4061 ((eq what 'range)
4062 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
4063 ((setq e (assoc var org-table-named-field-locations))
4064 (org-table-goto-field var)
4065 (org-table-highlight-rectangle)
4066 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
4067 ((setq e (assoc var org-table-column-names))
4068 (org-table-goto-column (string-to-number (cdr e)))
4069 (org-table-highlight-rectangle)
4070 (goto-char table-start)
4071 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
4072 (org-table-end) t)
4073 (progn
4074 (goto-char (match-beginning 1))
4075 (org-table-highlight-rectangle)
4076 (message "Named column (column %s)" (cdr e)))
4077 (user-error "Column name not found")))
4078 ((eq what 'column)
4079 ;; Column number.
4080 (org-table-goto-column (string-to-number (substring match 1)))
4081 (org-table-highlight-rectangle)
4082 (message "Column %s" (substring match 1)))
4083 ((setq e (assoc var org-table-local-parameters))
4084 (goto-char table-start)
4085 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
4086 (progn
4087 (goto-char (match-beginning 1))
4088 (org-table-highlight-rectangle)
4089 (message "Local parameter."))
4090 (user-error "Parameter not found")))
4091 ((not var) (user-error "No reference at point"))
4092 ((setq e (assoc var org-table-formula-constants-local))
4093 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4094 var (cdr e)))
4095 ((setq e (assoc var org-table-formula-constants))
4096 (message "Constant: $%s=%s in `org-table-formula-constants'."
4097 var (cdr e)))
4098 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4099 (message "Constant: $%s=%s, from `constants.el'%s."
4100 var e (format " (%s units)" constants-unit-system)))
4101 (t (user-error "Undefined name $%s" var)))
4102 (goto-char pos)
4103 (when (and org-show-positions
4104 (not (memq this-command '(org-table-fedit-scroll
4105 org-table-fedit-scroll-down))))
4106 (push pos org-show-positions)
4107 (push table-start org-show-positions)
4108 (let ((min (apply 'min org-show-positions))
4109 (max (apply 'max org-show-positions)))
4110 (set-window-start (selected-window) min)
4111 (goto-char max)
4112 (or (pos-visible-in-window-p max)
4113 (set-window-start (selected-window) max)))))
4114 (select-window win))))
4116 (defun org-table-force-dataline ()
4117 "Make sure the cursor is in a dataline in a table."
4118 (unless (save-excursion
4119 (beginning-of-line 1)
4120 (looking-at org-table-dataline-regexp))
4121 (let* ((re org-table-dataline-regexp)
4122 (p1 (save-excursion (re-search-forward re nil 'move)))
4123 (p2 (save-excursion (re-search-backward re nil 'move))))
4124 (cond ((and p1 p2)
4125 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4126 p1 p2)))
4127 ((or p1 p2) (goto-char (or p1 p2)))
4128 (t (user-error "No table dataline around here"))))))
4130 (defun org-table-fedit-line-up ()
4131 "Move cursor one line up in the window showing the table."
4132 (interactive)
4133 (org-table-fedit-move 'previous-line))
4135 (defun org-table-fedit-line-down ()
4136 "Move cursor one line down in the window showing the table."
4137 (interactive)
4138 (org-table-fedit-move 'next-line))
4140 (defun org-table-fedit-move (command)
4141 "Move the cursor in the window showing the table.
4142 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4143 (let ((org-table-allow-automatic-line-recalculation nil)
4144 (pos org-pos) (win (selected-window)) p)
4145 (select-window (get-buffer-window (marker-buffer org-pos)))
4146 (setq p (point))
4147 (call-interactively command)
4148 (while (and (org-at-table-p)
4149 (org-at-table-hline-p))
4150 (call-interactively command))
4151 (or (org-at-table-p) (goto-char p))
4152 (move-marker pos (point))
4153 (select-window win)))
4155 (defun org-table-fedit-scroll (N)
4156 (interactive "p")
4157 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4158 (scroll-other-window N)))
4160 (defun org-table-fedit-scroll-down (N)
4161 (interactive "p")
4162 (org-table-fedit-scroll (- N)))
4164 (defvar org-table-rectangle-overlays nil)
4166 (defun org-table-add-rectangle-overlay (beg end &optional face)
4167 "Add a new overlay."
4168 (let ((ov (make-overlay beg end)))
4169 (overlay-put ov 'face (or face 'secondary-selection))
4170 (push ov org-table-rectangle-overlays)))
4172 (defun org-table-highlight-rectangle (&optional beg end face)
4173 "Highlight rectangular region in a table.
4174 When buffer positions BEG and END are provided, use them to
4175 delimit the region to highlight. Otherwise, refer to point. Use
4176 FACE, when non-nil, for the highlight."
4177 (let* ((beg (or beg (point)))
4178 (end (or end (point)))
4179 (b (min beg end))
4180 (e (max beg end))
4181 (start-coordinates
4182 (save-excursion
4183 (goto-char b)
4184 (cons (line-beginning-position) (org-table-current-column))))
4185 (end-coordinates
4186 (save-excursion
4187 (goto-char e)
4188 (cons (line-beginning-position) (org-table-current-column)))))
4189 (when (boundp 'org-show-positions)
4190 (setq org-show-positions (cons b (cons e org-show-positions))))
4191 (goto-char (car start-coordinates))
4192 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4193 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4194 (last-row (car end-coordinates)))
4195 (while (<= (point) last-row)
4196 (when (looking-at org-table-dataline-regexp)
4197 (org-table-goto-column column-start)
4198 (skip-chars-backward "^|\n")
4199 (let ((p (point)))
4200 (org-table-goto-column column-end)
4201 (skip-chars-forward "^|\n")
4202 (org-table-add-rectangle-overlay p (point) face)))
4203 (forward-line)))
4204 (goto-char (car start-coordinates)))
4205 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4207 (defun org-table-remove-rectangle-highlight (&rest _ignore)
4208 "Remove the rectangle overlays."
4209 (unless org-inhibit-highlight-removal
4210 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4211 (mapc 'delete-overlay org-table-rectangle-overlays)
4212 (setq org-table-rectangle-overlays nil)))
4214 (defvar-local org-table-coordinate-overlays nil
4215 "Collects the coordinate grid overlays, so that they can be removed.")
4217 (defun org-table-overlay-coordinates ()
4218 "Add overlays to the table at point, to show row/column coordinates."
4219 (interactive)
4220 (mapc 'delete-overlay org-table-coordinate-overlays)
4221 (setq org-table-coordinate-overlays nil)
4222 (save-excursion
4223 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4224 (goto-char (org-table-begin))
4225 (while (org-at-table-p)
4226 (setq eol (point-at-eol))
4227 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4228 (push ov org-table-coordinate-overlays)
4229 (setq hline (looking-at org-table-hline-regexp))
4230 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4231 (format "%4d" (setq id (1+ id)))))
4232 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4233 (when hline
4234 (setq ic 0)
4235 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4236 (setq beg (1+ (match-beginning 0))
4237 ic (1+ ic)
4238 s1 (concat "$" (int-to-string ic))
4239 s2 (org-number-to-letters ic)
4240 str (if (eq org-table-use-standard-references t) s2 s1))
4241 (setq ov (make-overlay beg (+ beg (length str))))
4242 (push ov org-table-coordinate-overlays)
4243 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4244 (beginning-of-line 2)))))
4246 ;;;###autoload
4247 (defun org-table-toggle-coordinate-overlays ()
4248 "Toggle the display of Row/Column numbers in tables."
4249 (interactive)
4250 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4251 (message "Tables Row/Column numbers display turned %s"
4252 (if org-table-overlay-coordinates "on" "off"))
4253 (if (and (org-at-table-p) org-table-overlay-coordinates)
4254 (org-table-align))
4255 (unless org-table-overlay-coordinates
4256 (mapc 'delete-overlay org-table-coordinate-overlays)
4257 (setq org-table-coordinate-overlays nil)))
4259 ;;;###autoload
4260 (defun org-table-toggle-formula-debugger ()
4261 "Toggle the formula debugger in tables."
4262 (interactive)
4263 (setq org-table-formula-debug (not org-table-formula-debug))
4264 (message "Formula debugging has been turned %s"
4265 (if org-table-formula-debug "on" "off")))
4267 ;;; The orgtbl minor mode
4269 ;; Define a minor mode which can be used in other modes in order to
4270 ;; integrate the Org table editor.
4272 ;; This is really a hack, because the Org table editor uses several
4273 ;; keys which normally belong to the major mode, for example the TAB
4274 ;; and RET keys. Here is how it works: The minor mode defines all the
4275 ;; keys necessary to operate the table editor, but wraps the commands
4276 ;; into a function which tests if the cursor is currently inside
4277 ;; a table. If that is the case, the table editor command is
4278 ;; executed. However, when any of those keys is used outside a table,
4279 ;; the function uses `key-binding' to look up if the key has an
4280 ;; associated command in another currently active keymap (minor modes,
4281 ;; major mode, global), and executes that command. There might be
4282 ;; problems if any of the keys used by the table editor is otherwise
4283 ;; used as a prefix key.
4285 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4286 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4287 ;; addresses this by checking explicitly for both bindings.
4289 ;; The optimized version (see variable `orgtbl-optimized') takes over
4290 ;; all keys which are bound to `self-insert-command' in the *global map*.
4291 ;; Some modes bind other commands to simple characters, for example
4292 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4293 ;; active, this binding is ignored inside tables and replaced with a
4294 ;; modified self-insert.
4297 (defvar orgtbl-mode-map (make-keymap)
4298 "Keymap for `orgtbl-mode'.")
4300 (defvar org-old-auto-fill-inhibit-regexp nil
4301 "Local variable used by `orgtbl-mode'.")
4303 (defconst orgtbl-line-start-regexp
4304 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4305 "Matches a line belonging to an orgtbl.")
4307 (defconst orgtbl-extra-font-lock-keywords
4308 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4309 0 (quote 'org-table) 'prepend))
4310 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4312 ;; Install it as a minor mode.
4313 (put 'orgtbl-mode :included t)
4314 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4316 ;;;###autoload
4317 (define-minor-mode orgtbl-mode
4318 "The `org-mode' table editor as a minor mode for use in other modes."
4319 :lighter " OrgTbl" :keymap orgtbl-mode-map
4320 (org-load-modules-maybe)
4321 (cond
4322 ((derived-mode-p 'org-mode)
4323 ;; Exit without error, in case some hook functions calls this
4324 ;; by accident in org-mode.
4325 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4326 (orgtbl-mode
4327 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4328 ;; Make sure we are first in minor-mode-map-alist
4329 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4330 ;; FIXME: maybe it should use emulation-mode-map-alists?
4331 (and c (setq minor-mode-map-alist
4332 (cons c (delq c minor-mode-map-alist)))))
4333 (setq-local org-table-may-need-update t)
4334 (add-hook 'before-change-functions 'org-before-change-function
4335 nil 'local)
4336 (setq-local org-old-auto-fill-inhibit-regexp
4337 auto-fill-inhibit-regexp)
4338 (setq-local auto-fill-inhibit-regexp
4339 (if auto-fill-inhibit-regexp
4340 (concat orgtbl-line-start-regexp "\\|"
4341 auto-fill-inhibit-regexp)
4342 orgtbl-line-start-regexp))
4343 (add-to-invisibility-spec '(org-cwidth))
4344 (when (fboundp 'font-lock-add-keywords)
4345 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4346 (org-restart-font-lock))
4347 (easy-menu-add orgtbl-mode-menu))
4349 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4350 (org-table-cleanup-narrow-column-properties)
4351 (org-remove-from-invisibility-spec '(org-cwidth))
4352 (remove-hook 'before-change-functions 'org-before-change-function t)
4353 (when (fboundp 'font-lock-remove-keywords)
4354 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4355 (org-restart-font-lock))
4356 (easy-menu-remove orgtbl-mode-menu)
4357 (force-mode-line-update 'all))))
4359 (defun org-table-cleanup-narrow-column-properties ()
4360 "Remove all properties related to narrow-column invisibility."
4361 (let ((s (point-min)))
4362 (while (setq s (text-property-any s (point-max)
4363 'display org-narrow-column-arrow))
4364 (remove-text-properties s (1+ s) '(display t)))
4365 (setq s (point-min))
4366 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4367 (remove-text-properties s (1+ s) '(org-cwidth t)))
4368 (setq s (point-min))
4369 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4370 (remove-text-properties s (1+ s) '(invisible t)))))
4372 (defun orgtbl-make-binding (fun n &rest keys)
4373 "Create a function for binding in the table minor mode.
4374 FUN is the command to call inside a table. N is used to create a unique
4375 command name. KEYS are keys that should be checked in for a command
4376 to execute outside of tables."
4377 (eval
4378 (list 'defun
4379 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4380 '(arg)
4381 (concat "In tables, run `" (symbol-name fun) "'.\n"
4382 "Outside of tables, run the binding of `"
4383 (mapconcat #'key-description keys "' or `")
4384 "'.")
4385 '(interactive "p")
4386 (list 'if
4387 '(org-at-table-p)
4388 (list 'call-interactively (list 'quote fun))
4389 (list 'let '(orgtbl-mode)
4390 (list 'call-interactively
4391 (append '(or)
4392 (mapcar (lambda (k)
4393 (list 'key-binding k))
4394 keys)
4395 '('orgtbl-error))))))))
4397 (defun orgtbl-error ()
4398 "Error when there is no default binding for a table key."
4399 (interactive)
4400 (user-error "This key has no function outside tables"))
4402 (defun orgtbl-setup ()
4403 "Setup orgtbl keymaps."
4404 (let ((nfunc 0)
4405 (bindings
4406 '(([(meta shift left)] org-table-delete-column)
4407 ([(meta left)] org-table-move-column-left)
4408 ([(meta right)] org-table-move-column-right)
4409 ([(meta shift right)] org-table-insert-column)
4410 ([(meta shift up)] org-table-kill-row)
4411 ([(meta shift down)] org-table-insert-row)
4412 ([(meta up)] org-table-move-row-up)
4413 ([(meta down)] org-table-move-row-down)
4414 ("\C-c\C-w" org-table-cut-region)
4415 ("\C-c\M-w" org-table-copy-region)
4416 ("\C-c\C-y" org-table-paste-rectangle)
4417 ("\C-c\C-w" org-table-wrap-region)
4418 ("\C-c-" org-table-insert-hline)
4419 ("\C-c}" org-table-toggle-coordinate-overlays)
4420 ("\C-c{" org-table-toggle-formula-debugger)
4421 ("\C-m" org-table-next-row)
4422 ([(shift return)] org-table-copy-down)
4423 ("\C-c?" org-table-field-info)
4424 ("\C-c " org-table-blank-field)
4425 ("\C-c+" org-table-sum)
4426 ("\C-c=" org-table-eval-formula)
4427 ("\C-c'" org-table-edit-formulas)
4428 ("\C-c`" org-table-edit-field)
4429 ("\C-c*" org-table-recalculate)
4430 ("\C-c^" org-table-sort-lines)
4431 ("\M-a" org-table-beginning-of-field)
4432 ("\M-e" org-table-end-of-field)
4433 ([(control ?#)] org-table-rotate-recalc-marks)))
4434 elt key fun cmd)
4435 (while (setq elt (pop bindings))
4436 (setq nfunc (1+ nfunc))
4437 (setq key (org-key (car elt))
4438 fun (nth 1 elt)
4439 cmd (orgtbl-make-binding fun nfunc key))
4440 (org-defkey orgtbl-mode-map key cmd))
4442 ;; Special treatment needed for TAB, RET and DEL
4443 (org-defkey orgtbl-mode-map [(return)]
4444 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4445 (org-defkey orgtbl-mode-map "\C-m"
4446 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4447 (org-defkey orgtbl-mode-map [(tab)]
4448 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4449 (org-defkey orgtbl-mode-map "\C-i"
4450 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4451 (org-defkey orgtbl-mode-map [(shift tab)]
4452 (orgtbl-make-binding 'org-table-previous-field 104
4453 [(shift tab)] [(tab)] "\C-i"))
4454 (org-defkey orgtbl-mode-map [backspace]
4455 (orgtbl-make-binding 'org-delete-backward-char 109
4456 [backspace] (kbd "DEL")))
4458 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4459 (orgtbl-make-binding 'org-table-previous-field 107
4460 [S-iso-lefttab] [backtab] [(shift tab)]
4461 [(tab)] "\C-i"))
4463 (org-defkey orgtbl-mode-map [backtab]
4464 (orgtbl-make-binding 'org-table-previous-field 108
4465 [backtab] [S-iso-lefttab] [(shift tab)]
4466 [(tab)] "\C-i"))
4468 (org-defkey orgtbl-mode-map "\M-\C-m"
4469 (orgtbl-make-binding 'org-table-wrap-region 105
4470 "\M-\C-m" [(meta return)]))
4471 (org-defkey orgtbl-mode-map [(meta return)]
4472 (orgtbl-make-binding 'org-table-wrap-region 106
4473 [(meta return)] "\M-\C-m"))
4475 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4476 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4478 (when orgtbl-optimized
4479 ;; If the user wants maximum table support, we need to hijack
4480 ;; some standard editing functions
4481 (org-remap orgtbl-mode-map
4482 'self-insert-command 'orgtbl-self-insert-command
4483 'delete-char 'org-delete-char
4484 'delete-backward-char 'org-delete-backward-char)
4485 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4486 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4487 '("OrgTbl"
4488 ["Create or convert" org-table-create-or-convert-from-region
4489 :active (not (org-at-table-p)) :keys "C-c |" ]
4490 "--"
4491 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4492 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4493 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4494 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4495 "--"
4496 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4497 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4498 ["Copy Field from Above"
4499 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4500 "--"
4501 ("Column"
4502 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4503 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4504 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4505 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4506 ("Row"
4507 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4508 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4509 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4510 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4511 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4512 "--"
4513 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4514 ("Rectangle"
4515 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4516 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4517 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4518 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4519 "--"
4520 ("Radio tables"
4521 ["Insert table template" orgtbl-insert-radio-table
4522 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
4523 ["Comment/uncomment table" orgtbl-toggle-comment t])
4524 "--"
4525 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4526 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4527 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4528 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4529 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4530 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4531 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4532 ["Sum Column/Rectangle" org-table-sum
4533 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4534 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4535 ["Debug Formulas"
4536 org-table-toggle-formula-debugger :active (org-at-table-p)
4537 :keys "C-c {"
4538 :style toggle :selected org-table-formula-debug]
4539 ["Show Col/Row Numbers"
4540 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4541 :keys "C-c }"
4542 :style toggle :selected org-table-overlay-coordinates]
4543 "--"
4544 ("Plot"
4545 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4546 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4549 (defun orgtbl-ctrl-c-ctrl-c (arg)
4550 "If the cursor is inside a table, realign the table.
4551 If it is a table to be sent away to a receiver, do it.
4552 With prefix arg, also recompute table."
4553 (interactive "P")
4554 (let ((case-fold-search t) (pos (point)) action)
4555 (save-excursion
4556 (beginning-of-line 1)
4557 (setq action (cond
4558 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4559 ((looking-at "[ \t]*|") pos)
4560 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4561 (cond
4562 ((integerp action)
4563 (goto-char action)
4564 (org-table-maybe-eval-formula)
4565 (if arg
4566 (call-interactively 'org-table-recalculate)
4567 (org-table-maybe-recalculate-line))
4568 (call-interactively 'org-table-align)
4569 (when (orgtbl-send-table 'maybe)
4570 (run-hooks 'orgtbl-after-send-table-hook)))
4571 ((eq action 'recalc)
4572 (save-excursion
4573 (beginning-of-line 1)
4574 (skip-chars-backward " \r\n\t")
4575 (if (org-at-table-p)
4576 (org-call-with-arg 'org-table-recalculate t))))
4577 (t (let (orgtbl-mode)
4578 (call-interactively (key-binding "\C-c\C-c")))))))
4580 (defun orgtbl-create-or-convert-from-region (_arg)
4581 "Create table or convert region to table, if no conflicting binding.
4582 This installs the table binding `C-c |', but only if there is no
4583 conflicting binding to this key outside orgtbl-mode."
4584 (interactive "P")
4585 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4586 (if cmd
4587 (call-interactively cmd)
4588 (call-interactively 'org-table-create-or-convert-from-region))))
4590 (defun orgtbl-tab (arg)
4591 "Justification and field motion for `orgtbl-mode'."
4592 (interactive "P")
4593 (if arg (org-table-edit-field t)
4594 (org-table-justify-field-maybe)
4595 (org-table-next-field)))
4597 (defun orgtbl-ret ()
4598 "Justification and field motion for `orgtbl-mode'."
4599 (interactive)
4600 (if (bobp)
4601 (newline)
4602 (org-table-justify-field-maybe)
4603 (org-table-next-row)))
4605 (defun orgtbl-self-insert-command (N)
4606 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4607 If the cursor is in a table looking at whitespace, the whitespace is
4608 overwritten, and the table is not marked as requiring realignment."
4609 (interactive "p")
4610 (if (and (org-at-table-p)
4612 (and org-table-auto-blank-field
4613 (member last-command
4614 '(orgtbl-hijacker-command-100
4615 orgtbl-hijacker-command-101
4616 orgtbl-hijacker-command-102
4617 orgtbl-hijacker-command-103
4618 orgtbl-hijacker-command-104
4619 orgtbl-hijacker-command-105
4620 yas/expand))
4621 (org-table-blank-field))
4623 (eq N 1)
4624 (looking-at "[^|\n]* \\( \\)|"))
4625 (let (org-table-may-need-update)
4626 (delete-region (match-beginning 1) (match-end 1))
4627 (self-insert-command N))
4628 (setq org-table-may-need-update t)
4629 (let* (orgtbl-mode
4631 (cmd (or (key-binding
4632 (or (and (listp function-key-map)
4633 (setq a (assoc last-input-event function-key-map))
4634 (cdr a))
4635 (vector last-input-event)))
4636 'self-insert-command)))
4637 (call-interactively cmd)
4638 (if (and org-self-insert-cluster-for-undo
4639 (eq cmd 'self-insert-command))
4640 (if (not (eq last-command 'orgtbl-self-insert-command))
4641 (setq org-self-insert-command-undo-counter 1)
4642 (if (>= org-self-insert-command-undo-counter 20)
4643 (setq org-self-insert-command-undo-counter 1)
4644 (and (> org-self-insert-command-undo-counter 0)
4645 buffer-undo-list
4646 (not (cadr buffer-undo-list)) ; remove nil entry
4647 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4648 (setq org-self-insert-command-undo-counter
4649 (1+ org-self-insert-command-undo-counter))))))))
4651 ;;;###autoload
4652 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4653 "Regular expression matching exponentials as produced by calc.")
4655 (defun orgtbl-gather-send-defs ()
4656 "Gather a plist of :name, :transform, :params for each destination before
4657 a radio table."
4658 (save-excursion
4659 (goto-char (org-table-begin))
4660 (let (rtn)
4661 (beginning-of-line 0)
4662 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4663 (let ((name (org-no-properties (match-string 1)))
4664 (transform (intern (match-string 2)))
4665 (params (if (match-end 3)
4666 (read (concat "(" (match-string 3) ")")))))
4667 (push (list :name name :transform transform :params params)
4668 rtn)
4669 (beginning-of-line 0)))
4670 rtn)))
4672 (defun orgtbl-send-replace-tbl (name text)
4673 "Find and replace table NAME with TEXT."
4674 (save-excursion
4675 (goto-char (point-min))
4676 (let* ((location-flag nil)
4677 (name (regexp-quote name))
4678 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4679 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4680 (while (re-search-forward begin-re nil t)
4681 (unless location-flag (setq location-flag t))
4682 (let ((beg (line-beginning-position 2)))
4683 (unless (re-search-forward end-re nil t)
4684 (user-error "Cannot find end of receiver location at %d" beg))
4685 (beginning-of-line)
4686 (delete-region beg (point))
4687 (insert text "\n")))
4688 (unless location-flag
4689 (user-error "No valid receiver location found in the buffer")))))
4691 ;;;###autoload
4692 (defun org-table-to-lisp (&optional txt)
4693 "Convert the table at point to a Lisp structure.
4694 The structure will be a list. Each item is either the symbol `hline'
4695 for a horizontal separator line, or a list of field values as strings.
4696 The table is taken from the parameter TXT, or from the buffer at point."
4697 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4698 (let ((txt (or txt
4699 (buffer-substring-no-properties (org-table-begin)
4700 (org-table-end)))))
4701 (mapcar (lambda (x)
4702 (if (string-match org-table-hline-regexp x) 'hline
4703 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4704 (org-split-string txt "[ \t]*\n[ \t]*"))))
4706 (defun orgtbl-send-table (&optional maybe)
4707 "Send a transformed version of table at point to the receiver position.
4708 With argument MAYBE, fail quietly if no transformation is defined
4709 for this table."
4710 (interactive)
4711 (catch 'exit
4712 (unless (org-at-table-p) (user-error "Not at a table"))
4713 ;; when non-interactive, we assume align has just happened.
4714 (when (called-interactively-p 'any) (org-table-align))
4715 (let ((dests (orgtbl-gather-send-defs))
4716 (table (org-table-to-lisp
4717 (buffer-substring-no-properties (org-table-begin)
4718 (org-table-end))))
4719 (ntbl 0))
4720 (unless dests
4721 (if maybe (throw 'exit nil)
4722 (user-error "Don't know how to transform this table")))
4723 (dolist (dest dests)
4724 (let ((name (plist-get dest :name))
4725 (transform (plist-get dest :transform))
4726 (params (plist-get dest :params)))
4727 (unless (fboundp transform)
4728 (user-error "No such transformation function %s" transform))
4729 (orgtbl-send-replace-tbl name (funcall transform table params)))
4730 (cl-incf ntbl))
4731 (message "Table converted and installed at %d receiver location%s"
4732 ntbl (if (> ntbl 1) "s" ""))
4733 (and (> ntbl 0) ntbl))))
4735 (defun org-remove-by-index (list indices &optional i0)
4736 "Remove the elements in LIST with indices in INDICES.
4737 First element has index 0, or I0 if given."
4738 (if (not indices)
4739 list
4740 (if (integerp indices) (setq indices (list indices)))
4741 (setq i0 (1- (or i0 0)))
4742 (delq :rm (mapcar (lambda (x)
4743 (setq i0 (1+ i0))
4744 (if (memq i0 indices) :rm x))
4745 list))))
4747 (defun orgtbl-toggle-comment ()
4748 "Comment or uncomment the orgtbl at point."
4749 (interactive)
4750 (let* ((case-fold-search t)
4751 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4752 (re2 (concat "^" orgtbl-line-start-regexp))
4753 (commented (save-excursion (beginning-of-line 1)
4754 (cond ((looking-at re1) t)
4755 ((looking-at re2) nil)
4756 (t (user-error "Not at an org table")))))
4757 (re (if commented re1 re2))
4758 beg end)
4759 (save-excursion
4760 (beginning-of-line 1)
4761 (while (looking-at re) (beginning-of-line 0))
4762 (beginning-of-line 2)
4763 (setq beg (point))
4764 (while (looking-at re) (beginning-of-line 2))
4765 (setq end (point)))
4766 (comment-region beg end (if commented '(4) nil))))
4768 (defun orgtbl-insert-radio-table ()
4769 "Insert a radio table template appropriate for this major mode."
4770 (interactive)
4771 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
4772 (txt (nth 1 e))
4773 name pos)
4774 (unless e (user-error "No radio table setup defined for %s" major-mode))
4775 (setq name (read-string "Table name: "))
4776 (while (string-match "%n" txt)
4777 (setq txt (replace-match name t t txt)))
4778 (or (bolp) (insert "\n"))
4779 (setq pos (point))
4780 (insert txt)
4781 (goto-char pos)))
4783 ;;;###autoload
4784 (defun orgtbl-to-generic (table params)
4785 "Convert the orgtbl-mode TABLE to some other format.
4787 This generic routine can be used for many standard cases.
4789 TABLE is a list, each entry either the symbol `hline' for
4790 a horizontal separator line, or a list of fields for that
4791 line. PARAMS is a property list of parameters that can
4792 influence the conversion.
4794 Valid parameters are:
4796 :backend, :raw
4798 Export back-end used as a basis to transcode elements of the
4799 table, when no specific parameter applies to it. It is also
4800 used to translate cells contents. You can prevent this by
4801 setting :raw property to a non-nil value.
4803 :splice
4805 When non-nil, only convert rows, not the table itself. This is
4806 equivalent to setting to the empty string both :tstart
4807 and :tend, which see.
4809 :skip
4811 When set to an integer N, skip the first N lines of the table.
4812 Horizontal separation lines do count for this parameter!
4814 :skipcols
4816 List of columns that should be skipped. If the table has
4817 a column with calculation marks, that column is automatically
4818 discarded beforehand.
4820 :hline
4822 String to be inserted on horizontal separation lines. May be
4823 nil to ignore these lines altogether.
4825 :sep
4827 Separator between two fields, as a string.
4829 Each in the following group may be either a string or a function
4830 of no arguments returning a string:
4832 :tstart, :tend
4834 Strings to start and end the table. Ignored when :splice is t.
4836 :lstart, :lend
4838 Strings to start and end a new table line.
4840 :llstart, :llend
4842 Strings to start and end the last table line. Default,
4843 respectively, to :lstart and :lend.
4845 Each in the following group may be a string or a function of one
4846 argument (either the cells in the current row, as a list of
4847 strings, or the current cell) returning a string:
4849 :lfmt
4851 Format string for an entire row, with enough %s to capture all
4852 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4854 :llfmt
4856 Format for the entire last line, defaults to :lfmt.
4858 :fmt
4860 A format to be used to wrap the field, should contain %s for
4861 the original field value. For example, to wrap everything in
4862 dollars, you could use :fmt \"$%s$\". This may also be
4863 a property list with column numbers and format strings, or
4864 functions, e.g.,
4866 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4868 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4870 Same as above, specific for the header lines in the table.
4871 All lines before the first hline are treated as header. If
4872 any of these is not present, the data line value is used.
4874 This may be either a string or a function of two arguments:
4876 :efmt
4878 Use this format to print numbers with exponential. The format
4879 should have %s twice for inserting mantissa and exponent, for
4880 example \"%s\\\\times10^{%s}\". This may also be a property
4881 list with column numbers and format strings or functions.
4882 :fmt will still be applied after :efmt."
4883 ;; Make sure `org-export-create-backend' is available.
4884 (require 'ox)
4885 (let* ((backend (plist-get params :backend))
4886 (custom-backend
4887 ;; Build a custom back-end according to PARAMS. Before
4888 ;; defining a translator, check if there is anything to do.
4889 ;; When there isn't, let BACKEND handle the element.
4890 (org-export-create-backend
4891 :parent (or backend 'org)
4892 :transcoders
4893 `((table . ,(org-table--to-generic-table params))
4894 (table-row . ,(org-table--to-generic-row params))
4895 (table-cell . ,(org-table--to-generic-cell params))
4896 ;; Macros are not going to be expanded. However, no
4897 ;; regular back-end has a transcoder for them. We
4898 ;; provide one so they are not ignored, but displayed
4899 ;; as-is instead.
4900 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4901 data info)
4902 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4903 ;; Initialize communication channel in INFO.
4904 (with-temp-buffer
4905 (let ((org-inhibit-startup t)) (org-mode))
4906 (let ((standard-output (current-buffer))
4907 (org-element-use-cache nil))
4908 (dolist (e table)
4909 (cond ((eq e 'hline) (princ "|--\n"))
4910 ((consp e)
4911 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4912 (princ "\n")))))
4913 ;; Add back-end specific filters, but not user-defined ones. In
4914 ;; particular, make sure to call parse-tree filters on the
4915 ;; table.
4916 (setq info
4917 (let ((org-export-filters-alist nil))
4918 (org-export-install-filters
4919 (org-combine-plists
4920 (org-export-get-environment backend nil params)
4921 `(:back-end ,(org-export-get-backend backend))))))
4922 (setq data
4923 (org-export-filter-apply-functions
4924 (plist-get info :filter-parse-tree)
4925 (org-element-map (org-element-parse-buffer) 'table
4926 #'identity nil t)
4927 info)))
4928 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4929 (user-error "Unknown :backend value"))
4930 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4931 ;; Handle :skip parameter.
4932 (let ((skip (plist-get info :skip)))
4933 (when skip
4934 (unless (wholenump skip) (user-error "Wrong :skip value"))
4935 (let ((n 0))
4936 (org-element-map data 'table-row
4937 (lambda (row)
4938 (if (>= n skip) t
4939 (org-element-extract-element row)
4940 (cl-incf n)
4941 nil))
4942 nil t))))
4943 ;; Handle :skipcols parameter.
4944 (let ((skipcols (plist-get info :skipcols)))
4945 (when skipcols
4946 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4947 (org-element-map data 'table
4948 (lambda (table)
4949 (let ((specialp (org-export-table-has-special-column-p table)))
4950 (dolist (row (org-element-contents table))
4951 (when (eq (org-element-property :type row) 'standard)
4952 (let ((c 1))
4953 (dolist (cell (nthcdr (if specialp 1 0)
4954 (org-element-contents row)))
4955 (when (memq c skipcols)
4956 (org-element-extract-element cell))
4957 (cl-incf c))))))))))
4958 ;; Since we are going to export using a low-level mechanism,
4959 ;; ignore special column and special rows manually.
4960 (let ((special? (org-export-table-has-special-column-p data))
4961 ignore)
4962 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4963 (lambda (datum)
4964 (when (if (eq (org-element-type datum) 'table-row)
4965 (org-export-table-row-is-special-p datum nil)
4966 (org-export-first-sibling-p datum nil))
4967 (push datum ignore))))
4968 (setq info (plist-put info :ignore-list ignore)))
4969 ;; We use a low-level mechanism to export DATA so as to skip all
4970 ;; usual pre-processing and post-processing, i.e., hooks, Babel
4971 ;; code evaluation, include keywords and macro expansion. Only
4972 ;; back-end specific filters are retained.
4973 (let ((output (org-export-data-with-backend data custom-backend info)))
4974 ;; Remove final newline.
4975 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4977 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4978 (cond ((null value) nil)
4979 ((functionp value) `(funcall ',value ,@args))
4980 ((stringp value)
4981 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4982 (args `(format ,value ,@args))
4983 (t value)))
4984 ((and with-cons (consp value))
4985 `(let ((val (cadr (memq column ',value))))
4986 (cond ((null val) contents)
4987 ((stringp val) (format val ,@args))
4988 ((functionp val) (funcall val ,@args))
4989 (t (user-error "Wrong %s value" ,name)))))
4990 (t (user-error "Wrong %s value" name))))
4992 (defun org-table--to-generic-table (params)
4993 "Return custom table transcoder according to PARAMS.
4994 PARAMS is a plist. See `orgtbl-to-generic' for more
4995 information."
4996 (let ((backend (plist-get params :backend))
4997 (splice (plist-get params :splice))
4998 (tstart (plist-get params :tstart))
4999 (tend (plist-get params :tend)))
5000 `(lambda (table contents info)
5001 (concat
5002 ,(and tstart (not splice)
5003 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
5004 ,(if (or (not backend) tstart tend splice) 'contents
5005 `(org-export-with-backend ',backend table contents info))
5006 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
5008 (defun org-table--to-generic-row (params)
5009 "Return custom table row transcoder according to PARAMS.
5010 PARAMS is a plist. See `orgtbl-to-generic' for more
5011 information."
5012 (let* ((backend (plist-get params :backend))
5013 (lstart (plist-get params :lstart))
5014 (llstart (plist-get params :llstart))
5015 (hlstart (plist-get params :hlstart))
5016 (hllstart (plist-get params :hllstart))
5017 (lend (plist-get params :lend))
5018 (llend (plist-get params :llend))
5019 (hlend (plist-get params :hlend))
5020 (hllend (plist-get params :hllend))
5021 (lfmt (plist-get params :lfmt))
5022 (llfmt (plist-get params :llfmt))
5023 (hlfmt (plist-get params :hlfmt))
5024 (hllfmt (plist-get params :hllfmt)))
5025 `(lambda (row contents info)
5026 (if (eq (org-element-property :type row) 'rule)
5027 ,(cond
5028 ((plist-member params :hline)
5029 (org-table--generic-apply (plist-get params :hline) ":hline"))
5030 (backend `(org-export-with-backend ',backend row nil info)))
5031 (let ((headerp ,(and (or hlfmt hlstart hlend)
5032 '(org-export-table-row-in-header-p row info)))
5033 (last-header-p
5034 ,(and (or hllfmt hllstart hllend)
5035 '(org-export-table-row-ends-header-p row info)))
5036 (lastp (not (org-export-get-next-element row info))))
5037 (when contents
5038 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5039 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5040 ;; `:lstart', `:lend' and their relatives.
5041 ,(let ((cells
5042 '(org-element-map row 'table-cell
5043 (lambda (cell)
5044 ;; Export all cells, without separators.
5046 ;; Use `org-export-data-with-backend'
5047 ;; instead of `org-export-data' to eschew
5048 ;; cached values, which
5049 ;; ignore :orgtbl-ignore-sep parameter.
5050 (org-export-data-with-backend
5051 cell
5052 (plist-get info :back-end)
5053 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5054 info)))
5055 `(cond
5056 ,(and hllfmt
5057 `(last-header-p ,(org-table--generic-apply
5058 hllfmt ":hllfmt" nil cells)))
5059 ,(and hlfmt
5060 `(headerp ,(org-table--generic-apply
5061 hlfmt ":hlfmt" nil cells)))
5062 ,(and llfmt
5063 `(lastp ,(org-table--generic-apply
5064 llfmt ":llfmt" nil cells)))
5066 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5067 `(concat
5068 (cond
5069 ,(and
5070 (or hllstart hllend)
5071 `(last-header-p
5072 (concat
5073 ,(org-table--generic-apply hllstart ":hllstart")
5074 contents
5075 ,(org-table--generic-apply hllend ":hllend"))))
5076 ,(and
5077 (or hlstart hlend)
5078 `(headerp
5079 (concat
5080 ,(org-table--generic-apply hlstart ":hlstart")
5081 contents
5082 ,(org-table--generic-apply hlend ":hlend"))))
5083 ,(and
5084 (or llstart llend)
5085 `(lastp
5086 (concat
5087 ,(org-table--generic-apply llstart ":llstart")
5088 contents
5089 ,(org-table--generic-apply llend ":llend"))))
5091 ,(cond
5092 ((or lstart lend)
5093 `(concat
5094 ,(org-table--generic-apply lstart ":lstart")
5095 contents
5096 ,(org-table--generic-apply lend ":lend")))
5097 (backend
5098 `(org-export-with-backend
5099 ',backend row contents info))
5100 (t 'contents)))))))))))))))
5102 (defun org-table--to-generic-cell (params)
5103 "Return custom table cell transcoder according to PARAMS.
5104 PARAMS is a plist. See `orgtbl-to-generic' for more
5105 information."
5106 (let* ((backend (plist-get params :backend))
5107 (efmt (plist-get params :efmt))
5108 (fmt (plist-get params :fmt))
5109 (hfmt (plist-get params :hfmt))
5110 (sep (plist-get params :sep))
5111 (hsep (plist-get params :hsep)))
5112 `(lambda (cell contents info)
5113 ;; Make sure that contents are exported as Org data when :raw
5114 ;; parameter is non-nil.
5115 ,(when (and backend (plist-get params :raw))
5116 `(setq contents
5117 ;; Since we don't know what are the pseudo object
5118 ;; types defined in backend, we cannot pass them to
5119 ;; `org-element-interpret-data'. As a consequence,
5120 ;; they will be treated as pseudo elements, and will
5121 ;; have newlines appended instead of spaces.
5122 ;; Therefore, we must make sure :post-blank value is
5123 ;; really turned into spaces.
5124 (replace-regexp-in-string
5125 "\n" " "
5126 (org-trim
5127 (org-element-interpret-data
5128 (org-element-contents cell))))))
5130 (let ((headerp ,(and (or hfmt hsep)
5131 '(org-export-table-row-in-header-p
5132 (org-export-get-parent-element cell) info)))
5133 (column
5134 ;; Call costly `org-export-table-cell-address' only if
5135 ;; absolutely necessary, i.e., if one
5136 ;; of :fmt :efmt :hfmt has a "plist type" value.
5137 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5138 (list efmt hfmt fmt))
5139 '(1+ (cdr (org-export-table-cell-address cell info))))))
5140 (when contents
5141 ;; Check if we can apply `:efmt' on CONTENTS.
5142 ,(when efmt
5143 `(when (string-match orgtbl-exp-regexp contents)
5144 (let ((mantissa (match-string 1 contents))
5145 (exponent (match-string 2 contents)))
5146 (setq contents ,(org-table--generic-apply
5147 efmt ":efmt" t 'mantissa 'exponent)))))
5148 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5149 (cond
5150 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5151 hfmt ":hfmt" t 'contents))))
5152 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5153 fmt ":fmt" t 'contents))))))
5154 ;; If a separator is provided, use it instead of BACKEND's.
5155 ;; Separators are ignored when LFMT (or equivalent) is
5156 ;; provided.
5157 ,(cond
5158 ((or hsep sep)
5159 `(if (or ,(and (not sep) '(not headerp))
5160 (plist-get info :orgtbl-ignore-sep)
5161 (not (org-export-get-next-element cell info)))
5162 ,(if (not backend) 'contents
5163 `(org-export-with-backend ',backend cell contents info))
5164 (concat contents
5165 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5166 (or hsep sep)))))
5167 (backend `(org-export-with-backend ',backend cell contents info))
5168 (t 'contents))))))
5170 ;;;###autoload
5171 (defun orgtbl-to-tsv (table params)
5172 "Convert the orgtbl-mode table to TAB separated material."
5173 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5175 ;;;###autoload
5176 (defun orgtbl-to-csv (table params)
5177 "Convert the orgtbl-mode table to CSV material.
5178 This does take care of the proper quoting of fields with comma or quotes."
5179 (orgtbl-to-generic table
5180 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5181 params)))
5183 ;;;###autoload
5184 (defun orgtbl-to-latex (table params)
5185 "Convert the orgtbl-mode TABLE to LaTeX.
5187 TABLE is a list, each entry either the symbol `hline' for
5188 a horizontal separator line, or a list of fields for that line.
5189 PARAMS is a property list of parameters that can influence the
5190 conversion. All parameters from `orgtbl-to-generic' are
5191 supported. It is also possible to use the following ones:
5193 :booktabs
5195 When non-nil, use formal \"booktabs\" style.
5197 :environment
5199 Specify environment to use, as a string. If you use
5200 \"longtable\", you may also want to specify :language property,
5201 as a string, to get proper continuation strings."
5202 (require 'ox-latex)
5203 (orgtbl-to-generic
5204 table
5205 (org-combine-plists
5206 ;; Provide sane default values.
5207 (list :backend 'latex
5208 :latex-default-table-mode 'table
5209 :latex-tables-centered nil
5210 :latex-tables-booktabs (plist-get params :booktabs)
5211 :latex-table-scientific-notation nil
5212 :latex-default-table-environment
5213 (or (plist-get params :environment) "tabular"))
5214 params)))
5216 ;;;###autoload
5217 (defun orgtbl-to-html (table params)
5218 "Convert the orgtbl-mode TABLE to HTML.
5220 TABLE is a list, each entry either the symbol `hline' for
5221 a horizontal separator line, or a list of fields for that line.
5222 PARAMS is a property list of parameters that can influence the
5223 conversion. All parameters from `orgtbl-to-generic' are
5224 supported. It is also possible to use the following one:
5226 :attributes
5228 Attributes and values, as a plist, which will be used in
5229 <table> tag."
5230 (require 'ox-html)
5231 (orgtbl-to-generic
5232 table
5233 (org-combine-plists
5234 ;; Provide sane default values.
5235 (list :backend 'html
5236 :html-table-data-tags '("<td%s>" . "</td>")
5237 :html-table-use-header-tags-for-first-column nil
5238 :html-table-align-individual-fields t
5239 :html-table-row-tags '("<tr>" . "</tr>")
5240 :html-table-attributes
5241 (if (plist-member params :attributes)
5242 (plist-get params :attributes)
5243 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5244 :frame "hsides")))
5245 params)))
5247 ;;;###autoload
5248 (defun orgtbl-to-texinfo (table params)
5249 "Convert the orgtbl-mode TABLE to Texinfo.
5251 TABLE is a list, each entry either the symbol `hline' for
5252 a horizontal separator line, or a list of fields for that line.
5253 PARAMS is a property list of parameters that can influence the
5254 conversion. All parameters from `orgtbl-to-generic' are
5255 supported. It is also possible to use the following one:
5257 :columns
5259 Column widths, as a string. When providing column fractions,
5260 \"@columnfractions\" command can be omitted."
5261 (require 'ox-texinfo)
5262 (let ((output
5263 (orgtbl-to-generic
5264 table
5265 (org-combine-plists
5266 (list :backend 'texinfo
5267 :texinfo-tables-verbatim nil
5268 :texinfo-table-scientific-notation nil)
5269 params)))
5270 (columns (let ((w (plist-get params :columns)))
5271 (cond ((not w) nil)
5272 ((string-match-p "{\\|@columnfractions " w) w)
5273 (t (concat "@columnfractions " w))))))
5274 (if (not columns) output
5275 (replace-regexp-in-string
5276 "@multitable \\(.*\\)" columns output t nil 1))))
5278 ;;;###autoload
5279 (defun orgtbl-to-orgtbl (table params)
5280 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5282 TABLE is a list, each entry either the symbol `hline' for
5283 a horizontal separator line, or a list of fields for that line.
5284 PARAMS is a property list of parameters that can influence the
5285 conversion. All parameters from `orgtbl-to-generic' are
5286 supported.
5288 Useful when slicing one table into many. The :hline, :sep,
5289 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5290 be set to provide ORGTBL directives for the generated table."
5291 (require 'ox-org)
5292 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5294 (defun orgtbl-to-table.el (table params)
5295 "Convert the orgtbl-mode TABLE into a table.el table.
5296 TABLE is a list, each entry either the symbol `hline' for
5297 a horizontal separator line, or a list of fields for that line.
5298 PARAMS is a property list of parameters that can influence the
5299 conversion. All parameters from `orgtbl-to-generic' are
5300 supported."
5301 (with-temp-buffer
5302 (insert (orgtbl-to-orgtbl table params))
5303 (org-table-align)
5304 (replace-regexp-in-string
5305 "-|" "-+"
5306 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5308 (defun orgtbl-to-unicode (table params)
5309 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5311 TABLE is a list, each entry either the symbol `hline' for
5312 a horizontal separator line, or a list of fields for that line.
5313 PARAMS is a property list of parameters that can influence the
5314 conversion. All parameters from `orgtbl-to-generic' are
5315 supported. It is also possible to use the following ones:
5317 :ascii-art
5319 When non-nil, use \"ascii-art-to-unicode\" package to translate
5320 the table. You can download it here:
5321 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5323 :narrow
5325 When non-nil, narrow columns width than provided width cookie,
5326 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5327 (require 'ox-ascii)
5328 (orgtbl-to-generic
5329 table
5330 (org-combine-plists
5331 (list :backend 'ascii
5332 :ascii-charset 'utf-8
5333 :ascii-table-widen-columns (not (plist-get params :narrow))
5334 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5335 params)))
5337 ;; Put the cursor in a column containing numerical values
5338 ;; of an Org table,
5339 ;; type C-c " a
5340 ;; A new column is added with a bar plot.
5341 ;; When the table is refreshed (C-u C-c *),
5342 ;; the plot is updated to reflect the new values.
5344 (defun orgtbl-ascii-draw (value min max &optional width characters)
5345 "Draw an ascii bar in a table.
5346 VALUE is the value to plot, it determines the width of the bar to draw.
5347 MIN is the value that will be displayed as empty (zero width bar).
5348 MAX is the value that will draw a bar filling all the WIDTH.
5349 WIDTH is the span in characters from MIN to MAX.
5350 CHARACTERS is a string that will compose the bar, with shades of grey
5351 from pure white to pure black. It defaults to a 10 characters string
5352 of regular ascii characters."
5353 (let* ((width (ceiling (or width 12)))
5354 (characters (or characters " .:;c!lhVHW"))
5355 (len (1- (length characters)))
5356 (value (float (if (numberp value)
5357 value (string-to-number value))))
5358 (relative (/ (- value min) (- max min)))
5359 (steps (round (* relative width len))))
5360 (cond ((< steps 0) "too small")
5361 ((> steps (* width len)) "too large")
5362 (t (let* ((int-division (/ steps len))
5363 (remainder (- steps (* int-division len))))
5364 (concat (make-string int-division (elt characters len))
5365 (string (elt characters remainder))))))))
5367 ;;;###autoload
5368 (defun orgtbl-ascii-plot (&optional ask)
5369 "Draw an ASCII bar plot in a column.
5371 With cursor in a column containing numerical values, this function
5372 will draw a plot in a new column.
5374 ASK, if given, is a numeric prefix to override the default 12
5375 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5376 prefix,
5377 which will prompt for the width."
5378 (interactive "P")
5379 (let ((col (org-table-current-column))
5380 (min 1e999) ; 1e999 will be converted to infinity
5381 (max -1e999) ; which is the desired result
5382 (table (org-table-to-lisp))
5383 (length
5384 (cond ((consp ask)
5385 (read-number "Length of column " 12))
5386 ((numberp ask) ask)
5387 (t 12))))
5388 ;; Skip any hline a the top of table.
5389 (while (eq (car table) 'hline) (setq table (cdr table)))
5390 ;; Skip table header if any.
5391 (dolist (x (or (cdr (memq 'hline table)) table))
5392 (when (consp x)
5393 (setq x (nth (1- col) x))
5394 (when (string-match
5395 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5397 (setq x (string-to-number x))
5398 (when (> min x) (setq min x))
5399 (when (< max x) (setq max x)))))
5400 (org-table-insert-column)
5401 (org-table-move-column-right)
5402 (org-table-store-formulas
5403 (cons
5404 (cons
5405 (concat "$" (number-to-string (1+ col)))
5406 (format "'(%s $%s %s %s %s)"
5407 "orgtbl-ascii-draw" col min max length))
5408 (org-table-get-stored-formulas)))
5409 (org-table-recalculate t)))
5411 ;; Example of extension: unicode characters
5412 ;; Here are two examples of different styles.
5414 ;; Unicode block characters are used to give a smooth effect.
5415 ;; See http://en.wikipedia.org/wiki/Block_Elements
5416 ;; Use one of those drawing functions
5417 ;; - orgtbl-ascii-draw (the default ascii)
5418 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5419 ;; - orgtbl-uc-draw-cont (smooth unicode)
5421 ;; This is best viewed with the "DejaVu Sans Mono" font
5422 ;; (use M-x set-default-font).
5424 (defun orgtbl-uc-draw-grid (value min max &optional width)
5425 "Draw a bar in a table using block unicode characters.
5426 It is a variant of orgtbl-ascii-draw with Unicode block
5427 characters, for a smooth display. Bars appear as grids (to the
5428 extent the font allows)."
5429 ;; http://en.wikipedia.org/wiki/Block_Elements
5430 ;; best viewed with the "DejaVu Sans Mono" font.
5431 (orgtbl-ascii-draw value min max width
5432 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5434 (defun orgtbl-uc-draw-cont (value min max &optional width)
5435 "Draw a bar in a table using block unicode characters.
5436 It is a variant of orgtbl-ascii-draw with Unicode block
5437 characters, for a smooth display. Bars are solid (to the extent
5438 the font allows)."
5439 (orgtbl-ascii-draw value min max width
5440 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5442 (defun org-table-get-remote-range (name-or-id form)
5443 "Get a field value or a list of values in a range from table at ID.
5445 NAME-OR-ID may be the name of a table in the current file as set
5446 by a \"#+NAME:\" directive. The first table following this line
5447 will then be used. Alternatively, it may be an ID referring to
5448 any entry, also in a different file. In this case, the first
5449 table in that entry will be referenced.
5450 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5451 \"@I$2..@II$2\". All the references must be absolute, not relative.
5453 The return value is either a single string for a single field, or a
5454 list of the fields in the rectangle."
5455 (save-match-data
5456 (let ((case-fold-search t) (id-loc nil)
5457 ;; Protect a bunch of variables from being overwritten by
5458 ;; the context of the remote table.
5459 org-table-column-names org-table-column-name-regexp
5460 org-table-local-parameters org-table-named-field-locations
5461 org-table-current-line-types
5462 org-table-current-begin-pos org-table-dlines
5463 org-table-current-ncol
5464 org-table-hlines org-table-last-alignment
5465 org-table-last-column-widths org-table-last-alignment
5466 org-table-last-column-widths
5467 buffer loc)
5468 (setq form (org-table-convert-refs-to-rc form))
5469 (org-with-wide-buffer
5470 (goto-char (point-min))
5471 (if (re-search-forward
5472 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5473 (regexp-quote name-or-id) "[ \t]*$")
5474 nil t)
5475 (setq buffer (current-buffer) loc (match-beginning 0))
5476 (setq id-loc (org-id-find name-or-id 'marker))
5477 (unless (and id-loc (markerp id-loc))
5478 (user-error "Can't find remote table \"%s\"" name-or-id))
5479 (setq buffer (marker-buffer id-loc)
5480 loc (marker-position id-loc))
5481 (move-marker id-loc nil))
5482 (with-current-buffer buffer
5483 (org-with-wide-buffer
5484 (goto-char loc)
5485 (forward-char 1)
5486 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5487 (not (match-beginning 1)))
5488 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5489 (org-table-analyze)
5490 (setq form (org-table-formula-substitute-names
5491 (org-table-formula-handle-first/last-rc form)))
5492 (if (and (string-match org-table-range-regexp form)
5493 (> (length (match-string 0 form)) 1))
5494 (org-table-get-range
5495 (match-string 0 form) org-table-current-begin-pos 1)
5496 form)))))))
5498 (defun org-table-remote-reference-indirection (form)
5499 "Return formula with table remote references substituted by indirection.
5500 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5501 This indirection works only with the format @ROW$COLUMN. The
5502 format \"B3\" is not supported because it can not be
5503 distinguished from a plain table name or ID."
5504 (let ((regexp
5505 ;; Same as in `org-table-eval-formula'.
5506 (concat "\\<remote([ \t]*\\("
5507 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5508 "[@$][^ \t,]+"
5509 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5510 (replace-regexp-in-string
5511 regexp
5512 (lambda (m)
5513 (save-match-data
5514 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5515 (org-table-get-range
5516 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5517 (concat "@0" eq)
5518 eq)))))
5519 form t t 1)))
5521 (defmacro org-define-lookup-function (mode)
5522 (let ((mode-str (symbol-name mode))
5523 (first-p (eq mode 'first))
5524 (all-p (eq mode 'all)))
5525 (let ((plural-str (if all-p "s" "")))
5526 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5527 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5528 If R-LIST is nil, return matching element%s of S-LIST.
5529 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5530 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5531 This function is generated by a call to the macro `org-define-lookup-function'."
5532 mode-str plural-str plural-str plural-str)
5533 (let ,(let ((lvars '((p (or predicate 'equal))
5534 (sl s-list)
5535 (rl (or r-list s-list))
5536 (ret nil))))
5537 (if first-p (cons '(match-p nil) lvars) lvars))
5538 (while ,(if first-p '(and (not match-p) sl) 'sl)
5539 (when (funcall p val (car sl))
5540 ,(when first-p '(setq match-p t))
5541 (let ((rval (car rl)))
5542 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5543 (setq sl (cdr sl) rl (cdr rl)))
5544 ret)))))
5546 (org-define-lookup-function first)
5547 (org-define-lookup-function last)
5548 (org-define-lookup-function all)
5550 (provide 'org-table)
5552 ;; Local variables:
5553 ;; generated-autoload-file: "org-loaddefs.el"
5554 ;; End:
5556 ;;; org-table.el ends here