* test/lisp/emacs-lisp/derived-tests.el: Fix copy&paste leftovers
[emacs.git] / lisp / org / org-table.el
blob6ebd6da9d0a8770943157de99d63121dd8a60340
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 (and org-table-automatic-realign
1091 org-table-may-need-update)
1092 (org-table-align))
1093 (let ((col (org-table-current-column)))
1094 (beginning-of-line 2)
1095 (when (or (not (org-at-table-p))
1096 (org-at-table-hline-p))
1097 (beginning-of-line 0)
1098 (org-table-insert-row 'below))
1099 (org-table-goto-column col)
1100 (skip-chars-backward "^|\n\r")
1101 (when (looking-at " ") (forward-char))))
1103 ;;;###autoload
1104 (defun org-table-copy-down (n)
1105 "Copy the value of the current field one row below.
1107 If the field at the cursor is empty, copy the content of the
1108 nearest non-empty field above. With argument N, use the Nth
1109 non-empty field.
1111 If the current field is not empty, it is copied down to the next
1112 row, and the cursor is moved with it. Therefore, repeating this
1113 command causes the column to be filled row-by-row.
1115 If the variable `org-table-copy-increment' is non-nil and the
1116 field is an integer or a timestamp, it will be incremented while
1117 copying. By default, increment by the difference between the
1118 value in the current field and the one in the field above. To
1119 increment using a fixed integer, set `org-table-copy-increment'
1120 to a number. In the case of a timestamp, increment by days."
1121 (interactive "p")
1122 (let* ((colpos (org-table-current-column))
1123 (col (current-column))
1124 (field (save-excursion (org-table-get-field)))
1125 (field-up (or (save-excursion
1126 (org-table-get (1- (org-table-current-line))
1127 (org-table-current-column))) ""))
1128 (non-empty (string-match "[^ \t]" field))
1129 (non-empty-up (string-match "[^ \t]" field-up))
1130 (beg (org-table-begin))
1131 (orig-n n)
1132 txt txt-up inc)
1133 (org-table-check-inside-data-field)
1134 (if (not non-empty)
1135 (save-excursion
1136 (setq txt
1137 (catch 'exit
1138 (while (progn (beginning-of-line 1)
1139 (re-search-backward org-table-dataline-regexp
1140 beg t))
1141 (org-table-goto-column colpos t)
1142 (if (and (looking-at
1143 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1144 (<= (setq n (1- n)) 0))
1145 (throw 'exit (match-string 1))))))
1146 (setq field-up
1147 (catch 'exit
1148 (while (progn (beginning-of-line 1)
1149 (re-search-backward org-table-dataline-regexp
1150 beg t))
1151 (org-table-goto-column colpos t)
1152 (if (and (looking-at
1153 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1154 (<= (setq n (1- n)) 0))
1155 (throw 'exit (match-string 1))))))
1156 (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
1157 ;; Above field was not empty, go down to the next row
1158 (setq txt (org-trim field))
1159 (org-table-next-row)
1160 (org-table-blank-field))
1161 (if non-empty-up (setq txt-up (org-trim field-up)))
1162 (setq inc (cond
1163 ((numberp org-table-copy-increment) org-table-copy-increment)
1164 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
1165 (string-match org-ts-regexp3 txt))
1166 (- (org-time-string-to-absolute txt)
1167 (org-time-string-to-absolute txt-up)))
1168 ((string-match org-ts-regexp3 txt) 1)
1169 ((string-match "\\([-+]\\)?[0-9]+\\(?:\.[0-9]+\\)?" txt-up)
1170 (- (string-to-number txt)
1171 (string-to-number (match-string 0 txt-up))))
1172 (t 1)))
1173 (t 1)))
1174 (if (not txt)
1175 (user-error "No non-empty field found")
1176 (if (and org-table-copy-increment
1177 (not (equal orig-n 0))
1178 (string-match-p "^[-+^/*0-9eE.]+$" txt)
1179 (< (string-to-number txt) 100000000))
1180 (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
1181 (insert txt)
1182 (org-move-to-column col)
1183 (if (and org-table-copy-increment (org-at-timestamp-p 'lax))
1184 (org-timestamp-up-day inc)
1185 (org-table-maybe-recalculate-line))
1186 (org-table-align)
1187 (org-move-to-column col))))
1189 (defun org-table-check-inside-data-field (&optional noerror)
1190 "Is point inside a table data field?
1191 I.e. not on a hline or before the first or after the last column?
1192 This actually throws an error, so it aborts the current command."
1193 (cond ((and (org-at-table-p)
1194 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1195 (not (org-at-table-hline-p))
1196 (not (looking-at "[ \t]*$"))))
1197 (noerror nil)
1198 (t (user-error "Not in table data field"))))
1200 (defvar org-table-clip nil
1201 "Clipboard for table regions.")
1203 (defun org-table-get (line column)
1204 "Get the field in table line LINE, column COLUMN.
1205 If LINE is larger than the number of data lines in the table, the function
1206 returns nil. However, if COLUMN is too large, we will simply return an
1207 empty string.
1208 If LINE is nil, use the current line.
1209 If COLUMN is nil, use the current column."
1210 (setq column (or column (org-table-current-column)))
1211 (save-excursion
1212 (and (or (not line) (org-table-goto-line line))
1213 (org-trim (org-table-get-field column)))))
1215 (defun org-table-put (line column value &optional align)
1216 "Put VALUE into line LINE, column COLUMN.
1217 When ALIGN is set, also realign the table."
1218 (setq column (or column (org-table-current-column)))
1219 (prog1 (save-excursion
1220 (and (or (not line) (org-table-goto-line line))
1221 (progn (org-table-goto-column column nil 'force) t)
1222 (org-table-get-field column value)))
1223 (and align (org-table-align))))
1225 (defun org-table-current-line ()
1226 "Return the index of the current data line."
1227 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1228 (save-excursion
1229 (goto-char (org-table-begin))
1230 (while (and (re-search-forward org-table-dataline-regexp end t)
1231 (setq cnt (1+ cnt))
1232 (< (point-at-eol) pos))))
1233 cnt))
1235 (defun org-table-goto-line (N)
1236 "Go to the Nth data line in the current table.
1237 Return t when the line exists, nil if it does not exist."
1238 (goto-char (org-table-begin))
1239 (let ((end (org-table-end)) (cnt 0))
1240 (while (and (re-search-forward org-table-dataline-regexp end t)
1241 (< (setq cnt (1+ cnt)) N)))
1242 (= cnt N)))
1244 ;;;###autoload
1245 (defun org-table-blank-field ()
1246 "Blank the current table field or active region."
1247 (interactive)
1248 (org-table-check-inside-data-field)
1249 (if (and (called-interactively-p 'any) (org-region-active-p))
1250 (let (org-table-clip)
1251 (org-table-cut-region (region-beginning) (region-end)))
1252 (skip-chars-backward "^|")
1253 (backward-char 1)
1254 (if (looking-at "|[^|\n]+")
1255 (let* ((pos (match-beginning 0))
1256 (match (match-string 0))
1257 (len (org-string-width match)))
1258 (replace-match (concat "|" (make-string (1- len) ?\ )))
1259 (goto-char (+ 2 pos))
1260 (substring match 1)))))
1262 (defun org-table-get-field (&optional n replace)
1263 "Return the value of the field in column N of current row.
1264 N defaults to current column. If REPLACE is a string, replace
1265 field with this value. The return value is always the old
1266 value."
1267 (when n (org-table-goto-column n))
1268 (skip-chars-backward "^|\n")
1269 (if (or (bolp) (looking-at-p "[ \t]*$"))
1270 ;; Before first column or after last one.
1272 (looking-at "[^|\r\n]*")
1273 (let* ((pos (match-beginning 0))
1274 (val (buffer-substring pos (match-end 0))))
1275 (when replace
1276 (replace-match (if (equal replace "") " " replace) t t))
1277 (goto-char (min (line-end-position) (1+ pos)))
1278 val)))
1280 ;;;###autoload
1281 (defun org-table-field-info (_arg)
1282 "Show info about the current field, and highlight any reference at point."
1283 (interactive "P")
1284 (unless (org-at-table-p) (user-error "Not at a table"))
1285 (org-table-analyze)
1286 (save-excursion
1287 (let* ((pos (point))
1288 (col (org-table-current-column))
1289 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1290 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1291 (line-beginning-position))
1292 col)
1293 org-table-named-field-locations)))
1294 (eql (org-table-expand-lhs-ranges
1295 (mapcar
1296 (lambda (e)
1297 (cons (org-table-formula-handle-first/last-rc (car e))
1298 (cdr e)))
1299 (org-table-get-stored-formulas))))
1300 (dline (org-table-current-dline))
1301 (ref (format "@%d$%d" dline col))
1302 (ref1 (org-table-convert-refs-to-an ref))
1303 ;; Prioritize field formulas over column formulas.
1304 (fequation (or (assoc name eql) (assoc ref eql)))
1305 (cequation (assoc (format "$%d" col) eql))
1306 (eqn (or fequation cequation)))
1307 (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
1308 (when p (setq eqn p)))
1309 (goto-char pos)
1310 (ignore-errors (org-table-show-reference 'local))
1311 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1312 dline col
1313 (if cname (concat " or $" cname) "")
1314 dline col ref1
1315 (if name (concat " or $" name) "")
1316 ;; FIXME: formula info not correct if special table line
1317 (if eqn
1318 (concat ", formula: "
1319 (org-table-formula-to-user
1320 (concat
1321 (if (or (string-prefix-p "$" (car eqn))
1322 (string-prefix-p "@" (car eqn)))
1324 "$")
1325 (car eqn) "=" (cdr eqn))))
1326 "")))))
1328 (defun org-table-current-column ()
1329 "Find out which column we are in."
1330 (interactive)
1331 (save-excursion
1332 (let ((column 0) (pos (point)))
1333 (beginning-of-line)
1334 (while (search-forward "|" pos t) (cl-incf column))
1335 column)))
1337 (defun org-table-current-dline ()
1338 "Find out what table data line we are in.
1339 Only data lines count for this."
1340 (save-excursion
1341 (let ((c 0)
1342 (pos (line-beginning-position)))
1343 (goto-char (org-table-begin))
1344 (while (<= (point) pos)
1345 (when (looking-at org-table-dataline-regexp) (cl-incf c))
1346 (forward-line))
1347 c)))
1349 ;;;###autoload
1350 (defun org-table-goto-column (n &optional on-delim force)
1351 "Move the cursor to the Nth column in the current table line.
1352 With optional argument ON-DELIM, stop with point before the left delimiter
1353 of the field.
1354 If there are less than N fields, just go to after the last delimiter.
1355 However, when FORCE is non-nil, create new columns if necessary."
1356 (interactive "p")
1357 (beginning-of-line 1)
1358 (when (> n 0)
1359 (while (and (> (setq n (1- n)) -1)
1360 (or (search-forward "|" (point-at-eol) t)
1361 (and force
1362 (progn (end-of-line 1)
1363 (skip-chars-backward "^|")
1364 (insert " | ")
1365 t)))))
1366 (when (and force (not (looking-at ".*|")))
1367 (save-excursion (end-of-line 1) (insert " | ")))
1368 (if on-delim
1369 (backward-char 1)
1370 (if (looking-at " ") (forward-char 1)))))
1372 ;;;###autoload
1373 (defun org-table-insert-column ()
1374 "Insert a new column into the table."
1375 (interactive)
1376 (unless (org-at-table-p) (user-error "Not at a table"))
1377 (org-table-find-dataline)
1378 (let* ((col (max 1 (org-table-current-column)))
1379 (beg (org-table-begin))
1380 (end (copy-marker (org-table-end))))
1381 (org-table-save-field
1382 (goto-char beg)
1383 (while (< (point) end)
1384 (unless (org-at-table-hline-p)
1385 (org-table-goto-column col t)
1386 (insert "| "))
1387 (forward-line)))
1388 (set-marker end nil)
1389 (org-table-align)
1390 (when (or (not org-table-fix-formulas-confirm)
1391 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1392 (org-table-fix-formulas "$" nil (1- col) 1)
1393 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1395 (defun org-table-find-dataline ()
1396 "Find a data line in the current table, which is needed for column commands."
1397 (if (and (org-at-table-p)
1398 (not (org-at-table-hline-p)))
1400 (let ((col (current-column))
1401 (end (org-table-end)))
1402 (org-move-to-column col)
1403 (while (and (< (point) end)
1404 (or (not (= (current-column) col))
1405 (org-at-table-hline-p)))
1406 (beginning-of-line 2)
1407 (org-move-to-column col))
1408 (if (and (org-at-table-p)
1409 (not (org-at-table-hline-p)))
1411 (user-error
1412 "Please position cursor in a data line for column operations")))))
1414 (defun org-table-line-to-dline (line &optional above)
1415 "Turn a buffer line number into a data line number.
1417 If there is no data line in this line, return nil.
1419 If there is no matching dline (most likely the reference was
1420 a hline), the first dline below it is used. When ABOVE is
1421 non-nil, the one above is used."
1422 (let ((min 1)
1423 (max (1- (length org-table-dlines))))
1424 (cond ((or (> (aref org-table-dlines min) line)
1425 (< (aref org-table-dlines max) line))
1426 nil)
1427 ((= (aref org-table-dlines max) line) max)
1428 (t (catch 'exit
1429 (while (> (- max min) 1)
1430 (let* ((mean (/ (+ max min) 2))
1431 (v (aref org-table-dlines mean)))
1432 (cond ((= v line) (throw 'exit mean))
1433 ((> v line) (setq max mean))
1434 (t (setq min mean)))))
1435 (if above min max))))))
1437 ;;;###autoload
1438 (defun org-table-delete-column ()
1439 "Delete a column from the table."
1440 (interactive)
1441 (unless (org-at-table-p) (user-error "Not at a table"))
1442 (org-table-find-dataline)
1443 (org-table-check-inside-data-field)
1444 (let ((col (org-table-current-column))
1445 (beg (org-table-begin))
1446 (end (copy-marker (org-table-end))))
1447 (org-table-save-field
1448 (goto-char beg)
1449 (while (< (point) end)
1450 (if (org-at-table-hline-p)
1452 (org-table-goto-column col t)
1453 (and (looking-at "|[^|\n]+|")
1454 (replace-match "|")))
1455 (forward-line)))
1456 (set-marker end nil)
1457 (org-table-goto-column (max 1 (1- col)))
1458 (org-table-align)
1459 (when (or (not org-table-fix-formulas-confirm)
1460 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1461 (org-table-fix-formulas
1462 "$" (list (cons (number-to-string col) "INVALID")) col -1 col)
1463 (org-table-fix-formulas
1464 "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col))))
1466 ;;;###autoload
1467 (defun org-table-move-column-right ()
1468 "Move column to the right."
1469 (interactive)
1470 (org-table-move-column nil))
1471 ;;;###autoload
1472 (defun org-table-move-column-left ()
1473 "Move column to the left."
1474 (interactive)
1475 (org-table-move-column 'left))
1477 ;;;###autoload
1478 (defun org-table-move-column (&optional left)
1479 "Move the current column to the right. With arg LEFT, move to the left."
1480 (interactive "P")
1481 (unless (org-at-table-p) (user-error "Not at a table"))
1482 (org-table-find-dataline)
1483 (org-table-check-inside-data-field)
1484 (let* ((col (org-table-current-column))
1485 (col1 (if left (1- col) col))
1486 (colpos (if left (1- col) (1+ col)))
1487 (beg (org-table-begin))
1488 (end (copy-marker (org-table-end))))
1489 (when (and left (= col 1))
1490 (user-error "Cannot move column further left"))
1491 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1492 (user-error "Cannot move column further right"))
1493 (org-table-save-field
1494 (goto-char beg)
1495 (while (< (point) end)
1496 (unless (org-at-table-hline-p)
1497 (org-table-goto-column col1 t)
1498 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1499 (transpose-regions
1500 (match-beginning 1) (match-end 1)
1501 (match-beginning 2) (match-end 2))))
1502 (forward-line)))
1503 (set-marker end nil)
1504 (org-table-goto-column colpos)
1505 (org-table-align)
1506 (when (or (not org-table-fix-formulas-confirm)
1507 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1508 (org-table-fix-formulas
1509 "$" (list (cons (number-to-string col) (number-to-string colpos))
1510 (cons (number-to-string colpos) (number-to-string col))))
1511 (org-table-fix-formulas
1512 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1513 (cons (number-to-string colpos) (number-to-string col)))))))
1515 ;;;###autoload
1516 (defun org-table-move-row-down ()
1517 "Move table row down."
1518 (interactive)
1519 (org-table-move-row nil))
1520 ;;;###autoload
1521 (defun org-table-move-row-up ()
1522 "Move table row up."
1523 (interactive)
1524 (org-table-move-row 'up))
1526 ;;;###autoload
1527 (defun org-table-move-row (&optional up)
1528 "Move the current table line down. With arg UP, move it up."
1529 (interactive "P")
1530 (let* ((col (current-column))
1531 (pos (point))
1532 (hline1p (save-excursion (beginning-of-line 1)
1533 (looking-at org-table-hline-regexp)))
1534 (dline1 (org-table-current-dline))
1535 (dline2 (+ dline1 (if up -1 1)))
1536 (tonew (if up 0 2))
1537 hline2p)
1538 (when (and up (= (point-min) (line-beginning-position)))
1539 (user-error "Cannot move row further"))
1540 (beginning-of-line tonew)
1541 (when (or (and (not up) (eobp)) (not (org-at-table-p)))
1542 (goto-char pos)
1543 (user-error "Cannot move row further"))
1544 (setq hline2p (looking-at org-table-hline-regexp))
1545 (goto-char pos)
1546 (let ((row (delete-and-extract-region (line-beginning-position)
1547 (line-beginning-position 2))))
1548 (beginning-of-line tonew)
1549 (unless (bolp) (insert "\n")) ;at eob without a newline
1550 (insert row)
1551 (unless (bolp) (insert "\n")) ;missing final newline in ROW
1552 (beginning-of-line 0)
1553 (org-move-to-column col)
1554 (unless (or hline1p hline2p
1555 (not (or (not org-table-fix-formulas-confirm)
1556 (funcall org-table-fix-formulas-confirm
1557 "Fix formulas? "))))
1558 (org-table-fix-formulas
1559 "@" (list
1560 (cons (number-to-string dline1) (number-to-string dline2))
1561 (cons (number-to-string dline2) (number-to-string dline1))))))))
1563 ;;;###autoload
1564 (defun org-table-insert-row (&optional arg)
1565 "Insert a new row above the current line into the table.
1566 With prefix ARG, insert below the current line."
1567 (interactive "P")
1568 (unless (org-at-table-p) (user-error "Not at a table"))
1569 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1570 (new (org-table-clean-line line)))
1571 ;; Fix the first field if necessary
1572 (if (string-match "^[ \t]*| *[#$] *|" line)
1573 (setq new (replace-match (match-string 0 line) t t new)))
1574 (beginning-of-line (if arg 2 1))
1575 ;; Buffer may not end of a newline character, so ensure
1576 ;; (beginning-of-line 2) moves point to a new line.
1577 (unless (bolp) (insert "\n"))
1578 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1579 (beginning-of-line 0)
1580 (re-search-forward "| ?" (line-end-position) t)
1581 (when (or org-table-may-need-update org-table-overlay-coordinates)
1582 (org-table-align))
1583 (when (or (not org-table-fix-formulas-confirm)
1584 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1585 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1587 ;;;###autoload
1588 (defun org-table-insert-hline (&optional above)
1589 "Insert a horizontal-line below the current line into the table.
1590 With prefix ABOVE, insert above the current line."
1591 (interactive "P")
1592 (if (not (org-at-table-p))
1593 (user-error "Not at a table"))
1594 (when (eobp) (insert "\n") (backward-char 1))
1595 (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
1596 (org-table-align))
1597 (let ((line (org-table-clean-line
1598 (buffer-substring (point-at-bol) (point-at-eol))))
1599 (col (current-column)))
1600 (while (string-match "|\\( +\\)|" line)
1601 (setq line (replace-match
1602 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1603 ?-) "|") t t line)))
1604 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1605 (beginning-of-line (if above 1 2))
1606 (insert line "\n")
1607 (beginning-of-line (if above 1 -1))
1608 (org-move-to-column col)
1609 (and org-table-overlay-coordinates (org-table-align))))
1611 ;;;###autoload
1612 (defun org-table-hline-and-move (&optional same-column)
1613 "Insert a hline and move to the row below that line."
1614 (interactive "P")
1615 (let ((col (org-table-current-column)))
1616 (org-table-maybe-eval-formula)
1617 (org-table-maybe-recalculate-line)
1618 (org-table-insert-hline)
1619 (end-of-line 2)
1620 (if (looking-at "\n[ \t]*|-")
1621 (progn (insert "\n|") (org-table-align))
1622 (org-table-next-field))
1623 (if same-column (org-table-goto-column col))))
1625 (defun org-table-clean-line (s)
1626 "Convert a table line S into a string with only \"|\" and space.
1627 In particular, this does handle wide and invisible characters."
1628 (if (string-match "^[ \t]*|-" s)
1629 ;; It's a hline, just map the characters
1630 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1631 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1632 (setq s (replace-match
1633 (concat "|" (make-string (org-string-width (match-string 1 s))
1634 ?\ ) "|")
1635 t t s)))
1638 ;;;###autoload
1639 (defun org-table-kill-row ()
1640 "Delete the current row or horizontal line from the table."
1641 (interactive)
1642 (if (not (org-at-table-p))
1643 (user-error "Not at a table"))
1644 (let ((col (current-column))
1645 (dline (and (not (org-match-line org-table-hline-regexp))
1646 (org-table-current-dline))))
1647 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1648 (if (not (org-at-table-p)) (beginning-of-line 0))
1649 (org-move-to-column col)
1650 (when (and dline
1651 (or (not org-table-fix-formulas-confirm)
1652 (funcall org-table-fix-formulas-confirm "Fix formulas? ")))
1653 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1654 dline -1 dline))))
1656 ;;;###autoload
1657 (defun org-table-sort-lines
1658 (&optional with-case sorting-type getkey-func compare-func interactive?)
1659 "Sort table lines according to the column at point.
1661 The position of point indicates the column to be used for
1662 sorting, and the range of lines is the range between the nearest
1663 horizontal separator lines, or the entire table of no such lines
1664 exist. If point is before the first column, you will be prompted
1665 for the sorting column. If there is an active region, the mark
1666 specifies the first line and the sorting column, while point
1667 should be in the last line to be included into the sorting.
1669 The command then prompts for the sorting type which can be
1670 alphabetically, numerically, or by time (as given in a time stamp
1671 in the field, or as a HH:MM value). Sorting in reverse order is
1672 also possible.
1674 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1676 If SORTING-TYPE is specified when this function is called from a Lisp
1677 program, no prompting will take place. SORTING-TYPE must be a character,
1678 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1679 sorting should be done in reverse order.
1681 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1682 a function to be called to extract the key. It must return a value
1683 that is compatible with COMPARE-FUNC, the function used to compare
1684 entries.
1686 A non-nil value for INTERACTIVE? is used to signal that this
1687 function is being called interactively."
1688 (interactive (list current-prefix-arg nil nil nil t))
1689 (when (org-region-active-p) (goto-char (region-beginning)))
1690 ;; Point must be either within a field or before a data line.
1691 (save-excursion
1692 (skip-chars-backward " \t")
1693 (when (bolp) (search-forward "|" (line-end-position) t))
1694 (org-table-check-inside-data-field))
1695 ;; Set appropriate case sensitivity and column used for sorting.
1696 (let ((column (let ((c (org-table-current-column)))
1697 (cond ((> c 0) c)
1698 (interactive?
1699 (read-number "Use column N for sorting: "))
1700 (t 1))))
1701 (sorting-type
1702 (or sorting-type
1703 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1704 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1705 (save-restriction
1706 ;; Narrow buffer to appropriate sorting area.
1707 (if (org-region-active-p)
1708 (progn (goto-char (region-beginning))
1709 (narrow-to-region
1710 (point)
1711 (save-excursion (goto-char (region-end))
1712 (line-beginning-position 2))))
1713 (let ((start (org-table-begin))
1714 (end (org-table-end)))
1715 (narrow-to-region
1716 (save-excursion
1717 (if (re-search-backward org-table-hline-regexp start t)
1718 (line-beginning-position 2)
1719 start))
1720 (if (save-excursion (re-search-forward org-table-hline-regexp end t))
1721 (match-beginning 0)
1722 end))))
1723 ;; Determine arguments for `sort-subr'. Also record original
1724 ;; position. `org-table-save-field' cannot help here since
1725 ;; sorting is too much destructive.
1726 (let* ((sort-fold-case (not with-case))
1727 (coordinates
1728 (cons (count-lines (point-min) (line-beginning-position))
1729 (current-column)))
1730 (extract-key-from-field
1731 ;; Function to be called on the contents of the field
1732 ;; used for sorting in the current row.
1733 (cl-case sorting-type
1734 ((?n ?N) #'string-to-number)
1735 ((?a ?A) #'org-sort-remove-invisible)
1736 ((?t ?T)
1737 (lambda (f)
1738 (cond ((string-match org-ts-regexp-both f)
1739 (float-time
1740 (org-time-string-to-time (match-string 0 f))))
1741 ((org-duration-p f) (org-duration-to-minutes f))
1742 ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f)
1743 (org-duration-to-minutes (match-string 0 f)))
1744 (t 0))))
1745 ((?f ?F)
1746 (or getkey-func
1747 (and interactive?
1748 (org-read-function "Function for extracting keys: "))
1749 (error "Missing key extractor to sort rows")))
1750 (t (user-error "Invalid sorting type `%c'" sorting-type))))
1751 (predicate
1752 (cl-case sorting-type
1753 ((?n ?N ?t ?T) #'<)
1754 ((?a ?A) #'string<)
1755 ((?f ?F)
1756 (or compare-func
1757 (and interactive?
1758 (org-read-function
1759 (concat "Function for comparing keys "
1760 "(empty for default `sort-subr' predicate): ")
1761 'allow-empty)))))))
1762 (goto-char (point-min))
1763 (sort-subr (memq sorting-type '(?A ?N ?T ?F))
1764 (lambda ()
1765 (forward-line)
1766 (while (and (not (eobp))
1767 (not (looking-at org-table-dataline-regexp)))
1768 (forward-line)))
1769 #'end-of-line
1770 (lambda ()
1771 (funcall extract-key-from-field
1772 (org-trim (org-table-get-field column))))
1774 predicate)
1775 ;; Move back to initial field.
1776 (forward-line (car coordinates))
1777 (move-to-column (cdr coordinates))))))
1779 ;;;###autoload
1780 (defun org-table-cut-region (beg end)
1781 "Copy region in table to the clipboard and blank all relevant fields.
1782 If there is no active region, use just the field at point."
1783 (interactive (list
1784 (if (org-region-active-p) (region-beginning) (point))
1785 (if (org-region-active-p) (region-end) (point))))
1786 (org-table-copy-region beg end 'cut))
1788 ;;;###autoload
1789 (defun org-table-copy-region (beg end &optional cut)
1790 "Copy rectangular region in table to clipboard.
1791 A special clipboard is used which can only be accessed
1792 with `org-table-paste-rectangle'."
1793 (interactive (list
1794 (if (org-region-active-p) (region-beginning) (point))
1795 (if (org-region-active-p) (region-end) (point))
1796 current-prefix-arg))
1797 (goto-char (min beg end))
1798 (org-table-check-inside-data-field)
1799 (let ((beg (line-beginning-position))
1800 (c01 (org-table-current-column))
1801 region)
1802 (goto-char (max beg end))
1803 (org-table-check-inside-data-field)
1804 (let* ((end (copy-marker (line-end-position)))
1805 (c02 (org-table-current-column))
1806 (column-start (min c01 c02))
1807 (column-end (max c01 c02))
1808 (column-number (1+ (- column-end column-start)))
1809 (rpl (and cut " ")))
1810 (goto-char beg)
1811 (while (< (point) end)
1812 (unless (org-at-table-hline-p)
1813 ;; Collect every cell between COLUMN-START and COLUMN-END.
1814 (let (cols)
1815 (dotimes (c column-number)
1816 (push (org-table-get-field (+ c column-start) rpl) cols))
1817 (push (nreverse cols) region)))
1818 (forward-line))
1819 (set-marker end nil))
1820 (when cut (org-table-align))
1821 (setq org-table-clip (nreverse region))))
1823 ;;;###autoload
1824 (defun org-table-paste-rectangle ()
1825 "Paste a rectangular region into a table.
1826 The upper right corner ends up in the current field. All involved fields
1827 will be overwritten. If the rectangle does not fit into the present table,
1828 the table is enlarged as needed. The process ignores horizontal separator
1829 lines."
1830 (interactive)
1831 (unless (consp org-table-clip)
1832 (user-error "First cut/copy a region to paste!"))
1833 (org-table-check-inside-data-field)
1834 (let* ((column (org-table-current-column))
1835 (org-table-automatic-realign nil))
1836 (org-table-save-field
1837 (dolist (row org-table-clip)
1838 (while (org-at-table-hline-p) (forward-line))
1839 ;; If we left the table, create a new row.
1840 (when (and (bolp) (not (looking-at "[ \t]*|")))
1841 (end-of-line 0)
1842 (org-table-next-field))
1843 (let ((c column))
1844 (dolist (field row)
1845 (org-table-goto-column c nil 'force)
1846 (org-table-get-field nil field)
1847 (cl-incf c)))
1848 (forward-line)))
1849 (org-table-align)))
1851 ;;;###autoload
1852 (defun org-table-convert ()
1853 "Convert from `org-mode' table to table.el and back.
1854 Obviously, this only works within limits. When an Org table is converted
1855 to table.el, all horizontal separator lines get lost, because table.el uses
1856 these as cell boundaries and has no notion of horizontal lines. A table.el
1857 table can be converted to an Org table only if it does not do row or column
1858 spanning. Multiline cells will become multiple cells. Beware, Org mode
1859 does not test if the table can be successfully converted - it blindly
1860 applies a recipe that works for simple tables."
1861 (interactive)
1862 (require 'table)
1863 (if (org-at-table.el-p)
1864 ;; convert to Org table
1865 (let ((beg (copy-marker (org-table-begin t)))
1866 (end (copy-marker (org-table-end t))))
1867 (table-unrecognize-region beg end)
1868 (goto-char beg)
1869 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1870 (replace-match ""))
1871 (goto-char beg))
1872 (if (org-at-table-p)
1873 ;; convert to table.el table
1874 (let ((beg (copy-marker (org-table-begin)))
1875 (end (copy-marker (org-table-end))))
1876 ;; first, get rid of all horizontal lines
1877 (goto-char beg)
1878 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1879 (replace-match ""))
1880 ;; insert a hline before first
1881 (goto-char beg)
1882 (org-table-insert-hline 'above)
1883 (beginning-of-line -1)
1884 ;; insert a hline after each line
1885 (while (progn (beginning-of-line 3) (< (point) end))
1886 (org-table-insert-hline))
1887 (goto-char beg)
1888 (setq end (move-marker end (org-table-end)))
1889 ;; replace "+" at beginning and ending of hlines
1890 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1891 (replace-match "\\1+-"))
1892 (goto-char beg)
1893 (while (re-search-forward "-|[ \t]*$" end t)
1894 (replace-match "-+"))
1895 (goto-char beg)))))
1897 (defun org-table-transpose-table-at-point ()
1898 "Transpose Org table at point and eliminate hlines.
1899 So a table like
1901 | 1 | 2 | 4 | 5 |
1902 |---+---+---+---|
1903 | a | b | c | d |
1904 | e | f | g | h |
1906 will be transposed as
1908 | 1 | a | e |
1909 | 2 | b | f |
1910 | 4 | c | g |
1911 | 5 | d | h |
1913 Note that horizontal lines disappear."
1914 (interactive)
1915 (let* ((table (delete 'hline (org-table-to-lisp)))
1916 (dline_old (org-table-current-line))
1917 (col_old (org-table-current-column))
1918 (contents (mapcar (lambda (_)
1919 (let ((tp table))
1920 (mapcar
1921 (lambda (_)
1922 (prog1
1923 (pop (car tp))
1924 (setq tp (cdr tp))))
1925 table)))
1926 (car table))))
1927 (goto-char (org-table-begin))
1928 (re-search-forward "|")
1929 (backward-char)
1930 (delete-region (point) (org-table-end))
1931 (insert (mapconcat
1932 (lambda(x)
1933 (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1934 contents ""))
1935 (org-table-goto-line col_old)
1936 (org-table-goto-column dline_old))
1937 (org-table-align))
1939 ;;;###autoload
1940 (defun org-table-wrap-region (arg)
1941 "Wrap several fields in a column like a paragraph.
1942 This is useful if you'd like to spread the contents of a field over several
1943 lines, in order to keep the table compact.
1945 If there is an active region, and both point and mark are in the same column,
1946 the text in the column is wrapped to minimum width for the given number of
1947 lines. Generally, this makes the table more compact. A prefix ARG may be
1948 used to change the number of desired lines. For example, \
1949 `C-2 \\[org-table-wrap-region]'
1950 formats the selected text to two lines. If the region was longer than two
1951 lines, the remaining lines remain empty. A negative prefix argument reduces
1952 the current number of lines by that amount. The wrapped text is pasted back
1953 into the table. If you formatted it to more lines than it was before, fields
1954 further down in the table get overwritten - so you might need to make space in
1955 the table first.
1957 If there is no region, the current field is split at the cursor position and
1958 the text fragment to the right of the cursor is prepended to the field one
1959 line down.
1961 If there is no region, but you specify a prefix ARG, the current field gets
1962 blank, and the content is appended to the field above."
1963 (interactive "P")
1964 (org-table-check-inside-data-field)
1965 (if (org-region-active-p)
1966 ;; There is a region: fill as a paragraph.
1967 (let ((start (region-beginning)))
1968 (org-table-cut-region (region-beginning) (region-end))
1969 (when (> (length (car org-table-clip)) 1)
1970 (user-error "Region must be limited to single column"))
1971 (let ((nlines (cond ((not arg) (length org-table-clip))
1972 ((< arg 1) (+ (length org-table-clip) arg))
1973 (t arg))))
1974 (setq org-table-clip
1975 (mapcar #'list
1976 (org-wrap (mapconcat #'car org-table-clip " ")
1978 nlines))))
1979 (goto-char start)
1980 (org-table-paste-rectangle))
1981 ;; No region, split the current field at point.
1982 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1983 (skip-chars-forward "^\r\n|"))
1984 (cond
1985 (arg ; Combine with field above.
1986 (let ((s (org-table-blank-field))
1987 (col (org-table-current-column)))
1988 (forward-line -1)
1989 (while (org-at-table-hline-p) (forward-line -1))
1990 (org-table-goto-column col)
1991 (skip-chars-forward "^|")
1992 (skip-chars-backward " ")
1993 (insert " " (org-trim s))
1994 (org-table-align)))
1995 ((looking-at "\\([^|]+\\)+|") ; Split field.
1996 (let ((s (match-string 1)))
1997 (replace-match " |")
1998 (goto-char (match-beginning 0))
1999 (org-table-next-row)
2000 (insert (org-trim s) " ")
2001 (org-table-align)))
2002 (t (org-table-next-row)))))
2004 (defvar org-field-marker nil)
2006 ;;;###autoload
2007 (defun org-table-edit-field (arg)
2008 "Edit table field in a different window.
2009 This is mainly useful for fields that contain hidden parts.
2011 When called with a `\\[universal-argument]' prefix, just make the full field
2012 visible so that it can be edited in place.
2014 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2015 toggle `org-table-follow-field-mode'."
2016 (interactive "P")
2017 (unless (org-at-table-p) (user-error "Not at a table"))
2018 (cond
2019 ((equal arg '(16))
2020 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
2021 (arg
2022 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2023 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2024 (remove-text-properties b e '(org-cwidth t invisible t
2025 display t intangible t))
2026 (if (and (boundp 'font-lock-mode) font-lock-mode)
2027 (font-lock-fontify-block))))
2029 (let ((pos (point-marker))
2030 (coord
2031 (if (eq org-table-use-standard-references t)
2032 (concat (org-number-to-letters (org-table-current-column))
2033 (int-to-string (org-table-current-dline)))
2034 (concat "@" (int-to-string (org-table-current-dline))
2035 "$" (int-to-string (org-table-current-column)))))
2036 (field (org-table-get-field))
2037 (cw (current-window-configuration))
2039 (goto-char pos)
2040 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2041 (when (and (local-variable-p 'org-field-marker)
2042 (markerp org-field-marker))
2043 (move-marker org-field-marker nil))
2044 (erase-buffer)
2045 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
2046 (let ((org-inhibit-startup t)) (org-mode))
2047 (auto-fill-mode -1)
2048 (setq truncate-lines nil)
2049 (setq word-wrap t)
2050 (goto-char (setq p (point-max)))
2051 (insert (org-trim field))
2052 (remove-text-properties p (point-max)
2053 '(invisible t org-cwidth t display t
2054 intangible t))
2055 (goto-char p)
2056 (setq-local org-finish-function 'org-table-finish-edit-field)
2057 (setq-local org-window-configuration cw)
2058 (setq-local org-field-marker pos)
2059 (message "Edit and finish with C-c C-c")))))
2061 (defun org-table-finish-edit-field ()
2062 "Finish editing a table data field.
2063 Remove all newline characters, insert the result into the table, realign
2064 the table and kill the editing buffer."
2065 (let ((pos org-field-marker)
2066 (cw org-window-configuration)
2067 (cb (current-buffer))
2068 text)
2069 (goto-char (point-min))
2070 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
2071 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
2072 (replace-match " "))
2073 (setq text (org-trim (buffer-string)))
2074 (set-window-configuration cw)
2075 (kill-buffer cb)
2076 (select-window (get-buffer-window (marker-buffer pos)))
2077 (goto-char pos)
2078 (move-marker pos nil)
2079 (org-table-check-inside-data-field)
2080 (org-table-get-field nil text)
2081 (org-table-align)
2082 (message "New field value inserted")))
2084 (define-minor-mode org-table-follow-field-mode
2085 "Minor mode to make the table field editor window follow the cursor.
2086 When this mode is active, the field editor window will always show the
2087 current field. The mode exits automatically when the cursor leaves the
2088 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2089 nil " TblFollow" nil
2090 (if org-table-follow-field-mode
2091 (add-hook 'post-command-hook 'org-table-follow-fields-with-editor
2092 'append 'local)
2093 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
2094 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2095 (win (and buf (get-buffer-window buf))))
2096 (when win (delete-window win))
2097 (when buf
2098 (with-current-buffer buf
2099 (move-marker org-field-marker nil))
2100 (kill-buffer buf)))))
2102 (defun org-table-follow-fields-with-editor ()
2103 (if (and org-table-exit-follow-field-mode-when-leaving-table
2104 (not (org-at-table-p)))
2105 ;; We have left the table, exit the follow mode
2106 (org-table-follow-field-mode -1)
2107 (when (org-table-check-inside-data-field 'noerror)
2108 (let ((win (selected-window)))
2109 (org-table-edit-field nil)
2110 (org-fit-window-to-buffer)
2111 (select-window win)))))
2113 (defvar org-timecnt) ; dynamically scoped parameter
2115 ;;;###autoload
2116 (defun org-table-sum (&optional beg end nlast)
2117 "Sum numbers in region of current table column.
2118 The result will be displayed in the echo area, and will be available
2119 as kill to be inserted with \\[yank].
2121 If there is an active region, it is interpreted as a rectangle and all
2122 numbers in that rectangle will be summed. If there is no active
2123 region and point is located in a table column, sum all numbers in that
2124 column.
2126 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2127 numbers are assumed to be times as well (in decimal hours) and the
2128 numbers are added as such.
2130 If NLAST is a number, only the NLAST fields will actually be summed."
2131 (interactive)
2132 (save-excursion
2133 (let (col (org-timecnt 0) diff h m s org-table-clip)
2134 (cond
2135 ((and beg end)) ; beg and end given explicitly
2136 ((org-region-active-p)
2137 (setq beg (region-beginning) end (region-end)))
2139 (setq col (org-table-current-column))
2140 (goto-char (org-table-begin))
2141 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2142 (user-error "No table data"))
2143 (org-table-goto-column col)
2144 (setq beg (point))
2145 (goto-char (org-table-end))
2146 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2147 (user-error "No table data"))
2148 (org-table-goto-column col)
2149 (setq end (point))))
2150 (let* ((items (apply 'append (org-table-copy-region beg end)))
2151 (items1 (cond ((not nlast) items)
2152 ((>= nlast (length items)) items)
2153 (t (setq items (reverse items))
2154 (setcdr (nthcdr (1- nlast) items) nil)
2155 (nreverse items))))
2156 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2157 items1)))
2158 (res (apply '+ numbers))
2159 (sres (if (= org-timecnt 0)
2160 (number-to-string res)
2161 (setq diff (* 3600 res)
2162 h (floor (/ diff 3600)) diff (mod diff 3600)
2163 m (floor (/ diff 60)) diff (mod diff 60)
2164 s diff)
2165 (format "%.0f:%02.0f:%02.0f" h m s))))
2166 (kill-new sres)
2167 (when (called-interactively-p 'interactive)
2168 (message "%s" (substitute-command-keys
2169 (format "Sum of %d items: %-20s \
2170 \(\\[yank] will insert result into buffer)" (length numbers) sres))))
2171 sres))))
2173 (defun org-table-get-number-for-summing (s)
2174 (let (n)
2175 (if (string-match "^ *|? *" s)
2176 (setq s (replace-match "" nil nil s)))
2177 (if (string-match " *|? *$" s)
2178 (setq s (replace-match "" nil nil s)))
2179 (setq n (string-to-number s))
2180 (cond
2181 ((and (string-match "0" s)
2182 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2183 ((string-match "\\`[ \t]+\\'" s) nil)
2184 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2185 (let ((h (string-to-number (or (match-string 1 s) "0")))
2186 (m (string-to-number (or (match-string 2 s) "0")))
2187 (s (string-to-number (or (match-string 4 s) "0"))))
2188 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2189 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2190 ((equal n 0) nil)
2191 (t n))))
2193 (defun org-table-current-field-formula (&optional key noerror)
2194 "Return the formula active for the current field.
2196 Assumes that table is already analyzed. If KEY is given, return
2197 the key to this formula. Otherwise return the formula preceded
2198 with \"=\" or \":=\"."
2199 (let* ((line (count-lines org-table-current-begin-pos
2200 (line-beginning-position)))
2201 (row (org-table-line-to-dline line)))
2202 (cond
2203 (row
2204 (let* ((col (org-table-current-column))
2205 (name (car (rassoc (list line col)
2206 org-table-named-field-locations)))
2207 (scol (format "$%d" col))
2208 (ref (format "@%d$%d" (org-table-current-dline) col))
2209 (stored-list (org-table-get-stored-formulas noerror))
2210 (ass (or (assoc name stored-list)
2211 (assoc ref stored-list)
2212 (assoc scol stored-list))))
2213 (cond (key (car ass))
2214 (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=")
2215 (cdr ass))))))
2216 (noerror nil)
2217 (t (error "No formula active for the current field")))))
2219 (defun org-table-get-formula (&optional equation named)
2220 "Read a formula from the minibuffer, offer stored formula as default.
2221 When NAMED is non-nil, look for a named equation."
2222 (let* ((stored-list (org-table-get-stored-formulas))
2223 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2224 (line-beginning-position))
2225 (org-table-current-column))
2226 org-table-named-field-locations)))
2227 (ref (format "@%d$%d"
2228 (org-table-current-dline)
2229 (org-table-current-column)))
2230 (scol (cond
2231 ((not named) (format "$%d" (org-table-current-column)))
2232 ((and name (not (string-match "\\`LR[0-9]+\\'" name))) name)
2233 (t ref)))
2234 (name (or name ref))
2235 (org-table-may-need-update nil)
2236 (stored (cdr (assoc scol stored-list)))
2237 (eq (cond
2238 ((and stored equation (string-match-p "^ *=? *$" equation))
2239 stored)
2240 ((stringp equation)
2241 equation)
2242 (t (org-table-formula-from-user
2243 (read-string
2244 (org-table-formula-to-user
2245 (format "%s formula %s="
2246 (if named "Field" "Column")
2247 scol))
2248 (if stored (org-table-formula-to-user stored) "")
2249 'org-table-formula-history
2250 )))))
2251 mustsave)
2252 (when (not (string-match "\\S-" eq))
2253 ;; remove formula
2254 (setq stored-list (delq (assoc scol stored-list) stored-list))
2255 (org-table-store-formulas stored-list)
2256 (user-error "Formula removed"))
2257 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2258 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2259 (if (and name (not named))
2260 ;; We set the column equation, delete the named one.
2261 (setq stored-list (delq (assoc name stored-list) stored-list)
2262 mustsave t))
2263 (if stored
2264 (setcdr (assoc scol stored-list) eq)
2265 (setq stored-list (cons (cons scol eq) stored-list)))
2266 (if (or mustsave (not (equal stored eq)))
2267 (org-table-store-formulas stored-list))
2268 eq))
2270 (defun org-table-store-formulas (alist &optional location)
2271 "Store the list of formulas below the current table.
2272 If optional argument LOCATION is a buffer position, insert it at
2273 LOCATION instead."
2274 (save-excursion
2275 (if location
2276 (progn (goto-char location) (beginning-of-line))
2277 (goto-char (org-table-end)))
2278 (let ((case-fold-search t))
2279 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2280 (progn
2281 ;; Don't overwrite TBLFM, we might use text properties to
2282 ;; store stuff.
2283 (goto-char (match-beginning 3))
2284 (delete-region (match-beginning 3) (match-end 0)))
2285 (org-indent-line)
2286 (insert (or (match-string 2) "#+TBLFM:")))
2287 (insert " "
2288 (mapconcat (lambda (x) (concat (car x) "=" (cdr x)))
2289 (sort alist #'org-table-formula-less-p)
2290 "::")
2291 "\n"))))
2293 (defsubst org-table-formula-make-cmp-string (a)
2294 (when (string-match "\\`$[<>]" a)
2295 (let ((arrow (string-to-char (substring a 1))))
2296 ;; Fake a high number to make sure this is sorted at the end.
2297 (setq a (org-table-formula-handle-first/last-rc a))
2298 (setq a (format "$%d" (+ 10000
2299 (if (= arrow ?<) -1000 0)
2300 (string-to-number (substring a 1)))))))
2301 (when (string-match
2302 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2304 (concat
2305 (if (match-end 2)
2306 (format "@%05d" (string-to-number (match-string 2 a))) "")
2307 (if (match-end 4)
2308 (format "$%05d" (string-to-number (match-string 4 a))) "")
2309 (if (match-end 5)
2310 (concat "@@" (match-string 5 a))))))
2312 (defun org-table-formula-less-p (a b)
2313 "Compare two formulas for sorting."
2314 (let ((as (org-table-formula-make-cmp-string (car a)))
2315 (bs (org-table-formula-make-cmp-string (car b))))
2316 (and as bs (string< as bs))))
2318 ;;;###autoload
2319 (defun org-table-get-stored-formulas (&optional noerror location)
2320 "Return an alist with the stored formulas directly after current table.
2321 By default, only return active formulas, i.e., formulas located
2322 on the first line after the table. However, if optional argument
2323 LOCATION is a buffer position, consider the formulas there."
2324 (save-excursion
2325 (if location
2326 (progn (goto-char location) (beginning-of-line))
2327 (goto-char (org-table-end)))
2328 (let ((case-fold-search t))
2329 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2330 (let ((strings (org-split-string (match-string-no-properties 2)
2331 " *:: *"))
2332 eq-alist seen)
2333 (dolist (string strings (nreverse eq-alist))
2334 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2335 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2336 string)
2337 (let ((lhs
2338 (let ((m (match-string 1 string)))
2339 (cond
2340 ((not (match-end 2)) m)
2341 ;; Is it a column reference?
2342 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m) m)
2343 ;; Since named columns are not possible in
2344 ;; LHS, assume this is a named field.
2345 (t (match-string 2 string)))))
2346 (rhs (match-string 3 string)))
2347 (push (cons lhs rhs) eq-alist)
2348 (cond
2349 ((not (member lhs seen)) (push lhs seen))
2350 (noerror
2351 (message
2352 "Double definition `%s=' in TBLFM line, please fix by hand"
2353 lhs)
2354 (ding)
2355 (sit-for 2))
2357 (user-error
2358 "Double definition `%s=' in TBLFM line, please fix by hand"
2359 lhs)))))))))))
2361 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2362 "Modify the equations after the table structure has been edited.
2363 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2364 For all numbers larger than LIMIT, shift them by DELTA."
2365 (save-excursion
2366 (goto-char (org-table-end))
2367 (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2368 (let ((msg "The formulas in #+TBLFM have been updated")
2369 (re (concat key "\\([0-9]+\\)"))
2370 (re2
2371 (when remove
2372 (if (or (equal key "$") (equal key "$LR"))
2373 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2374 (regexp-quote key) remove)
2375 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2376 s n a)
2377 (when remove
2378 (while (re-search-forward re2 (point-at-eol) t)
2379 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2380 (if (equal (char-before (match-beginning 0)) ?.)
2381 (user-error
2382 "Change makes TBLFM term %s invalid, use undo to recover"
2383 (match-string 0))
2384 (replace-match "")))))
2385 (while (re-search-forward re (point-at-eol) t)
2386 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2387 (setq s (match-string 1) n (string-to-number s))
2388 (cond
2389 ((setq a (assoc s replace))
2390 (replace-match (concat key (cdr a)) t t)
2391 (message msg))
2392 ((and limit (> n limit))
2393 (replace-match (concat key (int-to-string (+ n delta))) t t)
2394 (message msg))))))
2395 (forward-line))))
2397 ;;;###autoload
2398 (defun org-table-maybe-eval-formula ()
2399 "Check if the current field starts with \"=\" or \":=\".
2400 If yes, store the formula and apply it."
2401 ;; We already know we are in a table. Get field will only return a formula
2402 ;; when appropriate. It might return a separator line, but no problem.
2403 (when org-table-formula-evaluate-inline
2404 (let* ((field (org-trim (or (org-table-get-field) "")))
2405 named eq)
2406 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2407 (setq named (equal (string-to-char field) ?:)
2408 eq (match-string 1 field))
2409 (org-table-eval-formula (and named '(4))
2410 (org-table-formula-from-user eq))))))
2412 (defvar org-recalc-commands nil
2413 "List of commands triggering the recalculation of a line.
2414 Will be filled automatically during use.")
2416 (defvar org-recalc-marks
2417 '((" " . "Unmarked: no special line, no automatic recalculation")
2418 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2419 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2420 ("!" . "Column name definition line. Reference in formula as $name.")
2421 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2422 ("_" . "Names for values in row below this one.")
2423 ("^" . "Names for values in row above this one.")))
2425 ;;;###autoload
2426 (defun org-table-rotate-recalc-marks (&optional newchar)
2427 "Rotate the recalculation mark in the first column.
2428 If in any row, the first field is not consistent with a mark,
2429 insert a new column for the markers.
2430 When there is an active region, change all the lines in the region,
2431 after prompting for the marking character.
2432 After each change, a message will be displayed indicating the meaning
2433 of the new mark."
2434 (interactive)
2435 (unless (org-at-table-p) (user-error "Not at a table"))
2436 (let* ((region (org-region-active-p))
2437 (l1 (and region
2438 (save-excursion (goto-char (region-beginning))
2439 (copy-marker (line-beginning-position)))))
2440 (l2 (and region
2441 (save-excursion (goto-char (region-end))
2442 (copy-marker (line-beginning-position)))))
2443 (l (copy-marker (line-beginning-position)))
2444 (col (org-table-current-column))
2445 (newchar (if region
2446 (char-to-string
2447 (read-char-exclusive
2448 "Change region to what mark? Type # * ! $ or SPC: "))
2449 newchar))
2450 (no-special-column
2451 (save-excursion
2452 (goto-char (org-table-begin))
2453 (re-search-forward
2454 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
2455 (when (and newchar (not (assoc newchar org-recalc-marks)))
2456 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2457 newchar))
2458 (when l1 (goto-char l1))
2459 (save-excursion
2460 (beginning-of-line)
2461 (unless (looking-at org-table-dataline-regexp)
2462 (user-error "Not at a table data line")))
2463 (when no-special-column
2464 (org-table-goto-column 1)
2465 (org-table-insert-column))
2466 (let ((previous-line-end (line-end-position))
2467 (newchar
2468 (save-excursion
2469 (beginning-of-line)
2470 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2471 (newchar)
2472 (t (cadr (member (match-string 1)
2473 (append (mapcar #'car org-recalc-marks)
2474 '(" ")))))))))
2475 ;; Rotate mark in first row.
2476 (org-table-get-field 1 (format " %s " newchar))
2477 ;; Rotate marks in additional rows if a region is active.
2478 (when region
2479 (save-excursion
2480 (forward-line)
2481 (while (<= (point) l2)
2482 (when (looking-at org-table-dataline-regexp)
2483 (org-table-get-field 1 (format " %s " newchar)))
2484 (forward-line))))
2485 ;; Only align if rotation actually changed lines' length.
2486 (when (/= previous-line-end (line-end-position)) (org-table-align)))
2487 (goto-char l)
2488 (org-table-goto-column (if no-special-column (1+ col) col))
2489 (when l1 (set-marker l1 nil))
2490 (when l2 (set-marker l2 nil))
2491 (set-marker l nil)
2492 (when (called-interactively-p 'interactive)
2493 (message "%s" (cdr (assoc newchar org-recalc-marks))))))
2495 ;;;###autoload
2496 (defun org-table-analyze ()
2497 "Analyze table at point and store results.
2499 This function sets up the following dynamically scoped variables:
2501 `org-table-column-name-regexp',
2502 `org-table-column-names',
2503 `org-table-current-begin-pos',
2504 `org-table-current-line-types',
2505 `org-table-current-ncol',
2506 `org-table-dlines',
2507 `org-table-hlines',
2508 `org-table-local-parameters',
2509 `org-table-named-field-locations'."
2510 (let ((beg (org-table-begin))
2511 (end (org-table-end)))
2512 (save-excursion
2513 (goto-char beg)
2514 ;; Extract column names.
2515 (setq org-table-column-names nil)
2516 (when (save-excursion
2517 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
2518 (let ((c 1))
2519 (dolist (name (org-split-string (match-string 1) " *| *"))
2520 (cl-incf c)
2521 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
2522 (push (cons name (int-to-string c)) org-table-column-names)))))
2523 (setq org-table-column-names (nreverse org-table-column-names))
2524 (setq org-table-column-name-regexp
2525 (format "\\$\\(%s\\)\\>"
2526 (regexp-opt (mapcar #'car org-table-column-names) t)))
2527 ;; Extract local parameters.
2528 (setq org-table-local-parameters nil)
2529 (save-excursion
2530 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2531 (dolist (field (org-split-string (match-string 1) " *| *"))
2532 (when (string-match
2533 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2534 (push (cons (match-string 1 field) (match-string 2 field))
2535 org-table-local-parameters)))))
2536 ;; Update named fields locations. We minimize `count-lines'
2537 ;; processing by storing last known number of lines in LAST.
2538 (setq org-table-named-field-locations nil)
2539 (save-excursion
2540 (let ((last (cons (point) 0)))
2541 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2542 (let ((c (match-string 1))
2543 (fields (org-split-string (match-string 2) " *| *")))
2544 (save-excursion
2545 (forward-line (if (equal c "_") 1 -1))
2546 (let ((fields1
2547 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2548 (org-split-string (match-string 1) " *| *")))
2549 (line (cl-incf (cdr last) (count-lines (car last) (point))))
2550 (col 1))
2551 (setcar last (point)) ; Update last known position.
2552 (while (and fields fields1)
2553 (let ((field (pop fields))
2554 (v (pop fields1)))
2555 (cl-incf col)
2556 (when (and (stringp field)
2557 (stringp v)
2558 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2559 field))
2560 (push (cons field v) org-table-local-parameters)
2561 (push (list field line col)
2562 org-table-named-field-locations))))))))))
2563 ;; Re-use existing markers when possible.
2564 (if (markerp org-table-current-begin-pos)
2565 (move-marker org-table-current-begin-pos (point))
2566 (setq org-table-current-begin-pos (point-marker)))
2567 ;; Analyze the line types.
2568 (let ((l 0) hlines dlines types)
2569 (while (looking-at "[ \t]*|\\(-\\)?")
2570 (push (if (match-end 1) 'hline 'dline) types)
2571 (if (match-end 1) (push l hlines) (push l dlines))
2572 (forward-line)
2573 (cl-incf l))
2574 (push 'hline types) ; Add an imaginary extra hline to the end.
2575 (setq org-table-current-line-types (apply #'vector (nreverse types)))
2576 (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
2577 (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
2578 ;; Get the number of columns from the first data line in table.
2579 (goto-char beg)
2580 (forward-line (aref org-table-dlines 1))
2581 (let* ((fields
2582 (org-split-string
2583 (buffer-substring (line-beginning-position) (line-end-position))
2584 "[ \t]*|[ \t]*"))
2585 (nfields (length fields))
2586 al al2)
2587 (setq org-table-current-ncol nfields)
2588 (let ((last-dline
2589 (aref org-table-dlines (1- (length org-table-dlines)))))
2590 (dotimes (i nfields)
2591 (let ((column (1+ i)))
2592 (push (list (format "LR%d" column) last-dline column) al)
2593 (push (cons (format "LR%d" column) (nth i fields)) al2))))
2594 (setq org-table-named-field-locations
2595 (append org-table-named-field-locations al))
2596 (setq org-table-local-parameters
2597 (append org-table-local-parameters al2))))))
2599 (defun org-table-goto-field (ref &optional create-column-p)
2600 "Move point to a specific field in the current table.
2602 REF is either the name of a field its absolute reference, as
2603 a string. No column is created unless CREATE-COLUMN-P is
2604 non-nil. If it is a function, it is called with the column
2605 number as its argument as is used as a predicate to know if the
2606 column can be created.
2608 This function assumes the table is already analyzed (i.e., using
2609 `org-table-analyze')."
2610 (let* ((coordinates
2611 (cond
2612 ((cdr (assoc ref org-table-named-field-locations)))
2613 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
2614 (list (condition-case nil
2615 (aref org-table-dlines
2616 (string-to-number (match-string 1 ref)))
2617 (error (user-error "Invalid row number in %s" ref)))
2618 (string-to-number (match-string 2 ref))))
2619 (t (user-error "Unknown field: %s" ref))))
2620 (line (car coordinates))
2621 (column (nth 1 coordinates))
2622 (create-new-column (if (functionp create-column-p)
2623 (funcall create-column-p column)
2624 create-column-p)))
2625 (when coordinates
2626 (goto-char org-table-current-begin-pos)
2627 (forward-line line)
2628 (org-table-goto-column column nil create-new-column))))
2630 ;;;###autoload
2631 (defun org-table-maybe-recalculate-line ()
2632 "Recompute the current line if marked for it, and if we haven't just done it."
2633 (interactive)
2634 (and org-table-allow-automatic-line-recalculation
2635 (not (and (memq last-command org-recalc-commands)
2636 (eq org-last-recalc-line (line-beginning-position))))
2637 (save-excursion (beginning-of-line 1)
2638 (looking-at org-table-auto-recalculate-regexp))
2639 (org-table-recalculate) t))
2641 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2642 (defsubst org-set-calc-mode (var &optional value)
2643 (if (stringp var)
2644 (setq var (assoc var '(("D" calc-angle-mode deg)
2645 ("R" calc-angle-mode rad)
2646 ("F" calc-prefer-frac t)
2647 ("S" calc-symbolic-mode t)))
2648 value (nth 2 var) var (nth 1 var)))
2649 (if (memq var org-tbl-calc-modes)
2650 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2651 (cons var (cons value org-tbl-calc-modes)))
2652 org-tbl-calc-modes)
2654 ;;;###autoload
2655 (defun org-table-eval-formula (&optional arg equation
2656 suppress-align suppress-const
2657 suppress-store suppress-analysis)
2658 "Replace the table field value at the cursor by the result of a calculation.
2660 In a table, this command replaces the value in the current field with the
2661 result of a formula. It also installs the formula as the \"current\" column
2662 formula, by storing it in a special line below the table. When called
2663 with a `\\[universal-argument]' prefix the formula is installed as a \
2664 field formula.
2666 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2667 insert the active equation for the field
2668 back into the current field, so that it can be edited there. This is \
2669 useful
2670 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2671 check the referenced fields.
2673 When called, the command first prompts for a formula, which is read in
2674 the minibuffer. Previously entered formulas are available through the
2675 history list, and the last used formula is offered as a default.
2676 These stored formulas are adapted correctly when moving, inserting, or
2677 deleting columns with the corresponding commands.
2679 The formula can be any algebraic expression understood by the Calc package.
2680 For details, see the Org mode manual.
2682 This function can also be called from Lisp programs and offers
2683 additional arguments: EQUATION can be the formula to apply. If this
2684 argument is given, the user will not be prompted.
2686 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2687 unnecessary aligns.
2689 SUPPRESS-CONST suppresses the interpretation of constants in the
2690 formula, assuming that this has been done already outside the
2691 function.
2693 SUPPRESS-STORE means the formula should not be stored, either
2694 because it is already stored, or because it is a modified
2695 equation that should not overwrite the stored one.
2697 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2698 location of point."
2699 (interactive "P")
2700 (unless suppress-analysis
2701 (org-table-check-inside-data-field)
2702 (org-table-analyze))
2703 (if (equal arg '(16))
2704 (let ((eq (org-table-current-field-formula)))
2705 (org-table-get-field nil eq)
2706 (org-table-align)
2707 (setq org-table-may-need-update t))
2708 (let* (fields
2709 (ndown (if (integerp arg) arg 1))
2710 (org-table-automatic-realign nil)
2711 (case-fold-search nil)
2712 (down (> ndown 1))
2713 (formula (if (and equation suppress-store)
2714 equation
2715 (org-table-get-formula equation (equal arg '(4)))))
2716 (n0 (org-table-current-column))
2717 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2718 (numbers nil) ; was a variable, now fixed default
2719 (keep-empty nil)
2720 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2721 duration duration-output-format)
2722 ;; Parse the format string. Since we have a lot of modes, this is
2723 ;; a lot of work. However, I think calc still uses most of the time.
2724 (if (string-match ";" formula)
2725 (let ((tmp (org-split-string formula ";")))
2726 (setq formula (car tmp)
2727 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2728 (nth 1 tmp)))
2729 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2730 (setq c (string-to-char (match-string 1 fmt))
2731 n (string-to-number (match-string 2 fmt)))
2732 (if (= c ?p)
2733 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2734 (setq org-tbl-calc-modes
2735 (org-set-calc-mode
2736 'calc-float-format
2737 (list (cdr (assoc c '((?n . float) (?f . fix)
2738 (?s . sci) (?e . eng))))
2739 n))))
2740 (setq fmt (replace-match "" t t fmt)))
2741 (if (string-match "[tTU]" fmt)
2742 (let ((ff (match-string 0 fmt)))
2743 (setq duration t numbers t
2744 duration-output-format
2745 (cond ((equal ff "T") nil)
2746 ((equal ff "t") org-table-duration-custom-format)
2747 ((equal ff "U") 'hh:mm))
2748 fmt (replace-match "" t t fmt))))
2749 (if (string-match "N" fmt)
2750 (setq numbers t
2751 fmt (replace-match "" t t fmt)))
2752 (if (string-match "L" fmt)
2753 (setq literal t
2754 fmt (replace-match "" t t fmt)))
2755 (if (string-match "E" fmt)
2756 (setq keep-empty t
2757 fmt (replace-match "" t t fmt)))
2758 (while (string-match "[DRFS]" fmt)
2759 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2760 (setq fmt (replace-match "" t t fmt)))
2761 (unless (string-match "\\S-" fmt)
2762 (setq fmt nil))))
2763 (when (and (not suppress-const) org-table-formula-use-constants)
2764 (setq formula (org-table-formula-substitute-names formula)))
2765 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2766 (setq formula (org-table-formula-handle-first/last-rc formula))
2767 (while (> ndown 0)
2768 (setq fields (org-split-string
2769 (org-trim
2770 (buffer-substring-no-properties
2771 (line-beginning-position) (line-end-position)))
2772 " *| *"))
2773 ;; replace fields with duration values if relevant
2774 (if duration
2775 (setq fields
2776 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2777 fields)))
2778 (if (eq numbers t)
2779 (setq fields (mapcar
2780 (lambda (x)
2781 (if (string-match "\\S-" x)
2782 (number-to-string (string-to-number x))
2784 fields)))
2785 (setq ndown (1- ndown))
2786 (setq form (copy-sequence formula)
2787 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2788 (if (and lispp literal) (setq lispp 'literal))
2790 ;; Insert row and column number of formula result field
2791 (while (string-match "[@$]#" form)
2792 (setq form
2793 (replace-match
2794 (format "%d"
2795 (save-match-data
2796 (if (equal (substring form (match-beginning 0)
2797 (1+ (match-beginning 0)))
2798 "@")
2799 (org-table-current-dline)
2800 (org-table-current-column))))
2801 t t form)))
2803 ;; Check for old vertical references
2804 (org-table--error-on-old-row-references form)
2805 ;; Insert remote references
2806 (setq form (org-table-remote-reference-indirection form))
2807 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2808 (setq form
2809 (replace-match
2810 (save-match-data
2811 (org-table-make-reference
2812 (let ((rmtrng (org-table-get-remote-range
2813 (match-string 1 form) (match-string 2 form))))
2814 (if duration
2815 (if (listp rmtrng)
2816 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2817 (org-table-time-string-to-seconds rmtrng))
2818 rmtrng))
2819 keep-empty numbers lispp))
2820 t t form)))
2821 ;; Insert complex ranges
2822 (while (and (string-match org-table-range-regexp form)
2823 (> (length (match-string 0 form)) 1))
2824 (setq formrg
2825 (save-match-data
2826 (org-table-get-range
2827 (match-string 0 form) org-table-current-begin-pos n0)))
2828 (setq formrpl
2829 (save-match-data
2830 (org-table-make-reference
2831 ;; possibly handle durations
2832 (if duration
2833 (if (listp formrg)
2834 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2835 (org-table-time-string-to-seconds formrg))
2836 formrg)
2837 keep-empty numbers lispp)))
2838 (if (not (save-match-data
2839 (string-match (regexp-quote form) formrpl)))
2840 (setq form (replace-match formrpl t t form))
2841 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2842 ;; Insert simple ranges, i.e. included in the current row.
2843 (while (string-match
2844 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2845 form)
2846 (setq form
2847 (replace-match
2848 (save-match-data
2849 (org-table-make-reference
2850 (cl-subseq fields
2851 (+ (if (match-end 2) n0 0)
2852 (string-to-number (match-string 1 form))
2854 (+ (if (match-end 4) n0 0)
2855 (string-to-number (match-string 3 form))))
2856 keep-empty numbers lispp))
2857 t t form)))
2858 (setq form0 form)
2859 ;; Insert the references to fields in same row
2860 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2861 (setq n (+ (string-to-number (match-string 1 form))
2862 (if (match-end 2) n0 0))
2863 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2864 formrpl (save-match-data
2865 (org-table-make-reference
2866 x keep-empty numbers lispp)))
2867 (when (or (not x)
2868 (save-match-data
2869 (string-match (regexp-quote formula) formrpl)))
2870 (user-error "Invalid field specifier \"%s\""
2871 (match-string 0 form)))
2872 (setq form (replace-match formrpl t t form)))
2874 (if lispp
2875 (setq ev (condition-case nil
2876 (eval (eval (read form)))
2877 (error "#ERROR"))
2878 ev (if (numberp ev) (number-to-string ev) ev)
2879 ev (if duration (org-table-time-seconds-to-string
2880 (string-to-number ev)
2881 duration-output-format) ev))
2883 ;; Use <...> time-stamps so that Calc can handle them.
2884 (setq form
2885 (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form))
2886 ;; Internationalize local time-stamps by setting locale to
2887 ;; "C".
2888 (setq form
2889 (replace-regexp-in-string
2890 org-ts-regexp
2891 (lambda (ts)
2892 (let ((system-time-locale "C"))
2893 (format-time-string
2894 (org-time-stamp-format
2895 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2896 (apply #'encode-time
2897 (save-match-data (org-parse-time-string ts))))))
2898 form t t))
2900 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2901 form
2902 (calc-eval (cons form org-tbl-calc-modes)
2903 (when (and (not keep-empty) numbers) 'num)))
2904 ev (if duration (org-table-time-seconds-to-string
2905 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2906 (string-to-number (org-table-time-string-to-seconds ev))
2907 (string-to-number ev))
2908 duration-output-format)
2909 ev)))
2911 (when org-table-formula-debug
2912 (with-output-to-temp-buffer "*Substitution History*"
2913 (princ (format "Substitution history of formula
2914 Orig: %s
2915 $xyz-> %s
2916 @r$c-> %s
2917 $1-> %s\n" orig formula form0 form))
2918 (if (consp ev)
2919 (princ (format " %s^\nError: %s"
2920 (make-string (car ev) ?\-) (nth 1 ev)))
2921 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2922 ev (or fmt "NONE")
2923 (if fmt (format fmt (string-to-number ev)) ev)))))
2924 (setq bw (get-buffer-window "*Substitution History*"))
2925 (org-fit-window-to-buffer bw)
2926 (unless (and (called-interactively-p 'any) (not ndown))
2927 (unless (let (inhibit-redisplay)
2928 (y-or-n-p "Debugging Formula. Continue to next? "))
2929 (org-table-align)
2930 (user-error "Abort"))
2931 (delete-window bw)
2932 (message "")))
2933 (when (consp ev) (setq fmt nil ev "#ERROR"))
2934 (org-table-justify-field-maybe
2935 (format org-table-formula-field-format
2936 (cond
2937 ((not (stringp ev)) ev)
2938 (fmt (format fmt (string-to-number ev)))
2939 ;; Replace any active time stamp in the result with
2940 ;; an inactive one. Dates in tables are likely
2941 ;; piece of regular data, not meant to appear in the
2942 ;; agenda.
2943 (t (replace-regexp-in-string org-ts-regexp "[\\1]" ev)))))
2944 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2945 (call-interactively 'org-return)
2946 (setq ndown 0)))
2947 (and down (org-table-maybe-recalculate-line))
2948 (or suppress-align (and org-table-may-need-update
2949 (org-table-align))))))
2951 (defun org-table-put-field-property (prop value)
2952 (save-excursion
2953 (put-text-property (progn (skip-chars-backward "^|") (point))
2954 (progn (skip-chars-forward "^|") (point))
2955 prop value)))
2957 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2958 "Get a calc vector from a column, according to descriptor DESC.
2960 Optional arguments TBEG and COL can give the beginning of the table and
2961 the current column, to avoid unnecessary parsing.
2963 HIGHLIGHT means just highlight the range.
2965 When CORNERS-ONLY is set, only return the corners of the range as
2966 a list (line1 column1 line2 column2) where line1 and line2 are
2967 line numbers relative to beginning of table, or TBEG, and column1
2968 and column2 are table column numbers."
2969 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
2970 (replace-regexp-in-string "\\$" "@0$" desc)
2971 desc))
2972 (col (or col (org-table-current-column)))
2973 (tbeg (or tbeg (org-table-begin)))
2974 (thisline (count-lines tbeg (line-beginning-position))))
2975 (unless (string-match org-table-range-regexp desc)
2976 (user-error "Invalid table range specifier `%s'" desc))
2977 (let ((rangep (match-end 3))
2978 (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
2979 (or (save-match-data
2980 (and (org-string-nw-p r)
2981 (org-table--descriptor-line r thisline)))
2982 thisline)))
2983 (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
2984 (or (save-match-data
2985 (and (org-string-nw-p r)
2986 (org-table--descriptor-line r thisline)))
2987 thisline)))
2988 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
2989 (if (or (not c) (= (string-to-number c) 0)) col
2990 (+ (string-to-number c)
2991 (if (memq (string-to-char c) '(?- ?+)) col 0)))))
2992 (c2 (let ((c (and (match-end 5) (substring (match-string 5 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 (save-excursion
2997 (if (and (not corners-only)
2998 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2999 ;; Just one field.
3000 (progn
3001 (forward-line (- r1 thisline))
3002 (while (not (looking-at org-table-dataline-regexp))
3003 (forward-line))
3004 (prog1 (org-trim (org-table-get-field c1))
3005 (when highlight (org-table-highlight-rectangle))))
3006 ;; A range, return a vector. First sort the numbers to get
3007 ;; a regular rectangle.
3008 (let ((first-row (min r1 r2))
3009 (last-row (max r1 r2))
3010 (first-column (min c1 c2))
3011 (last-column (max c1 c2)))
3012 (if corners-only (list first-row first-column last-row last-column)
3013 ;; Copy the range values into a list.
3014 (forward-line (- first-row thisline))
3015 (while (not (looking-at org-table-dataline-regexp))
3016 (forward-line)
3017 (cl-incf first-row))
3018 (org-table-goto-column first-column)
3019 (let ((beg (point)))
3020 (forward-line (- last-row first-row))
3021 (while (not (looking-at org-table-dataline-regexp))
3022 (forward-line -1))
3023 (org-table-goto-column last-column)
3024 (let ((end (point)))
3025 (when highlight
3026 (org-table-highlight-rectangle
3027 beg (progn (skip-chars-forward "^|\n") (point))))
3028 ;; Return string representation of calc vector.
3029 (mapcar #'org-trim
3030 (apply #'append
3031 (org-table-copy-region beg end))))))))))))
3033 (defun org-table--descriptor-line (desc cline)
3034 "Return relative line number corresponding to descriptor DESC.
3035 The cursor is currently in relative line number CLINE."
3036 (if (string-match "\\`[0-9]+\\'" desc)
3037 (aref org-table-dlines (string-to-number desc))
3038 (when (or (not (string-match
3039 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3040 ;; 1 2 3 4 5 6
3041 desc))
3042 (and (not (match-end 3)) (not (match-end 6)))
3043 (and (match-end 3) (match-end 6) (not (match-end 5))))
3044 (user-error "Invalid row descriptor `%s'" desc))
3045 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3046 (hdir (match-string 2 desc))
3047 (odir (match-string 5 desc))
3048 (on (and (match-end 6) (string-to-number (match-string 6 desc))))
3049 (rel (and (match-end 6)
3050 (or (and (match-end 1) (not (match-end 3)))
3051 (match-end 5)))))
3052 (when (and hn (not hdir))
3053 (setq cline 0)
3054 (setq hdir "+")
3055 (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn)))
3056 (when (and (not hn) on (not odir)) (user-error "Should never happen"))
3057 (when hn
3058 (setq cline
3059 (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
3060 (when on
3061 (setq cline
3062 (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
3063 cline)))
3065 (defun org-table--row-type (type n i backwards relative desc)
3066 "Return relative line of Nth row with type TYPE.
3067 Search starts from relative line I. When BACKWARDS in non-nil,
3068 look before I. When RELATIVE is non-nil, the reference is
3069 relative. DESC is the original descriptor that started the
3070 search, as a string."
3071 (let ((l (length org-table-current-line-types)))
3072 (catch :exit
3073 (dotimes (_ n)
3074 (while (and (cl-incf i (if backwards -1 1))
3075 (>= i 0)
3076 (< i l)
3077 (not (eq (aref org-table-current-line-types i) type))
3078 ;; We are going to cross a hline. Check if this is
3079 ;; an authorized move.
3080 (cond
3081 ((not relative))
3082 ((not (eq (aref org-table-current-line-types i) 'hline)))
3083 ((eq org-table-relative-ref-may-cross-hline t))
3084 ((eq org-table-relative-ref-may-cross-hline 'error)
3085 (user-error "Row descriptor %s crosses hline" desc))
3086 (t (cl-decf i (if backwards -1 1)) ; Step back.
3087 (throw :exit nil)))))))
3088 (cond ((or (< i 0) (>= i l))
3089 (user-error "Row descriptor %s leads outside table" desc))
3090 ;; The last hline doesn't exist. Instead, point to last row
3091 ;; in table.
3092 ((= i (1- l)) (1- i))
3093 (t i))))
3095 (defun org-table--error-on-old-row-references (s)
3096 (when (string-match "&[-+0-9I]" s)
3097 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3099 (defun org-table-make-reference (elements keep-empty numbers lispp)
3100 "Convert list ELEMENTS to something appropriate to insert into formula.
3101 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3102 NUMBERS indicates that everything should be converted to numbers.
3103 LISPP non-nil means to return something appropriate for a Lisp
3104 list, `literal' is for the format specifier L."
3105 ;; Calc nan (not a number) is used for the conversion of the empty
3106 ;; field to a reference for several reasons: (i) It is accepted in a
3107 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3108 ;; (ii) In a single field (not in range) it can be distinguished
3109 ;; from "(nan)" which is the reference made from a single field
3110 ;; containing "nan".
3111 (if (stringp elements)
3112 ;; field reference
3113 (if lispp
3114 (if (eq lispp 'literal)
3115 elements
3116 (if (and (eq elements "") (not keep-empty))
3118 (prin1-to-string
3119 (if numbers (string-to-number elements) elements))))
3120 (if (string-match "\\S-" elements)
3121 (progn
3122 (when numbers (setq elements (number-to-string
3123 (string-to-number elements))))
3124 (concat "(" elements ")"))
3125 (if (or (not keep-empty) numbers) "(0)" "nan")))
3126 ;; range reference
3127 (unless keep-empty
3128 (setq elements
3129 (delq nil
3130 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3131 elements))))
3132 (setq elements (or elements '())) ; if delq returns nil then we need '()
3133 (if lispp
3134 (mapconcat
3135 (lambda (x)
3136 (if (eq lispp 'literal)
3138 (prin1-to-string (if numbers (string-to-number x) x))))
3139 elements " ")
3140 (concat "[" (mapconcat
3141 (lambda (x)
3142 (if (string-match "\\S-" x)
3143 (if numbers
3144 (number-to-string (string-to-number x))
3146 (if (or (not keep-empty) numbers) "0" "nan")))
3147 elements
3148 ",") "]"))))
3150 (defun org-table-message-once-per-second (t1 &rest args)
3151 "If there has been more than one second since T1, display message.
3152 ARGS are passed as arguments to the `message' function. Returns
3153 current time if a message is printed, otherwise returns T1. If
3154 T1 is nil, always messages."
3155 (let ((curtime (current-time)))
3156 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3157 (progn (apply 'message args)
3158 curtime)
3159 t1)))
3161 ;;;###autoload
3162 (defun org-table-recalculate (&optional all noalign)
3163 "Recalculate the current table line by applying all stored formulas.
3165 With prefix arg ALL, do this for all lines in the table.
3167 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3168 if ALL is the symbol `iterate',
3169 recompute the table until it no longer changes.
3171 If NOALIGN is not nil, do not re-align the table after the computations
3172 are done. This is typically used internally to save time, if it is
3173 known that the table will be realigned a little later anyway."
3174 (interactive "P")
3175 (unless (memq this-command org-recalc-commands)
3176 (push this-command org-recalc-commands))
3177 (unless (org-at-table-p) (user-error "Not at a table"))
3178 (if (or (eq all 'iterate) (equal all '(16)))
3179 (org-table-iterate)
3180 (org-table-analyze)
3181 (let* ((eqlist (sort (org-table-get-stored-formulas)
3182 (lambda (a b) (string< (car a) (car b)))))
3183 (inhibit-redisplay (not debug-on-error))
3184 (line-re org-table-dataline-regexp)
3185 (log-first-time (current-time))
3186 (log-last-time log-first-time)
3187 (cnt 0)
3188 beg end eqlcol eqlfield)
3189 ;; Insert constants in all formulas.
3190 (when eqlist
3191 (org-table-save-field
3192 ;; Expand equations, then split the equation list between
3193 ;; column formulas and field formulas.
3194 (dolist (eq eqlist)
3195 (let* ((rhs (org-table-formula-substitute-names
3196 (org-table-formula-handle-first/last-rc (cdr eq))))
3197 (old-lhs (car eq))
3198 (lhs
3199 (org-table-formula-handle-first/last-rc
3200 (cond
3201 ((string-match "\\`@-?I+" old-lhs)
3202 (user-error "Can't assign to hline relative reference"))
3203 ((string-match "\\`$[<>]" old-lhs)
3204 (let ((new (org-table-formula-handle-first/last-rc
3205 old-lhs)))
3206 (when (assoc new eqlist)
3207 (user-error "\"%s=\" formula tries to overwrite \
3208 existing formula for column %s"
3209 old-lhs
3210 new))
3211 new))
3212 (t old-lhs)))))
3213 (if (string-match-p "\\`\\$[0-9]+\\'" lhs)
3214 (push (cons lhs rhs) eqlcol)
3215 (push (cons lhs rhs) eqlfield))))
3216 (setq eqlcol (nreverse eqlcol))
3217 ;; Expand ranges in lhs of formulas
3218 (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
3219 ;; Get the correct line range to process.
3220 (if all
3221 (progn
3222 (setq end (copy-marker (org-table-end)))
3223 (goto-char (setq beg org-table-current-begin-pos))
3224 (cond
3225 ((re-search-forward org-table-calculate-mark-regexp end t)
3226 ;; This is a table with marked lines, compute selected
3227 ;; lines.
3228 (setq line-re org-table-recalculate-regexp))
3229 ;; Move forward to the first non-header line.
3230 ((and (re-search-forward org-table-dataline-regexp end t)
3231 (re-search-forward org-table-hline-regexp end t)
3232 (re-search-forward org-table-dataline-regexp end t))
3233 (setq beg (match-beginning 0)))
3234 ;; Just leave BEG at the start of the table.
3235 (t nil)))
3236 (setq beg (line-beginning-position)
3237 end (copy-marker (line-beginning-position 2))))
3238 (goto-char beg)
3239 ;; Mark named fields untouchable. Also check if several
3240 ;; field/range formulas try to set the same field.
3241 (remove-text-properties beg end '(:org-untouchable t))
3242 (let ((current-line (count-lines org-table-current-begin-pos
3243 (line-beginning-position)))
3244 seen-fields)
3245 (dolist (eq eqlfield)
3246 (let* ((name (car eq))
3247 (location (assoc name org-table-named-field-locations))
3248 (eq-line (or (nth 1 location)
3249 (and (string-match "\\`@\\([0-9]+\\)" name)
3250 (aref org-table-dlines
3251 (string-to-number
3252 (match-string 1 name))))))
3253 (reference
3254 (if location
3255 ;; Turn field coordinates associated to NAME
3256 ;; into an absolute reference.
3257 (format "@%d$%d"
3258 (org-table-line-to-dline eq-line)
3259 (nth 2 location))
3260 name)))
3261 (when (member reference seen-fields)
3262 (user-error "Several field/range formulas try to set %s"
3263 reference))
3264 (push reference seen-fields)
3265 (when (or all (eq eq-line current-line))
3266 (org-table-goto-field name)
3267 (org-table-put-field-property :org-untouchable t)))))
3268 ;; Evaluate the column formulas, but skip fields covered by
3269 ;; field formulas.
3270 (goto-char beg)
3271 (while (re-search-forward line-re end t)
3272 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3273 ;; Unprotected line, recalculate.
3274 (cl-incf cnt)
3275 (when all
3276 (setq log-last-time
3277 (org-table-message-once-per-second
3278 log-last-time
3279 "Re-applying formulas to full table...(line %d)" cnt)))
3280 (if (markerp org-last-recalc-line)
3281 (move-marker org-last-recalc-line (line-beginning-position))
3282 (setq org-last-recalc-line
3283 (copy-marker (line-beginning-position))))
3284 (dolist (entry eqlcol)
3285 (goto-char org-last-recalc-line)
3286 (org-table-goto-column
3287 (string-to-number (substring (car entry) 1)) nil 'force)
3288 (unless (get-text-property (point) :org-untouchable)
3289 (org-table-eval-formula
3290 nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
3291 ;; Evaluate the field formulas.
3292 (dolist (eq eqlfield)
3293 (let ((reference (car eq))
3294 (formula (cdr eq)))
3295 (setq log-last-time
3296 (org-table-message-once-per-second
3297 (and all log-last-time)
3298 "Re-applying formula to field: %s" (car eq)))
3299 (org-table-goto-field
3300 reference
3301 ;; Possibly create a new column, as long as
3302 ;; `org-table-formula-create-columns' allows it.
3303 (let ((column-count (progn (end-of-line)
3304 (1- (org-table-current-column)))))
3305 (lambda (column)
3306 (when (> column 1000)
3307 (user-error "Formula column target too large"))
3308 (and (> column column-count)
3309 (or (eq org-table-formula-create-columns t)
3310 (and (eq org-table-formula-create-columns 'warn)
3311 (progn
3312 (org-display-warning
3313 "Out-of-bounds formula added columns")
3315 (and (eq org-table-formula-create-columns 'prompt)
3316 (yes-or-no-p
3317 "Out-of-bounds formula. Add columns? ")))))))
3318 (org-table-eval-formula nil formula t t t t))))
3319 ;; Clean up markers and internal text property.
3320 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3321 (set-marker end nil)
3322 (unless noalign
3323 (when org-table-may-need-update (org-table-align))
3324 (when all
3325 (org-table-message-once-per-second
3326 log-first-time "Re-applying formulas to %d lines... done" cnt)))
3327 (org-table-message-once-per-second
3328 (and all log-first-time) "Re-applying formulas... done")))))
3330 ;;;###autoload
3331 (defun org-table-iterate (&optional arg)
3332 "Recalculate the table until it does not change anymore.
3333 The maximum number of iterations is 10, but you can choose a different value
3334 with the prefix ARG."
3335 (interactive "P")
3336 (let ((imax (if arg (prefix-numeric-value arg) 10))
3337 (i 0)
3338 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3339 thistbl)
3340 (catch 'exit
3341 (while (< i imax)
3342 (setq i (1+ i))
3343 (org-table-recalculate 'all)
3344 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3345 (if (not (string= lasttbl thistbl))
3346 (setq lasttbl thistbl)
3347 (if (> i 1)
3348 (message "Convergence after %d iterations" i)
3349 (message "Table was already stable"))
3350 (throw 'exit t)))
3351 (user-error "No convergence after %d iterations" i))))
3353 ;;;###autoload
3354 (defun org-table-recalculate-buffer-tables ()
3355 "Recalculate all tables in the current buffer."
3356 (interactive)
3357 (org-with-wide-buffer
3358 (org-table-map-tables
3359 (lambda ()
3360 ;; Reason for separate `org-table-align': When repeating
3361 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3362 ;; the way.
3363 (org-table-recalculate t t)
3364 (org-table-align))
3365 t)))
3367 ;;;###autoload
3368 (defun org-table-iterate-buffer-tables ()
3369 "Iterate all tables in the buffer, to converge inter-table dependencies."
3370 (interactive)
3371 (let* ((imax 10)
3372 (i imax)
3373 (checksum (md5 (buffer-string)))
3375 (org-with-wide-buffer
3376 (catch 'exit
3377 (while (> i 0)
3378 (setq i (1- i))
3379 (org-table-map-tables (lambda () (org-table-recalculate t t)) t)
3380 (if (equal checksum (setq c1 (md5 (buffer-string))))
3381 (progn
3382 (org-table-map-tables #'org-table-align t)
3383 (message "Convergence after %d iterations" (- imax i))
3384 (throw 'exit t))
3385 (setq checksum c1)))
3386 (org-table-map-tables #'org-table-align t)
3387 (user-error "No convergence after %d iterations" imax)))))
3389 (defun org-table-calc-current-TBLFM (&optional arg)
3390 "Apply the #+TBLFM in the line at point to the table."
3391 (interactive "P")
3392 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3393 (let ((formula (buffer-substring
3394 (line-beginning-position)
3395 (line-end-position))))
3396 (save-excursion
3397 ;; Insert a temporary formula at right after the table
3398 (goto-char (org-table-TBLFM-begin))
3399 (let ((s (point-marker)))
3400 (insert formula "\n")
3401 (let ((e (point-marker)))
3402 ;; Recalculate the table.
3403 (beginning-of-line 0) ; move to the inserted line
3404 (skip-chars-backward " \r\n\t")
3405 (unwind-protect
3406 (org-call-with-arg #'org-table-recalculate (or arg t))
3407 ;; Delete the formula inserted temporarily.
3408 (delete-region s e)
3409 (set-marker s nil)
3410 (set-marker e nil)))))))
3412 (defun org-table-TBLFM-begin ()
3413 "Find the beginning of the TBLFM lines and return its position.
3414 Return nil when the beginning of TBLFM line was not found."
3415 (save-excursion
3416 (when (progn (forward-line 1)
3417 (re-search-backward org-table-TBLFM-begin-regexp nil t))
3418 (line-beginning-position 2))))
3420 (defun org-table-expand-lhs-ranges (equations)
3421 "Expand list of formulas.
3422 If some of the RHS in the formulas are ranges or a row reference,
3423 expand them to individual field equations for each field. This
3424 function assumes the table is already analyzed (i.e., using
3425 `org-table-analyze')."
3426 (let (res)
3427 (dolist (e equations (nreverse res))
3428 (let ((lhs (car e))
3429 (rhs (cdr e)))
3430 (cond
3431 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
3432 ;; This just refers to one fixed field.
3433 (push e res))
3434 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
3435 ;; This just refers to one fixed named field.
3436 (push e res))
3437 ((string-match-p "\\`\\$[0-9]+\\'" lhs)
3438 ;; Column formulas are treated specially and are not
3439 ;; expanded.
3440 (push e res))
3441 ((string-match "\\`@[0-9]+\\'" lhs)
3442 (dotimes (ic org-table-current-ncol)
3443 (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
3444 rhs)
3445 res)))
3447 (let* ((range (org-table-get-range
3448 lhs org-table-current-begin-pos 1 nil 'corners))
3449 (r1 (org-table-line-to-dline (nth 0 range)))
3450 (c1 (nth 1 range))
3451 (r2 (org-table-line-to-dline (nth 2 range) 'above))
3452 (c2 (nth 3 range)))
3453 (cl-loop for ir from r1 to r2 do
3454 (cl-loop for ic from c1 to c2 do
3455 (push (cons (propertize
3456 (format "@%d$%d" ir ic) :orig-eqn e)
3457 rhs)
3458 res))))))))))
3460 (defun org-table-formula-handle-first/last-rc (s)
3461 "Replace @<, @>, $<, $> with first/last row/column of the table.
3462 So @< and $< will always be replaced with @1 and $1, respectively.
3463 The advantage of these special markers are that structure editing of
3464 the table will not change them, while @1 and $1 will be modified
3465 when a line/row is swapped out of that privileged position. So for
3466 formulas that use a range of rows or columns, it may often be better
3467 to anchor the formula with \"I\" row markers, or to offset from the
3468 borders of the table using the @< @> $< $> makers."
3469 (let (n nmax len char (start 0))
3470 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3471 s start)
3472 (if (match-end 3)
3473 (setq start (match-end 3))
3474 (setq nmax (if (equal (match-string 1 s) "@")
3475 (1- (length org-table-dlines))
3476 org-table-current-ncol)
3477 len (- (match-end 2) (match-beginning 2))
3478 char (string-to-char (match-string 2 s))
3479 n (if (= char ?<)
3481 (- nmax len -1)))
3482 (if (or (< n 1) (> n nmax))
3483 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3484 (match-string 0 s) s))
3485 (setq start (match-beginning 0))
3486 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3489 (defun org-table-formula-substitute-names (f)
3490 "Replace $const with values in string F."
3491 (let ((start 0)
3492 (pp (/= (string-to-char f) ?'))
3493 (duration (string-match-p ";.*[Tt].*\\'" f))
3494 (new (replace-regexp-in-string ; Check for column names.
3495 org-table-column-name-regexp
3496 (lambda (m)
3497 (concat "$" (cdr (assoc (match-string 1 m)
3498 org-table-column-names))))
3499 f t t)))
3500 ;; Parameters and constants.
3501 (while (setq start
3502 (string-match
3503 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3504 new start))
3505 (if (match-end 2) (setq start (match-end 2))
3506 (cl-incf start)
3507 ;; When a duration is expected, convert value on the fly.
3508 (let ((value
3509 (save-match-data
3510 (let ((v (org-table-get-constant (match-string 1 new))))
3511 (if (and (org-string-nw-p v) duration)
3512 (org-table-time-string-to-seconds v)
3513 v)))))
3514 (when value
3515 (setq new (replace-match
3516 (concat (and pp "(") value (and pp ")")) t t new))))))
3517 (if org-table-formula-debug (propertize new :orig-formula f) new)))
3519 (defun org-table-get-constant (const)
3520 "Find the value for a parameter or constant in a formula.
3521 Parameters get priority."
3522 (or (cdr (assoc const org-table-local-parameters))
3523 (cdr (assoc const org-table-formula-constants-local))
3524 (cdr (assoc const org-table-formula-constants))
3525 (and (fboundp 'constants-get) (constants-get const))
3526 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3527 (org-entry-get nil (substring const 5) 'inherit))
3528 "#UNDEFINED_NAME"))
3530 (defvar org-table-fedit-map
3531 (let ((map (make-sparse-keymap)))
3532 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3533 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3534 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3535 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3536 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3537 (org-defkey map "\C-c?" 'org-table-show-reference)
3538 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3539 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3540 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3541 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3542 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3543 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3544 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3545 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3546 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3547 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3548 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3549 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3550 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3551 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3552 map))
3554 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3555 '("Edit-Formulas"
3556 ["Finish and Install" org-table-fedit-finish t]
3557 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3558 ["Abort" org-table-fedit-abort t]
3559 "--"
3560 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3561 ["Complete Lisp Symbol" lisp-complete-symbol t]
3562 "--"
3563 "Shift Reference at Point"
3564 ["Up" org-table-fedit-ref-up t]
3565 ["Down" org-table-fedit-ref-down t]
3566 ["Left" org-table-fedit-ref-left t]
3567 ["Right" org-table-fedit-ref-right t]
3569 "Change Test Row for Column Formulas"
3570 ["Up" org-table-fedit-line-up t]
3571 ["Down" org-table-fedit-line-down t]
3572 "--"
3573 ["Scroll Table Window" org-table-fedit-scroll t]
3574 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3575 ["Show Table Grid" org-table-fedit-toggle-coordinates
3576 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3577 org-table-overlay-coordinates)]
3578 "--"
3579 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3580 :style toggle :selected org-table-buffer-is-an]))
3582 (defvar org-pos)
3583 (defvar org-table--fedit-source nil
3584 "Position of the TBLFM line being edited.")
3586 ;;;###autoload
3587 (defun org-table-edit-formulas ()
3588 "Edit the formulas of the current table in a separate buffer."
3589 (interactive)
3590 (let ((at-tblfm (org-at-TBLFM-p)))
3591 (unless (or at-tblfm (org-at-table-p))
3592 (user-error "Not at a table"))
3593 (save-excursion
3594 ;; Move point within the table before analyzing it.
3595 (when at-tblfm (re-search-backward "^[ \t]*|"))
3596 (org-table-analyze))
3597 (let ((key (org-table-current-field-formula 'key 'noerror))
3598 (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point)))
3599 #'org-table-formula-less-p))
3600 (pos (point-marker))
3601 (source (copy-marker (line-beginning-position)))
3602 (startline 1)
3603 (wc (current-window-configuration))
3604 (sel-win (selected-window))
3605 (titles '((column . "# Column Formulas\n")
3606 (field . "# Field and Range Formulas\n")
3607 (named . "# Named Field Formulas\n"))))
3608 (org-switch-to-buffer-other-window "*Edit Formulas*")
3609 (erase-buffer)
3610 ;; Keep global-font-lock-mode from turning on font-lock-mode
3611 (let ((font-lock-global-modes '(not fundamental-mode)))
3612 (fundamental-mode))
3613 (setq-local font-lock-global-modes (list 'not major-mode))
3614 (setq-local org-pos pos)
3615 (setq-local org-table--fedit-source source)
3616 (setq-local org-window-configuration wc)
3617 (setq-local org-selected-window sel-win)
3618 (use-local-map org-table-fedit-map)
3619 (add-hook 'post-command-hook #'org-table-fedit-post-command t t)
3620 (easy-menu-add org-table-fedit-menu)
3621 (setq startline (org-current-line))
3622 (dolist (entry eql)
3623 (let* ((type (cond
3624 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry))
3625 'column)
3626 ((equal (string-to-char (car entry)) ?@) 'field)
3627 (t 'named)))
3628 (title (assq type titles)))
3629 (when title
3630 (unless (bobp) (insert "\n"))
3631 (insert
3632 (org-add-props (cdr title) nil 'face font-lock-comment-face))
3633 (setq titles (remove title titles)))
3634 (when (equal key (car entry)) (setq startline (org-current-line)))
3635 (let ((s (concat
3636 (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$")
3637 (car entry) " = " (cdr entry) "\n")))
3638 (remove-text-properties 0 (length s) '(face nil) s)
3639 (insert s))))
3640 (when (eq org-table-use-standard-references t)
3641 (org-table-fedit-toggle-ref-type))
3642 (org-goto-line startline)
3643 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3644 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3645 See menu for more commands.")))))
3647 (defun org-table-fedit-post-command ()
3648 (when (not (memq this-command '(lisp-complete-symbol)))
3649 (let ((win (selected-window)))
3650 (save-excursion
3651 (ignore-errors (org-table-show-reference))
3652 (select-window win)))))
3654 (defun org-table-formula-to-user (s)
3655 "Convert a formula from internal to user representation."
3656 (if (eq org-table-use-standard-references t)
3657 (org-table-convert-refs-to-an s)
3660 (defun org-table-formula-from-user (s)
3661 "Convert a formula from user to internal representation."
3662 (if org-table-use-standard-references
3663 (org-table-convert-refs-to-rc s)
3666 (defun org-table-convert-refs-to-rc (s)
3667 "Convert spreadsheet references from A7 to @7$28.
3668 Works for single references, but also for entire formulas and even the
3669 full TBLFM line."
3670 (let ((start 0))
3671 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3672 (cond
3673 ((match-end 3)
3674 ;; format match, just advance
3675 (setq start (match-end 0)))
3676 ((and (> (match-beginning 0) 0)
3677 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3678 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3679 ;; 3.e5 or something like this.
3680 (setq start (match-end 0)))
3681 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3682 ;; (member (match-string 1 s)
3683 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3685 ;; function name, just advance
3686 (setq start (match-end 0)))
3688 (setq start (match-beginning 0)
3689 s (replace-match
3690 (if (equal (match-string 2 s) "&")
3691 (format "$%d" (org-letters-to-number (match-string 1 s)))
3692 (format "@%d$%d"
3693 (string-to-number (match-string 2 s))
3694 (org-letters-to-number (match-string 1 s))))
3695 t t s)))))
3698 (defun org-table-convert-refs-to-an (s)
3699 "Convert spreadsheet references from to @7$28 to AB7.
3700 Works for single references, but also for entire formulas and even the
3701 full TBLFM line."
3702 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3703 (setq s (replace-match
3704 (format "%s%d"
3705 (org-number-to-letters
3706 (string-to-number (match-string 2 s)))
3707 (string-to-number (match-string 1 s)))
3708 t t s)))
3709 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3710 (setq s (replace-match (concat "\\1"
3711 (org-number-to-letters
3712 (string-to-number (match-string 2 s))) "&")
3713 t nil s)))
3716 (defun org-letters-to-number (s)
3717 "Convert a base 26 number represented by letters into an integer.
3718 For example: AB -> 28."
3719 (let ((n 0))
3720 (setq s (upcase s))
3721 (while (> (length s) 0)
3722 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3723 s (substring s 1)))
3726 (defun org-number-to-letters (n)
3727 "Convert an integer into a base 26 number represented by letters.
3728 For example: 28 -> AB."
3729 (let ((s ""))
3730 (while (> n 0)
3731 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3732 n (/ (1- n) 26)))
3735 (defun org-table-time-string-to-seconds (s)
3736 "Convert a time string into numerical duration in seconds.
3737 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3738 If S is a string representing a number, keep this number."
3739 (if (equal s "")
3741 (let (hour minus min sec res)
3742 (cond
3743 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3744 (setq minus (< 0 (length (match-string 1 s)))
3745 hour (string-to-number (match-string 2 s))
3746 min (string-to-number (match-string 3 s))
3747 sec (string-to-number (match-string 4 s)))
3748 (if minus
3749 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3750 (setq res (+ (* hour 3600) (* min 60) sec))))
3751 ((and (not (string-match org-ts-regexp-both s))
3752 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3753 (setq minus (< 0 (length (match-string 1 s)))
3754 hour (string-to-number (match-string 2 s))
3755 min (string-to-number (match-string 3 s)))
3756 (if minus
3757 (setq res (- (+ (* hour 3600) (* min 60))))
3758 (setq res (+ (* hour 3600) (* min 60)))))
3759 (t (setq res (string-to-number s))))
3760 (number-to-string res))))
3762 (defun org-table-time-seconds-to-string (secs &optional output-format)
3763 "Convert a number of seconds to a time string.
3764 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3765 minutes or seconds."
3766 (let* ((secs0 (abs secs))
3767 (res
3768 (cond ((eq output-format 'days)
3769 (format "%.3f" (/ (float secs0) 86400)))
3770 ((eq output-format 'hours)
3771 (format "%.2f" (/ (float secs0) 3600)))
3772 ((eq output-format 'minutes)
3773 (format "%.1f" (/ (float secs0) 60)))
3774 ((eq output-format 'seconds)
3775 (format "%d" secs0))
3776 ((eq output-format 'hh:mm)
3777 ;; Ignore seconds
3778 (substring (format-seconds
3779 (if org-table-duration-hour-zero-padding
3780 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3781 secs0)
3782 0 -3))
3783 (t (format-seconds
3784 (if org-table-duration-hour-zero-padding
3785 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3786 secs0)))))
3787 (if (< secs 0) (concat "-" res) res)))
3789 (defun org-table-fedit-convert-buffer (function)
3790 "Convert all references in this buffer, using FUNCTION."
3791 (let ((origin (copy-marker (line-beginning-position))))
3792 (goto-char (point-min))
3793 (while (not (eobp))
3794 (insert (funcall function (buffer-substring (point) (line-end-position))))
3795 (delete-region (point) (line-end-position))
3796 (forward-line))
3797 (goto-char origin)
3798 (set-marker origin nil)))
3800 (defun org-table-fedit-toggle-ref-type ()
3801 "Convert all references in the buffer from B3 to @3$2 and back."
3802 (interactive)
3803 (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
3804 (org-table-fedit-convert-buffer
3805 (if org-table-buffer-is-an
3806 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3807 (message "Reference type switched to %s"
3808 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3810 (defun org-table-fedit-ref-up ()
3811 "Shift the reference at point one row/hline up."
3812 (interactive)
3813 (org-table-fedit-shift-reference 'up))
3814 (defun org-table-fedit-ref-down ()
3815 "Shift the reference at point one row/hline down."
3816 (interactive)
3817 (org-table-fedit-shift-reference 'down))
3818 (defun org-table-fedit-ref-left ()
3819 "Shift the reference at point one field to the left."
3820 (interactive)
3821 (org-table-fedit-shift-reference 'left))
3822 (defun org-table-fedit-ref-right ()
3823 "Shift the reference at point one field to the right."
3824 (interactive)
3825 (org-table-fedit-shift-reference 'right))
3827 (defun org-table-fedit-shift-reference (dir)
3828 (cond
3829 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3830 (if (memq dir '(left right))
3831 (org-rematch-and-replace 1 (eq dir 'left))
3832 (user-error "Cannot shift reference in this direction")))
3833 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3834 ;; A B3-like reference
3835 (if (memq dir '(up down))
3836 (org-rematch-and-replace 2 (eq dir 'up))
3837 (org-rematch-and-replace 1 (eq dir 'left))))
3838 ((org-in-regexp
3839 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3840 ;; An internal reference
3841 (if (memq dir '(up down))
3842 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3843 (org-rematch-and-replace 5 (eq dir 'left))))))
3845 (defun org-rematch-and-replace (n &optional decr hline)
3846 "Re-match the group N, and replace it with the shifted reference."
3847 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3848 (goto-char (match-beginning n))
3849 (and (looking-at (regexp-quote (match-string n)))
3850 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3851 t t)))
3853 (defun org-table-shift-refpart (ref &optional decr hline)
3854 "Shift a reference part REF.
3855 If DECR is set, decrease the references row/column, else increase.
3856 If HLINE is set, this may be a hline reference, it certainly is not
3857 a translation reference."
3858 (save-match-data
3859 (let* ((sign (string-match "^[-+]" ref)) n)
3861 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3862 (cond
3863 ((and hline (string-match "^I+" ref))
3864 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3865 (setq n (+ n (if decr -1 1)))
3866 (if (= n 0) (setq n (+ n (if decr -1 1))))
3867 (if sign
3868 (setq sign (if (< n 0) "-" "+") n (abs n))
3869 (setq n (max 1 n)))
3870 (concat sign (make-string n ?I)))
3872 ((string-match "^[0-9]+" ref)
3873 (setq n (string-to-number (concat sign ref)))
3874 (setq n (+ n (if decr -1 1)))
3875 (if sign
3876 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3877 (number-to-string (max 1 n))))
3879 ((string-match "^[a-zA-Z]+" ref)
3880 (org-number-to-letters
3881 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3883 (t (user-error "Cannot shift reference"))))))
3885 (defun org-table-fedit-toggle-coordinates ()
3886 "Toggle the display of coordinates in the referenced table."
3887 (interactive)
3888 (let ((pos (marker-position org-pos)))
3889 (with-current-buffer (marker-buffer org-pos)
3890 (save-excursion
3891 (goto-char pos)
3892 (org-table-toggle-coordinate-overlays)))))
3894 (defun org-table-fedit-finish (&optional arg)
3895 "Parse the buffer for formula definitions and install them.
3896 With prefix ARG, apply the new formulas to the table."
3897 (interactive "P")
3898 (org-table-remove-rectangle-highlight)
3899 (when org-table-use-standard-references
3900 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3901 (setq org-table-buffer-is-an nil))
3902 (let ((pos org-pos)
3903 (sel-win org-selected-window)
3904 (source org-table--fedit-source)
3905 eql)
3906 (goto-char (point-min))
3907 (while (re-search-forward
3908 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3909 nil t)
3910 (let ((var (match-string 1))
3911 (form (org-trim (match-string 3))))
3912 (unless (equal form "")
3913 (while (string-match "[ \t]*\n[ \t]*" form)
3914 (setq form (replace-match " " t t form)))
3915 (when (assoc var eql)
3916 (user-error "Double formulas for %s" var))
3917 (push (cons var form) eql))))
3918 (set-window-configuration org-window-configuration)
3919 (select-window sel-win)
3920 (goto-char source)
3921 (org-table-store-formulas eql)
3922 (set-marker pos nil)
3923 (set-marker source nil)
3924 (kill-buffer "*Edit Formulas*")
3925 (if arg
3926 (org-table-recalculate 'all)
3927 (message "New formulas installed - press C-u C-c C-c to apply."))))
3929 (defun org-table-fedit-abort ()
3930 "Abort editing formulas, without installing the changes."
3931 (interactive)
3932 (org-table-remove-rectangle-highlight)
3933 (let ((pos org-pos) (sel-win org-selected-window))
3934 (set-window-configuration org-window-configuration)
3935 (select-window sel-win)
3936 (goto-char pos)
3937 (move-marker pos nil)
3938 (message "Formula editing aborted without installing changes")))
3940 (defun org-table-fedit-lisp-indent ()
3941 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3942 (interactive)
3943 (let ((pos (point)) beg end ind)
3944 (beginning-of-line 1)
3945 (cond
3946 ((looking-at "[ \t]")
3947 (goto-char pos)
3948 (call-interactively 'lisp-indent-line))
3949 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3950 ((not (fboundp 'pp-buffer))
3951 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3952 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3953 (goto-char (- (match-end 0) 2))
3954 (setq beg (point))
3955 (setq ind (make-string (current-column) ?\ ))
3956 (condition-case nil (forward-sexp 1)
3957 (error
3958 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3959 (setq end (point))
3960 (save-restriction
3961 (narrow-to-region beg end)
3962 (if (eq last-command this-command)
3963 (progn
3964 (goto-char (point-min))
3965 (setq this-command nil)
3966 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3967 (replace-match " ")))
3968 (pp-buffer)
3969 (untabify (point-min) (point-max))
3970 (goto-char (1+ (point-min)))
3971 (while (re-search-forward "^." nil t)
3972 (beginning-of-line 1)
3973 (insert ind))
3974 (goto-char (point-max))
3975 (org-delete-backward-char 1)))
3976 (goto-char beg))
3977 (t nil))))
3979 (defvar org-show-positions nil)
3981 (defun org-table-show-reference (&optional local)
3982 "Show the location/value of the $ expression at point.
3983 When LOCAL is non-nil, show references for the table at point."
3984 (interactive)
3985 (org-table-remove-rectangle-highlight)
3986 (when local (org-table-analyze))
3987 (catch 'exit
3988 (let ((pos (if local (point) org-pos))
3989 (face2 'highlight)
3990 (org-inhibit-highlight-removal t)
3991 (win (selected-window))
3992 (org-show-positions nil)
3993 var name e what match dest)
3994 (setq what (cond
3995 ((org-in-regexp "^@[0-9]+[ \t=]")
3996 (setq match (concat (substring (match-string 0) 0 -1)
3997 "$1.."
3998 (substring (match-string 0) 0 -1)
3999 "$100"))
4000 'range)
4001 ((or (org-in-regexp org-table-range-regexp2)
4002 (org-in-regexp org-table-translate-regexp)
4003 (org-in-regexp org-table-range-regexp))
4004 (setq match
4005 (save-match-data
4006 (org-table-convert-refs-to-rc (match-string 0))))
4007 'range)
4008 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
4009 ((org-in-regexp "\\$[0-9]+") 'column)
4010 ((not local) nil)
4011 (t (user-error "No reference at point")))
4012 match (and what (or match (match-string 0))))
4013 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
4014 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
4015 'secondary-selection))
4016 (add-hook 'before-change-functions
4017 #'org-table-remove-rectangle-highlight)
4018 (when (eq what 'name) (setq var (substring match 1)))
4019 (when (eq what 'range)
4020 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
4021 (setq match (org-table-formula-substitute-names match)))
4022 (unless local
4023 (save-excursion
4024 (end-of-line)
4025 (re-search-backward "^\\S-" nil t)
4026 (beginning-of-line)
4027 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4028 \\([0-9]+\\|&\\)\\) *=")
4029 (setq dest
4030 (save-match-data
4031 (org-table-convert-refs-to-rc (match-string 1))))
4032 (org-table-add-rectangle-overlay
4033 (match-beginning 1) (match-end 1) face2))))
4034 (if (and (markerp pos) (marker-buffer pos))
4035 (if (get-buffer-window (marker-buffer pos))
4036 (select-window (get-buffer-window (marker-buffer pos)))
4037 (org-switch-to-buffer-other-window (get-buffer-window
4038 (marker-buffer pos)))))
4039 (goto-char pos)
4040 (org-table-force-dataline)
4041 (let ((table-start
4042 (if local org-table-current-begin-pos (org-table-begin))))
4043 (when dest
4044 (setq name (substring dest 1))
4045 (cond
4046 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
4047 (org-table-goto-field dest))
4048 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4049 dest)
4050 (org-table-goto-field dest))
4051 (t (org-table-goto-column (string-to-number name))))
4052 (move-marker pos (point))
4053 (org-table-highlight-rectangle nil nil face2))
4054 (cond
4055 ((equal dest match))
4056 ((not match))
4057 ((eq what 'range)
4058 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
4059 ((setq e (assoc var org-table-named-field-locations))
4060 (org-table-goto-field var)
4061 (org-table-highlight-rectangle)
4062 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
4063 ((setq e (assoc var org-table-column-names))
4064 (org-table-goto-column (string-to-number (cdr e)))
4065 (org-table-highlight-rectangle)
4066 (goto-char table-start)
4067 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
4068 (org-table-end) t)
4069 (progn
4070 (goto-char (match-beginning 1))
4071 (org-table-highlight-rectangle)
4072 (message "Named column (column %s)" (cdr e)))
4073 (user-error "Column name not found")))
4074 ((eq what 'column)
4075 ;; Column number.
4076 (org-table-goto-column (string-to-number (substring match 1)))
4077 (org-table-highlight-rectangle)
4078 (message "Column %s" (substring match 1)))
4079 ((setq e (assoc var org-table-local-parameters))
4080 (goto-char table-start)
4081 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
4082 (progn
4083 (goto-char (match-beginning 1))
4084 (org-table-highlight-rectangle)
4085 (message "Local parameter."))
4086 (user-error "Parameter not found")))
4087 ((not var) (user-error "No reference at point"))
4088 ((setq e (assoc var org-table-formula-constants-local))
4089 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4090 var (cdr e)))
4091 ((setq e (assoc var org-table-formula-constants))
4092 (message "Constant: $%s=%s in `org-table-formula-constants'."
4093 var (cdr e)))
4094 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4095 (message "Constant: $%s=%s, from `constants.el'%s."
4096 var e (format " (%s units)" constants-unit-system)))
4097 (t (user-error "Undefined name $%s" var)))
4098 (goto-char pos)
4099 (when (and org-show-positions
4100 (not (memq this-command '(org-table-fedit-scroll
4101 org-table-fedit-scroll-down))))
4102 (push pos org-show-positions)
4103 (push table-start org-show-positions)
4104 (let ((min (apply 'min org-show-positions))
4105 (max (apply 'max org-show-positions)))
4106 (set-window-start (selected-window) min)
4107 (goto-char max)
4108 (or (pos-visible-in-window-p max)
4109 (set-window-start (selected-window) max)))))
4110 (select-window win))))
4112 (defun org-table-force-dataline ()
4113 "Make sure the cursor is in a dataline in a table."
4114 (unless (save-excursion
4115 (beginning-of-line 1)
4116 (looking-at org-table-dataline-regexp))
4117 (let* ((re org-table-dataline-regexp)
4118 (p1 (save-excursion (re-search-forward re nil 'move)))
4119 (p2 (save-excursion (re-search-backward re nil 'move))))
4120 (cond ((and p1 p2)
4121 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4122 p1 p2)))
4123 ((or p1 p2) (goto-char (or p1 p2)))
4124 (t (user-error "No table dataline around here"))))))
4126 (defun org-table-fedit-line-up ()
4127 "Move cursor one line up in the window showing the table."
4128 (interactive)
4129 (org-table-fedit-move 'previous-line))
4131 (defun org-table-fedit-line-down ()
4132 "Move cursor one line down in the window showing the table."
4133 (interactive)
4134 (org-table-fedit-move 'next-line))
4136 (defun org-table-fedit-move (command)
4137 "Move the cursor in the window showing the table.
4138 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4139 (let ((org-table-allow-automatic-line-recalculation nil)
4140 (pos org-pos) (win (selected-window)) p)
4141 (select-window (get-buffer-window (marker-buffer org-pos)))
4142 (setq p (point))
4143 (call-interactively command)
4144 (while (and (org-at-table-p)
4145 (org-at-table-hline-p))
4146 (call-interactively command))
4147 (or (org-at-table-p) (goto-char p))
4148 (move-marker pos (point))
4149 (select-window win)))
4151 (defun org-table-fedit-scroll (N)
4152 (interactive "p")
4153 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4154 (scroll-other-window N)))
4156 (defun org-table-fedit-scroll-down (N)
4157 (interactive "p")
4158 (org-table-fedit-scroll (- N)))
4160 (defvar org-table-rectangle-overlays nil)
4162 (defun org-table-add-rectangle-overlay (beg end &optional face)
4163 "Add a new overlay."
4164 (let ((ov (make-overlay beg end)))
4165 (overlay-put ov 'face (or face 'secondary-selection))
4166 (push ov org-table-rectangle-overlays)))
4168 (defun org-table-highlight-rectangle (&optional beg end face)
4169 "Highlight rectangular region in a table.
4170 When buffer positions BEG and END are provided, use them to
4171 delimit the region to highlight. Otherwise, refer to point. Use
4172 FACE, when non-nil, for the highlight."
4173 (let* ((beg (or beg (point)))
4174 (end (or end (point)))
4175 (b (min beg end))
4176 (e (max beg end))
4177 (start-coordinates
4178 (save-excursion
4179 (goto-char b)
4180 (cons (line-beginning-position) (org-table-current-column))))
4181 (end-coordinates
4182 (save-excursion
4183 (goto-char e)
4184 (cons (line-beginning-position) (org-table-current-column)))))
4185 (when (boundp 'org-show-positions)
4186 (setq org-show-positions (cons b (cons e org-show-positions))))
4187 (goto-char (car start-coordinates))
4188 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4189 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4190 (last-row (car end-coordinates)))
4191 (while (<= (point) last-row)
4192 (when (looking-at org-table-dataline-regexp)
4193 (org-table-goto-column column-start)
4194 (skip-chars-backward "^|\n")
4195 (let ((p (point)))
4196 (org-table-goto-column column-end)
4197 (skip-chars-forward "^|\n")
4198 (org-table-add-rectangle-overlay p (point) face)))
4199 (forward-line)))
4200 (goto-char (car start-coordinates)))
4201 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4203 (defun org-table-remove-rectangle-highlight (&rest _ignore)
4204 "Remove the rectangle overlays."
4205 (unless org-inhibit-highlight-removal
4206 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4207 (mapc 'delete-overlay org-table-rectangle-overlays)
4208 (setq org-table-rectangle-overlays nil)))
4210 (defvar-local org-table-coordinate-overlays nil
4211 "Collects the coordinate grid overlays, so that they can be removed.")
4213 (defun org-table-overlay-coordinates ()
4214 "Add overlays to the table at point, to show row/column coordinates."
4215 (interactive)
4216 (mapc 'delete-overlay org-table-coordinate-overlays)
4217 (setq org-table-coordinate-overlays nil)
4218 (save-excursion
4219 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4220 (goto-char (org-table-begin))
4221 (while (org-at-table-p)
4222 (setq eol (point-at-eol))
4223 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4224 (push ov org-table-coordinate-overlays)
4225 (setq hline (looking-at org-table-hline-regexp))
4226 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4227 (format "%4d" (setq id (1+ id)))))
4228 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4229 (when hline
4230 (setq ic 0)
4231 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4232 (setq beg (1+ (match-beginning 0))
4233 ic (1+ ic)
4234 s1 (concat "$" (int-to-string ic))
4235 s2 (org-number-to-letters ic)
4236 str (if (eq org-table-use-standard-references t) s2 s1))
4237 (setq ov (make-overlay beg (+ beg (length str))))
4238 (push ov org-table-coordinate-overlays)
4239 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4240 (beginning-of-line 2)))))
4242 ;;;###autoload
4243 (defun org-table-toggle-coordinate-overlays ()
4244 "Toggle the display of Row/Column numbers in tables."
4245 (interactive)
4246 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4247 (message "Tables Row/Column numbers display turned %s"
4248 (if org-table-overlay-coordinates "on" "off"))
4249 (if (and (org-at-table-p) org-table-overlay-coordinates)
4250 (org-table-align))
4251 (unless org-table-overlay-coordinates
4252 (mapc 'delete-overlay org-table-coordinate-overlays)
4253 (setq org-table-coordinate-overlays nil)))
4255 ;;;###autoload
4256 (defun org-table-toggle-formula-debugger ()
4257 "Toggle the formula debugger in tables."
4258 (interactive)
4259 (setq org-table-formula-debug (not org-table-formula-debug))
4260 (message "Formula debugging has been turned %s"
4261 (if org-table-formula-debug "on" "off")))
4263 ;;; The orgtbl minor mode
4265 ;; Define a minor mode which can be used in other modes in order to
4266 ;; integrate the Org table editor.
4268 ;; This is really a hack, because the Org table editor uses several
4269 ;; keys which normally belong to the major mode, for example the TAB
4270 ;; and RET keys. Here is how it works: The minor mode defines all the
4271 ;; keys necessary to operate the table editor, but wraps the commands
4272 ;; into a function which tests if the cursor is currently inside
4273 ;; a table. If that is the case, the table editor command is
4274 ;; executed. However, when any of those keys is used outside a table,
4275 ;; the function uses `key-binding' to look up if the key has an
4276 ;; associated command in another currently active keymap (minor modes,
4277 ;; major mode, global), and executes that command. There might be
4278 ;; problems if any of the keys used by the table editor is otherwise
4279 ;; used as a prefix key.
4281 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4282 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4283 ;; addresses this by checking explicitly for both bindings.
4285 ;; The optimized version (see variable `orgtbl-optimized') takes over
4286 ;; all keys which are bound to `self-insert-command' in the *global map*.
4287 ;; Some modes bind other commands to simple characters, for example
4288 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4289 ;; active, this binding is ignored inside tables and replaced with a
4290 ;; modified self-insert.
4293 (defvar orgtbl-mode-map (make-keymap)
4294 "Keymap for `orgtbl-mode'.")
4296 (defvar org-old-auto-fill-inhibit-regexp nil
4297 "Local variable used by `orgtbl-mode'.")
4299 (defconst orgtbl-line-start-regexp
4300 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4301 "Matches a line belonging to an orgtbl.")
4303 (defconst orgtbl-extra-font-lock-keywords
4304 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4305 0 (quote 'org-table) 'prepend))
4306 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4308 ;; Install it as a minor mode.
4309 (put 'orgtbl-mode :included t)
4310 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4312 ;;;###autoload
4313 (define-minor-mode orgtbl-mode
4314 "The `org-mode' table editor as a minor mode for use in other modes."
4315 :lighter " OrgTbl" :keymap orgtbl-mode-map
4316 (org-load-modules-maybe)
4317 (cond
4318 ((derived-mode-p 'org-mode)
4319 ;; Exit without error, in case some hook functions calls this
4320 ;; by accident in org-mode.
4321 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4322 (orgtbl-mode
4323 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4324 ;; Make sure we are first in minor-mode-map-alist
4325 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4326 ;; FIXME: maybe it should use emulation-mode-map-alists?
4327 (and c (setq minor-mode-map-alist
4328 (cons c (delq c minor-mode-map-alist)))))
4329 (setq-local org-table-may-need-update t)
4330 (add-hook 'before-change-functions 'org-before-change-function
4331 nil 'local)
4332 (setq-local org-old-auto-fill-inhibit-regexp
4333 auto-fill-inhibit-regexp)
4334 (setq-local auto-fill-inhibit-regexp
4335 (if auto-fill-inhibit-regexp
4336 (concat orgtbl-line-start-regexp "\\|"
4337 auto-fill-inhibit-regexp)
4338 orgtbl-line-start-regexp))
4339 (add-to-invisibility-spec '(org-cwidth))
4340 (when (fboundp 'font-lock-add-keywords)
4341 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4342 (org-restart-font-lock))
4343 (easy-menu-add orgtbl-mode-menu))
4345 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4346 (org-table-cleanup-narrow-column-properties)
4347 (org-remove-from-invisibility-spec '(org-cwidth))
4348 (remove-hook 'before-change-functions 'org-before-change-function t)
4349 (when (fboundp 'font-lock-remove-keywords)
4350 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4351 (org-restart-font-lock))
4352 (easy-menu-remove orgtbl-mode-menu)
4353 (force-mode-line-update 'all))))
4355 (defun org-table-cleanup-narrow-column-properties ()
4356 "Remove all properties related to narrow-column invisibility."
4357 (let ((s (point-min)))
4358 (while (setq s (text-property-any s (point-max)
4359 'display org-narrow-column-arrow))
4360 (remove-text-properties s (1+ s) '(display t)))
4361 (setq s (point-min))
4362 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4363 (remove-text-properties s (1+ s) '(org-cwidth t)))
4364 (setq s (point-min))
4365 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4366 (remove-text-properties s (1+ s) '(invisible t)))))
4368 (defun orgtbl-make-binding (fun n &rest keys)
4369 "Create a function for binding in the table minor mode.
4370 FUN is the command to call inside a table. N is used to create a unique
4371 command name. KEYS are keys that should be checked in for a command
4372 to execute outside of tables."
4373 (eval
4374 (list 'defun
4375 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4376 '(arg)
4377 (concat "In tables, run `" (symbol-name fun) "'.\n"
4378 "Outside of tables, run the binding of `"
4379 (mapconcat #'key-description keys "' or `")
4380 "'.")
4381 '(interactive "p")
4382 (list 'if
4383 '(org-at-table-p)
4384 (list 'call-interactively (list 'quote fun))
4385 (list 'let '(orgtbl-mode)
4386 (list 'call-interactively
4387 (append '(or)
4388 (mapcar (lambda (k)
4389 (list 'key-binding k))
4390 keys)
4391 '('orgtbl-error))))))))
4393 (defun orgtbl-error ()
4394 "Error when there is no default binding for a table key."
4395 (interactive)
4396 (user-error "This key has no function outside tables"))
4398 (defun orgtbl-setup ()
4399 "Setup orgtbl keymaps."
4400 (let ((nfunc 0)
4401 (bindings
4402 '(([(meta shift left)] org-table-delete-column)
4403 ([(meta left)] org-table-move-column-left)
4404 ([(meta right)] org-table-move-column-right)
4405 ([(meta shift right)] org-table-insert-column)
4406 ([(meta shift up)] org-table-kill-row)
4407 ([(meta shift down)] org-table-insert-row)
4408 ([(meta up)] org-table-move-row-up)
4409 ([(meta down)] org-table-move-row-down)
4410 ("\C-c\C-w" org-table-cut-region)
4411 ("\C-c\M-w" org-table-copy-region)
4412 ("\C-c\C-y" org-table-paste-rectangle)
4413 ("\C-c\C-w" org-table-wrap-region)
4414 ("\C-c-" org-table-insert-hline)
4415 ("\C-c}" org-table-toggle-coordinate-overlays)
4416 ("\C-c{" org-table-toggle-formula-debugger)
4417 ("\C-m" org-table-next-row)
4418 ([(shift return)] org-table-copy-down)
4419 ("\C-c?" org-table-field-info)
4420 ("\C-c " org-table-blank-field)
4421 ("\C-c+" org-table-sum)
4422 ("\C-c=" org-table-eval-formula)
4423 ("\C-c'" org-table-edit-formulas)
4424 ("\C-c`" org-table-edit-field)
4425 ("\C-c*" org-table-recalculate)
4426 ("\C-c^" org-table-sort-lines)
4427 ("\M-a" org-table-beginning-of-field)
4428 ("\M-e" org-table-end-of-field)
4429 ([(control ?#)] org-table-rotate-recalc-marks)))
4430 elt key fun cmd)
4431 (while (setq elt (pop bindings))
4432 (setq nfunc (1+ nfunc))
4433 (setq key (org-key (car elt))
4434 fun (nth 1 elt)
4435 cmd (orgtbl-make-binding fun nfunc key))
4436 (org-defkey orgtbl-mode-map key cmd))
4438 ;; Special treatment needed for TAB, RET and DEL
4439 (org-defkey orgtbl-mode-map [(return)]
4440 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4441 (org-defkey orgtbl-mode-map "\C-m"
4442 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4443 (org-defkey orgtbl-mode-map [(tab)]
4444 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4445 (org-defkey orgtbl-mode-map "\C-i"
4446 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4447 (org-defkey orgtbl-mode-map [(shift tab)]
4448 (orgtbl-make-binding 'org-table-previous-field 104
4449 [(shift tab)] [(tab)] "\C-i"))
4450 (org-defkey orgtbl-mode-map [backspace]
4451 (orgtbl-make-binding 'org-delete-backward-char 109
4452 [backspace] (kbd "DEL")))
4454 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4455 (orgtbl-make-binding 'org-table-previous-field 107
4456 [S-iso-lefttab] [backtab] [(shift tab)]
4457 [(tab)] "\C-i"))
4459 (org-defkey orgtbl-mode-map [backtab]
4460 (orgtbl-make-binding 'org-table-previous-field 108
4461 [backtab] [S-iso-lefttab] [(shift tab)]
4462 [(tab)] "\C-i"))
4464 (org-defkey orgtbl-mode-map "\M-\C-m"
4465 (orgtbl-make-binding 'org-table-wrap-region 105
4466 "\M-\C-m" [(meta return)]))
4467 (org-defkey orgtbl-mode-map [(meta return)]
4468 (orgtbl-make-binding 'org-table-wrap-region 106
4469 [(meta return)] "\M-\C-m"))
4471 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4472 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4474 (when orgtbl-optimized
4475 ;; If the user wants maximum table support, we need to hijack
4476 ;; some standard editing functions
4477 (org-remap orgtbl-mode-map
4478 'self-insert-command 'orgtbl-self-insert-command
4479 'delete-char 'org-delete-char
4480 'delete-backward-char 'org-delete-backward-char)
4481 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4482 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4483 '("OrgTbl"
4484 ["Create or convert" org-table-create-or-convert-from-region
4485 :active (not (org-at-table-p)) :keys "C-c |" ]
4486 "--"
4487 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4488 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4489 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4490 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4491 "--"
4492 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4493 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4494 ["Copy Field from Above"
4495 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4496 "--"
4497 ("Column"
4498 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4499 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4500 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4501 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4502 ("Row"
4503 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4504 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4505 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4506 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4507 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4508 "--"
4509 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4510 ("Rectangle"
4511 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4512 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4513 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4514 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4515 "--"
4516 ("Radio tables"
4517 ["Insert table template" orgtbl-insert-radio-table
4518 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
4519 ["Comment/uncomment table" orgtbl-toggle-comment t])
4520 "--"
4521 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4522 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4523 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4524 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4525 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4526 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4527 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4528 ["Sum Column/Rectangle" org-table-sum
4529 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4530 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4531 ["Debug Formulas"
4532 org-table-toggle-formula-debugger :active (org-at-table-p)
4533 :keys "C-c {"
4534 :style toggle :selected org-table-formula-debug]
4535 ["Show Col/Row Numbers"
4536 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4537 :keys "C-c }"
4538 :style toggle :selected org-table-overlay-coordinates]
4539 "--"
4540 ("Plot"
4541 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4542 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4545 (defun orgtbl-ctrl-c-ctrl-c (arg)
4546 "If the cursor is inside a table, realign the table.
4547 If it is a table to be sent away to a receiver, do it.
4548 With prefix arg, also recompute table."
4549 (interactive "P")
4550 (let ((case-fold-search t) (pos (point)) action)
4551 (save-excursion
4552 (beginning-of-line 1)
4553 (setq action (cond
4554 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4555 ((looking-at "[ \t]*|") pos)
4556 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4557 (cond
4558 ((integerp action)
4559 (goto-char action)
4560 (org-table-maybe-eval-formula)
4561 (if arg
4562 (call-interactively 'org-table-recalculate)
4563 (org-table-maybe-recalculate-line))
4564 (call-interactively 'org-table-align)
4565 (when (orgtbl-send-table 'maybe)
4566 (run-hooks 'orgtbl-after-send-table-hook)))
4567 ((eq action 'recalc)
4568 (save-excursion
4569 (beginning-of-line 1)
4570 (skip-chars-backward " \r\n\t")
4571 (if (org-at-table-p)
4572 (org-call-with-arg 'org-table-recalculate t))))
4573 (t (let (orgtbl-mode)
4574 (call-interactively (key-binding "\C-c\C-c")))))))
4576 (defun orgtbl-create-or-convert-from-region (_arg)
4577 "Create table or convert region to table, if no conflicting binding.
4578 This installs the table binding `C-c |', but only if there is no
4579 conflicting binding to this key outside orgtbl-mode."
4580 (interactive "P")
4581 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4582 (if cmd
4583 (call-interactively cmd)
4584 (call-interactively 'org-table-create-or-convert-from-region))))
4586 (defun orgtbl-tab (arg)
4587 "Justification and field motion for `orgtbl-mode'."
4588 (interactive "P")
4589 (if arg (org-table-edit-field t)
4590 (org-table-justify-field-maybe)
4591 (org-table-next-field)))
4593 (defun orgtbl-ret ()
4594 "Justification and field motion for `orgtbl-mode'."
4595 (interactive)
4596 (if (bobp)
4597 (newline)
4598 (org-table-justify-field-maybe)
4599 (org-table-next-row)))
4601 (defun orgtbl-self-insert-command (N)
4602 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4603 If the cursor is in a table looking at whitespace, the whitespace is
4604 overwritten, and the table is not marked as requiring realignment."
4605 (interactive "p")
4606 (if (and (org-at-table-p)
4608 (and org-table-auto-blank-field
4609 (member last-command
4610 '(orgtbl-hijacker-command-100
4611 orgtbl-hijacker-command-101
4612 orgtbl-hijacker-command-102
4613 orgtbl-hijacker-command-103
4614 orgtbl-hijacker-command-104
4615 orgtbl-hijacker-command-105
4616 yas/expand))
4617 (org-table-blank-field))
4619 (eq N 1)
4620 (looking-at "[^|\n]* \\( \\)|"))
4621 (let (org-table-may-need-update)
4622 (delete-region (match-beginning 1) (match-end 1))
4623 (self-insert-command N))
4624 (setq org-table-may-need-update t)
4625 (let* (orgtbl-mode
4627 (cmd (or (key-binding
4628 (or (and (listp function-key-map)
4629 (setq a (assoc last-input-event function-key-map))
4630 (cdr a))
4631 (vector last-input-event)))
4632 'self-insert-command)))
4633 (call-interactively cmd)
4634 (if (and org-self-insert-cluster-for-undo
4635 (eq cmd 'self-insert-command))
4636 (if (not (eq last-command 'orgtbl-self-insert-command))
4637 (setq org-self-insert-command-undo-counter 1)
4638 (if (>= org-self-insert-command-undo-counter 20)
4639 (setq org-self-insert-command-undo-counter 1)
4640 (and (> org-self-insert-command-undo-counter 0)
4641 buffer-undo-list
4642 (not (cadr buffer-undo-list)) ; remove nil entry
4643 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4644 (setq org-self-insert-command-undo-counter
4645 (1+ org-self-insert-command-undo-counter))))))))
4647 ;;;###autoload
4648 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4649 "Regular expression matching exponentials as produced by calc.")
4651 (defun orgtbl-gather-send-defs ()
4652 "Gather a plist of :name, :transform, :params for each destination before
4653 a radio table."
4654 (save-excursion
4655 (goto-char (org-table-begin))
4656 (let (rtn)
4657 (beginning-of-line 0)
4658 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4659 (let ((name (org-no-properties (match-string 1)))
4660 (transform (intern (match-string 2)))
4661 (params (if (match-end 3)
4662 (read (concat "(" (match-string 3) ")")))))
4663 (push (list :name name :transform transform :params params)
4664 rtn)
4665 (beginning-of-line 0)))
4666 rtn)))
4668 (defun orgtbl-send-replace-tbl (name text)
4669 "Find and replace table NAME with TEXT."
4670 (save-excursion
4671 (goto-char (point-min))
4672 (let* ((location-flag nil)
4673 (name (regexp-quote name))
4674 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4675 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4676 (while (re-search-forward begin-re nil t)
4677 (unless location-flag (setq location-flag t))
4678 (let ((beg (line-beginning-position 2)))
4679 (unless (re-search-forward end-re nil t)
4680 (user-error "Cannot find end of receiver location at %d" beg))
4681 (beginning-of-line)
4682 (delete-region beg (point))
4683 (insert text "\n")))
4684 (unless location-flag
4685 (user-error "No valid receiver location found in the buffer")))))
4687 ;;;###autoload
4688 (defun org-table-to-lisp (&optional txt)
4689 "Convert the table at point to a Lisp structure.
4690 The structure will be a list. Each item is either the symbol `hline'
4691 for a horizontal separator line, or a list of field values as strings.
4692 The table is taken from the parameter TXT, or from the buffer at point."
4693 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4694 (let ((txt (or txt
4695 (buffer-substring-no-properties (org-table-begin)
4696 (org-table-end)))))
4697 (mapcar (lambda (x)
4698 (if (string-match org-table-hline-regexp x) 'hline
4699 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4700 (org-split-string txt "[ \t]*\n[ \t]*"))))
4702 (defun orgtbl-send-table (&optional maybe)
4703 "Send a transformed version of table at point to the receiver position.
4704 With argument MAYBE, fail quietly if no transformation is defined
4705 for this table."
4706 (interactive)
4707 (catch 'exit
4708 (unless (org-at-table-p) (user-error "Not at a table"))
4709 ;; when non-interactive, we assume align has just happened.
4710 (when (called-interactively-p 'any) (org-table-align))
4711 (let ((dests (orgtbl-gather-send-defs))
4712 (table (org-table-to-lisp
4713 (buffer-substring-no-properties (org-table-begin)
4714 (org-table-end))))
4715 (ntbl 0))
4716 (unless dests
4717 (if maybe (throw 'exit nil)
4718 (user-error "Don't know how to transform this table")))
4719 (dolist (dest dests)
4720 (let ((name (plist-get dest :name))
4721 (transform (plist-get dest :transform))
4722 (params (plist-get dest :params)))
4723 (unless (fboundp transform)
4724 (user-error "No such transformation function %s" transform))
4725 (orgtbl-send-replace-tbl name (funcall transform table params)))
4726 (cl-incf ntbl))
4727 (message "Table converted and installed at %d receiver location%s"
4728 ntbl (if (> ntbl 1) "s" ""))
4729 (and (> ntbl 0) ntbl))))
4731 (defun org-remove-by-index (list indices &optional i0)
4732 "Remove the elements in LIST with indices in INDICES.
4733 First element has index 0, or I0 if given."
4734 (if (not indices)
4735 list
4736 (if (integerp indices) (setq indices (list indices)))
4737 (setq i0 (1- (or i0 0)))
4738 (delq :rm (mapcar (lambda (x)
4739 (setq i0 (1+ i0))
4740 (if (memq i0 indices) :rm x))
4741 list))))
4743 (defun orgtbl-toggle-comment ()
4744 "Comment or uncomment the orgtbl at point."
4745 (interactive)
4746 (let* ((case-fold-search t)
4747 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4748 (re2 (concat "^" orgtbl-line-start-regexp))
4749 (commented (save-excursion (beginning-of-line 1)
4750 (cond ((looking-at re1) t)
4751 ((looking-at re2) nil)
4752 (t (user-error "Not at an org table")))))
4753 (re (if commented re1 re2))
4754 beg end)
4755 (save-excursion
4756 (beginning-of-line 1)
4757 (while (looking-at re) (beginning-of-line 0))
4758 (beginning-of-line 2)
4759 (setq beg (point))
4760 (while (looking-at re) (beginning-of-line 2))
4761 (setq end (point)))
4762 (comment-region beg end (if commented '(4) nil))))
4764 (defun orgtbl-insert-radio-table ()
4765 "Insert a radio table template appropriate for this major mode."
4766 (interactive)
4767 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
4768 (txt (nth 1 e))
4769 name pos)
4770 (unless e (user-error "No radio table setup defined for %s" major-mode))
4771 (setq name (read-string "Table name: "))
4772 (while (string-match "%n" txt)
4773 (setq txt (replace-match name t t txt)))
4774 (or (bolp) (insert "\n"))
4775 (setq pos (point))
4776 (insert txt)
4777 (goto-char pos)))
4779 ;;;###autoload
4780 (defun orgtbl-to-generic (table params)
4781 "Convert the orgtbl-mode TABLE to some other format.
4783 This generic routine can be used for many standard cases.
4785 TABLE is a list, each entry either the symbol `hline' for
4786 a horizontal separator line, or a list of fields for that
4787 line. PARAMS is a property list of parameters that can
4788 influence the conversion.
4790 Valid parameters are:
4792 :backend, :raw
4794 Export back-end used as a basis to transcode elements of the
4795 table, when no specific parameter applies to it. It is also
4796 used to translate cells contents. You can prevent this by
4797 setting :raw property to a non-nil value.
4799 :splice
4801 When non-nil, only convert rows, not the table itself. This is
4802 equivalent to setting to the empty string both :tstart
4803 and :tend, which see.
4805 :skip
4807 When set to an integer N, skip the first N lines of the table.
4808 Horizontal separation lines do count for this parameter!
4810 :skipcols
4812 List of columns that should be skipped. If the table has
4813 a column with calculation marks, that column is automatically
4814 discarded beforehand.
4816 :hline
4818 String to be inserted on horizontal separation lines. May be
4819 nil to ignore these lines altogether.
4821 :sep
4823 Separator between two fields, as a string.
4825 Each in the following group may be either a string or a function
4826 of no arguments returning a string:
4828 :tstart, :tend
4830 Strings to start and end the table. Ignored when :splice is t.
4832 :lstart, :lend
4834 Strings to start and end a new table line.
4836 :llstart, :llend
4838 Strings to start and end the last table line. Default,
4839 respectively, to :lstart and :lend.
4841 Each in the following group may be a string or a function of one
4842 argument (either the cells in the current row, as a list of
4843 strings, or the current cell) returning a string:
4845 :lfmt
4847 Format string for an entire row, with enough %s to capture all
4848 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4850 :llfmt
4852 Format for the entire last line, defaults to :lfmt.
4854 :fmt
4856 A format to be used to wrap the field, should contain %s for
4857 the original field value. For example, to wrap everything in
4858 dollars, you could use :fmt \"$%s$\". This may also be
4859 a property list with column numbers and format strings, or
4860 functions, e.g.,
4862 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4864 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4866 Same as above, specific for the header lines in the table.
4867 All lines before the first hline are treated as header. If
4868 any of these is not present, the data line value is used.
4870 This may be either a string or a function of two arguments:
4872 :efmt
4874 Use this format to print numbers with exponential. The format
4875 should have %s twice for inserting mantissa and exponent, for
4876 example \"%s\\\\times10^{%s}\". This may also be a property
4877 list with column numbers and format strings or functions.
4878 :fmt will still be applied after :efmt."
4879 ;; Make sure `org-export-create-backend' is available.
4880 (require 'ox)
4881 (let* ((backend (plist-get params :backend))
4882 (custom-backend
4883 ;; Build a custom back-end according to PARAMS. Before
4884 ;; defining a translator, check if there is anything to do.
4885 ;; When there isn't, let BACKEND handle the element.
4886 (org-export-create-backend
4887 :parent (or backend 'org)
4888 :transcoders
4889 `((table . ,(org-table--to-generic-table params))
4890 (table-row . ,(org-table--to-generic-row params))
4891 (table-cell . ,(org-table--to-generic-cell params))
4892 ;; Macros are not going to be expanded. However, no
4893 ;; regular back-end has a transcoder for them. We
4894 ;; provide one so they are not ignored, but displayed
4895 ;; as-is instead.
4896 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4897 data info)
4898 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4899 ;; Initialize communication channel in INFO.
4900 (with-temp-buffer
4901 (let ((org-inhibit-startup t)) (org-mode))
4902 (let ((standard-output (current-buffer))
4903 (org-element-use-cache nil))
4904 (dolist (e table)
4905 (cond ((eq e 'hline) (princ "|--\n"))
4906 ((consp e)
4907 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4908 (princ "\n")))))
4909 ;; Add back-end specific filters, but not user-defined ones. In
4910 ;; particular, make sure to call parse-tree filters on the
4911 ;; table.
4912 (setq info
4913 (let ((org-export-filters-alist nil))
4914 (org-export-install-filters
4915 (org-combine-plists
4916 (org-export-get-environment backend nil params)
4917 `(:back-end ,(org-export-get-backend backend))))))
4918 (setq data
4919 (org-export-filter-apply-functions
4920 (plist-get info :filter-parse-tree)
4921 (org-element-map (org-element-parse-buffer) 'table
4922 #'identity nil t)
4923 info)))
4924 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4925 (user-error "Unknown :backend value"))
4926 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4927 ;; Handle :skip parameter.
4928 (let ((skip (plist-get info :skip)))
4929 (when skip
4930 (unless (wholenump skip) (user-error "Wrong :skip value"))
4931 (let ((n 0))
4932 (org-element-map data 'table-row
4933 (lambda (row)
4934 (if (>= n skip) t
4935 (org-element-extract-element row)
4936 (cl-incf n)
4937 nil))
4938 nil t))))
4939 ;; Handle :skipcols parameter.
4940 (let ((skipcols (plist-get info :skipcols)))
4941 (when skipcols
4942 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4943 (org-element-map data 'table
4944 (lambda (table)
4945 (let ((specialp (org-export-table-has-special-column-p table)))
4946 (dolist (row (org-element-contents table))
4947 (when (eq (org-element-property :type row) 'standard)
4948 (let ((c 1))
4949 (dolist (cell (nthcdr (if specialp 1 0)
4950 (org-element-contents row)))
4951 (when (memq c skipcols)
4952 (org-element-extract-element cell))
4953 (cl-incf c))))))))))
4954 ;; Since we are going to export using a low-level mechanism,
4955 ;; ignore special column and special rows manually.
4956 (let ((special? (org-export-table-has-special-column-p data))
4957 ignore)
4958 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4959 (lambda (datum)
4960 (when (if (eq (org-element-type datum) 'table-row)
4961 (org-export-table-row-is-special-p datum nil)
4962 (org-export-first-sibling-p datum nil))
4963 (push datum ignore))))
4964 (setq info (plist-put info :ignore-list ignore)))
4965 ;; We use a low-level mechanism to export DATA so as to skip all
4966 ;; usual pre-processing and post-processing, i.e., hooks, Babel
4967 ;; code evaluation, include keywords and macro expansion. Only
4968 ;; back-end specific filters are retained.
4969 (let ((output (org-export-data-with-backend data custom-backend info)))
4970 ;; Remove final newline.
4971 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4973 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4974 (cond ((null value) nil)
4975 ((functionp value) `(funcall ',value ,@args))
4976 ((stringp value)
4977 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4978 (args `(format ,value ,@args))
4979 (t value)))
4980 ((and with-cons (consp value))
4981 `(let ((val (cadr (memq column ',value))))
4982 (cond ((null val) contents)
4983 ((stringp val) (format val ,@args))
4984 ((functionp val) (funcall val ,@args))
4985 (t (user-error "Wrong %s value" ,name)))))
4986 (t (user-error "Wrong %s value" name))))
4988 (defun org-table--to-generic-table (params)
4989 "Return custom table transcoder according to PARAMS.
4990 PARAMS is a plist. See `orgtbl-to-generic' for more
4991 information."
4992 (let ((backend (plist-get params :backend))
4993 (splice (plist-get params :splice))
4994 (tstart (plist-get params :tstart))
4995 (tend (plist-get params :tend)))
4996 `(lambda (table contents info)
4997 (concat
4998 ,(and tstart (not splice)
4999 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
5000 ,(if (or (not backend) tstart tend splice) 'contents
5001 `(org-export-with-backend ',backend table contents info))
5002 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
5004 (defun org-table--to-generic-row (params)
5005 "Return custom table row transcoder according to PARAMS.
5006 PARAMS is a plist. See `orgtbl-to-generic' for more
5007 information."
5008 (let* ((backend (plist-get params :backend))
5009 (lstart (plist-get params :lstart))
5010 (llstart (plist-get params :llstart))
5011 (hlstart (plist-get params :hlstart))
5012 (hllstart (plist-get params :hllstart))
5013 (lend (plist-get params :lend))
5014 (llend (plist-get params :llend))
5015 (hlend (plist-get params :hlend))
5016 (hllend (plist-get params :hllend))
5017 (lfmt (plist-get params :lfmt))
5018 (llfmt (plist-get params :llfmt))
5019 (hlfmt (plist-get params :hlfmt))
5020 (hllfmt (plist-get params :hllfmt)))
5021 `(lambda (row contents info)
5022 (if (eq (org-element-property :type row) 'rule)
5023 ,(cond
5024 ((plist-member params :hline)
5025 (org-table--generic-apply (plist-get params :hline) ":hline"))
5026 (backend `(org-export-with-backend ',backend row nil info)))
5027 (let ((headerp ,(and (or hlfmt hlstart hlend)
5028 '(org-export-table-row-in-header-p row info)))
5029 (last-header-p
5030 ,(and (or hllfmt hllstart hllend)
5031 '(org-export-table-row-ends-header-p row info)))
5032 (lastp (not (org-export-get-next-element row info))))
5033 (when contents
5034 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5035 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5036 ;; `:lstart', `:lend' and their relatives.
5037 ,(let ((cells
5038 '(org-element-map row 'table-cell
5039 (lambda (cell)
5040 ;; Export all cells, without separators.
5042 ;; Use `org-export-data-with-backend'
5043 ;; instead of `org-export-data' to eschew
5044 ;; cached values, which
5045 ;; ignore :orgtbl-ignore-sep parameter.
5046 (org-export-data-with-backend
5047 cell
5048 (plist-get info :back-end)
5049 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5050 info)))
5051 `(cond
5052 ,(and hllfmt
5053 `(last-header-p ,(org-table--generic-apply
5054 hllfmt ":hllfmt" nil cells)))
5055 ,(and hlfmt
5056 `(headerp ,(org-table--generic-apply
5057 hlfmt ":hlfmt" nil cells)))
5058 ,(and llfmt
5059 `(lastp ,(org-table--generic-apply
5060 llfmt ":llfmt" nil cells)))
5062 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5063 `(concat
5064 (cond
5065 ,(and
5066 (or hllstart hllend)
5067 `(last-header-p
5068 (concat
5069 ,(org-table--generic-apply hllstart ":hllstart")
5070 contents
5071 ,(org-table--generic-apply hllend ":hllend"))))
5072 ,(and
5073 (or hlstart hlend)
5074 `(headerp
5075 (concat
5076 ,(org-table--generic-apply hlstart ":hlstart")
5077 contents
5078 ,(org-table--generic-apply hlend ":hlend"))))
5079 ,(and
5080 (or llstart llend)
5081 `(lastp
5082 (concat
5083 ,(org-table--generic-apply llstart ":llstart")
5084 contents
5085 ,(org-table--generic-apply llend ":llend"))))
5087 ,(cond
5088 ((or lstart lend)
5089 `(concat
5090 ,(org-table--generic-apply lstart ":lstart")
5091 contents
5092 ,(org-table--generic-apply lend ":lend")))
5093 (backend
5094 `(org-export-with-backend
5095 ',backend row contents info))
5096 (t 'contents)))))))))))))))
5098 (defun org-table--to-generic-cell (params)
5099 "Return custom table cell transcoder according to PARAMS.
5100 PARAMS is a plist. See `orgtbl-to-generic' for more
5101 information."
5102 (let* ((backend (plist-get params :backend))
5103 (efmt (plist-get params :efmt))
5104 (fmt (plist-get params :fmt))
5105 (hfmt (plist-get params :hfmt))
5106 (sep (plist-get params :sep))
5107 (hsep (plist-get params :hsep)))
5108 `(lambda (cell contents info)
5109 ;; Make sure that contents are exported as Org data when :raw
5110 ;; parameter is non-nil.
5111 ,(when (and backend (plist-get params :raw))
5112 `(setq contents
5113 ;; Since we don't know what are the pseudo object
5114 ;; types defined in backend, we cannot pass them to
5115 ;; `org-element-interpret-data'. As a consequence,
5116 ;; they will be treated as pseudo elements, and will
5117 ;; have newlines appended instead of spaces.
5118 ;; Therefore, we must make sure :post-blank value is
5119 ;; really turned into spaces.
5120 (replace-regexp-in-string
5121 "\n" " "
5122 (org-trim
5123 (org-element-interpret-data
5124 (org-element-contents cell))))))
5126 (let ((headerp ,(and (or hfmt hsep)
5127 '(org-export-table-row-in-header-p
5128 (org-export-get-parent-element cell) info)))
5129 (column
5130 ;; Call costly `org-export-table-cell-address' only if
5131 ;; absolutely necessary, i.e., if one
5132 ;; of :fmt :efmt :hfmt has a "plist type" value.
5133 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5134 (list efmt hfmt fmt))
5135 '(1+ (cdr (org-export-table-cell-address cell info))))))
5136 (when contents
5137 ;; Check if we can apply `:efmt' on CONTENTS.
5138 ,(when efmt
5139 `(when (string-match orgtbl-exp-regexp contents)
5140 (let ((mantissa (match-string 1 contents))
5141 (exponent (match-string 2 contents)))
5142 (setq contents ,(org-table--generic-apply
5143 efmt ":efmt" t 'mantissa 'exponent)))))
5144 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5145 (cond
5146 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5147 hfmt ":hfmt" t 'contents))))
5148 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5149 fmt ":fmt" t 'contents))))))
5150 ;; If a separator is provided, use it instead of BACKEND's.
5151 ;; Separators are ignored when LFMT (or equivalent) is
5152 ;; provided.
5153 ,(cond
5154 ((or hsep sep)
5155 `(if (or ,(and (not sep) '(not headerp))
5156 (plist-get info :orgtbl-ignore-sep)
5157 (not (org-export-get-next-element cell info)))
5158 ,(if (not backend) 'contents
5159 `(org-export-with-backend ',backend cell contents info))
5160 (concat contents
5161 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5162 (or hsep sep)))))
5163 (backend `(org-export-with-backend ',backend cell contents info))
5164 (t 'contents))))))
5166 ;;;###autoload
5167 (defun orgtbl-to-tsv (table params)
5168 "Convert the orgtbl-mode table to TAB separated material."
5169 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5171 ;;;###autoload
5172 (defun orgtbl-to-csv (table params)
5173 "Convert the orgtbl-mode table to CSV material.
5174 This does take care of the proper quoting of fields with comma or quotes."
5175 (orgtbl-to-generic table
5176 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5177 params)))
5179 ;;;###autoload
5180 (defun orgtbl-to-latex (table params)
5181 "Convert the orgtbl-mode TABLE to LaTeX.
5183 TABLE is a list, each entry either the symbol `hline' for
5184 a horizontal separator line, or a list of fields for that line.
5185 PARAMS is a property list of parameters that can influence the
5186 conversion. All parameters from `orgtbl-to-generic' are
5187 supported. It is also possible to use the following ones:
5189 :booktabs
5191 When non-nil, use formal \"booktabs\" style.
5193 :environment
5195 Specify environment to use, as a string. If you use
5196 \"longtable\", you may also want to specify :language property,
5197 as a string, to get proper continuation strings."
5198 (require 'ox-latex)
5199 (orgtbl-to-generic
5200 table
5201 (org-combine-plists
5202 ;; Provide sane default values.
5203 (list :backend 'latex
5204 :latex-default-table-mode 'table
5205 :latex-tables-centered nil
5206 :latex-tables-booktabs (plist-get params :booktabs)
5207 :latex-table-scientific-notation nil
5208 :latex-default-table-environment
5209 (or (plist-get params :environment) "tabular"))
5210 params)))
5212 ;;;###autoload
5213 (defun orgtbl-to-html (table params)
5214 "Convert the orgtbl-mode TABLE to HTML.
5216 TABLE is a list, each entry either the symbol `hline' for
5217 a horizontal separator line, or a list of fields for that line.
5218 PARAMS is a property list of parameters that can influence the
5219 conversion. All parameters from `orgtbl-to-generic' are
5220 supported. It is also possible to use the following one:
5222 :attributes
5224 Attributes and values, as a plist, which will be used in
5225 <table> tag."
5226 (require 'ox-html)
5227 (orgtbl-to-generic
5228 table
5229 (org-combine-plists
5230 ;; Provide sane default values.
5231 (list :backend 'html
5232 :html-table-data-tags '("<td%s>" . "</td>")
5233 :html-table-use-header-tags-for-first-column nil
5234 :html-table-align-individual-fields t
5235 :html-table-row-tags '("<tr>" . "</tr>")
5236 :html-table-attributes
5237 (if (plist-member params :attributes)
5238 (plist-get params :attributes)
5239 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5240 :frame "hsides")))
5241 params)))
5243 ;;;###autoload
5244 (defun orgtbl-to-texinfo (table params)
5245 "Convert the orgtbl-mode TABLE to Texinfo.
5247 TABLE is a list, each entry either the symbol `hline' for
5248 a horizontal separator line, or a list of fields for that line.
5249 PARAMS is a property list of parameters that can influence the
5250 conversion. All parameters from `orgtbl-to-generic' are
5251 supported. It is also possible to use the following one:
5253 :columns
5255 Column widths, as a string. When providing column fractions,
5256 \"@columnfractions\" command can be omitted."
5257 (require 'ox-texinfo)
5258 (let ((output
5259 (orgtbl-to-generic
5260 table
5261 (org-combine-plists
5262 (list :backend 'texinfo
5263 :texinfo-tables-verbatim nil
5264 :texinfo-table-scientific-notation nil)
5265 params)))
5266 (columns (let ((w (plist-get params :columns)))
5267 (cond ((not w) nil)
5268 ((string-match-p "{\\|@columnfractions " w) w)
5269 (t (concat "@columnfractions " w))))))
5270 (if (not columns) output
5271 (replace-regexp-in-string
5272 "@multitable \\(.*\\)" columns output t nil 1))))
5274 ;;;###autoload
5275 (defun orgtbl-to-orgtbl (table params)
5276 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5278 TABLE is a list, each entry either the symbol `hline' for
5279 a horizontal separator line, or a list of fields for that line.
5280 PARAMS is a property list of parameters that can influence the
5281 conversion. All parameters from `orgtbl-to-generic' are
5282 supported.
5284 Useful when slicing one table into many. The :hline, :sep,
5285 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5286 be set to provide ORGTBL directives for the generated table."
5287 (require 'ox-org)
5288 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5290 (defun orgtbl-to-table.el (table params)
5291 "Convert the orgtbl-mode TABLE into a table.el table.
5292 TABLE is a list, each entry either the symbol `hline' for
5293 a horizontal separator line, or a list of fields for that line.
5294 PARAMS is a property list of parameters that can influence the
5295 conversion. All parameters from `orgtbl-to-generic' are
5296 supported."
5297 (with-temp-buffer
5298 (insert (orgtbl-to-orgtbl table params))
5299 (org-table-align)
5300 (replace-regexp-in-string
5301 "-|" "-+"
5302 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5304 (defun orgtbl-to-unicode (table params)
5305 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5307 TABLE is a list, each entry either the symbol `hline' for
5308 a horizontal separator line, or a list of fields for that line.
5309 PARAMS is a property list of parameters that can influence the
5310 conversion. All parameters from `orgtbl-to-generic' are
5311 supported. It is also possible to use the following ones:
5313 :ascii-art
5315 When non-nil, use \"ascii-art-to-unicode\" package to translate
5316 the table. You can download it here:
5317 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5319 :narrow
5321 When non-nil, narrow columns width than provided width cookie,
5322 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5323 (require 'ox-ascii)
5324 (orgtbl-to-generic
5325 table
5326 (org-combine-plists
5327 (list :backend 'ascii
5328 :ascii-charset 'utf-8
5329 :ascii-table-widen-columns (not (plist-get params :narrow))
5330 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5331 params)))
5333 ;; Put the cursor in a column containing numerical values
5334 ;; of an Org table,
5335 ;; type C-c " a
5336 ;; A new column is added with a bar plot.
5337 ;; When the table is refreshed (C-u C-c *),
5338 ;; the plot is updated to reflect the new values.
5340 (defun orgtbl-ascii-draw (value min max &optional width characters)
5341 "Draw an ascii bar in a table.
5342 VALUE is the value to plot, it determines the width of the bar to draw.
5343 MIN is the value that will be displayed as empty (zero width bar).
5344 MAX is the value that will draw a bar filling all the WIDTH.
5345 WIDTH is the span in characters from MIN to MAX.
5346 CHARACTERS is a string that will compose the bar, with shades of grey
5347 from pure white to pure black. It defaults to a 10 characters string
5348 of regular ascii characters."
5349 (let* ((width (ceiling (or width 12)))
5350 (characters (or characters " .:;c!lhVHW"))
5351 (len (1- (length characters)))
5352 (value (float (if (numberp value)
5353 value (string-to-number value))))
5354 (relative (/ (- value min) (- max min)))
5355 (steps (round (* relative width len))))
5356 (cond ((< steps 0) "too small")
5357 ((> steps (* width len)) "too large")
5358 (t (let* ((int-division (/ steps len))
5359 (remainder (- steps (* int-division len))))
5360 (concat (make-string int-division (elt characters len))
5361 (string (elt characters remainder))))))))
5363 ;;;###autoload
5364 (defun orgtbl-ascii-plot (&optional ask)
5365 "Draw an ASCII bar plot in a column.
5367 With cursor in a column containing numerical values, this function
5368 will draw a plot in a new column.
5370 ASK, if given, is a numeric prefix to override the default 12
5371 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5372 prefix,
5373 which will prompt for the width."
5374 (interactive "P")
5375 (let ((col (org-table-current-column))
5376 (min 1e999) ; 1e999 will be converted to infinity
5377 (max -1e999) ; which is the desired result
5378 (table (org-table-to-lisp))
5379 (length
5380 (cond ((consp ask)
5381 (read-number "Length of column " 12))
5382 ((numberp ask) ask)
5383 (t 12))))
5384 ;; Skip any hline a the top of table.
5385 (while (eq (car table) 'hline) (setq table (cdr table)))
5386 ;; Skip table header if any.
5387 (dolist (x (or (cdr (memq 'hline table)) table))
5388 (when (consp x)
5389 (setq x (nth (1- col) x))
5390 (when (string-match
5391 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5393 (setq x (string-to-number x))
5394 (when (> min x) (setq min x))
5395 (when (< max x) (setq max x)))))
5396 (org-table-insert-column)
5397 (org-table-move-column-right)
5398 (org-table-store-formulas
5399 (cons
5400 (cons
5401 (concat "$" (number-to-string (1+ col)))
5402 (format "'(%s $%s %s %s %s)"
5403 "orgtbl-ascii-draw" col min max length))
5404 (org-table-get-stored-formulas)))
5405 (org-table-recalculate t)))
5407 ;; Example of extension: unicode characters
5408 ;; Here are two examples of different styles.
5410 ;; Unicode block characters are used to give a smooth effect.
5411 ;; See http://en.wikipedia.org/wiki/Block_Elements
5412 ;; Use one of those drawing functions
5413 ;; - orgtbl-ascii-draw (the default ascii)
5414 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5415 ;; - orgtbl-uc-draw-cont (smooth unicode)
5417 ;; This is best viewed with the "DejaVu Sans Mono" font
5418 ;; (use M-x set-default-font).
5420 (defun orgtbl-uc-draw-grid (value min max &optional width)
5421 "Draw a bar in a table using block unicode characters.
5422 It is a variant of orgtbl-ascii-draw with Unicode block
5423 characters, for a smooth display. Bars appear as grids (to the
5424 extent the font allows)."
5425 ;; http://en.wikipedia.org/wiki/Block_Elements
5426 ;; best viewed with the "DejaVu Sans Mono" font.
5427 (orgtbl-ascii-draw value min max width
5428 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5430 (defun orgtbl-uc-draw-cont (value min max &optional width)
5431 "Draw a bar in a table using block unicode characters.
5432 It is a variant of orgtbl-ascii-draw with Unicode block
5433 characters, for a smooth display. Bars are solid (to the extent
5434 the font allows)."
5435 (orgtbl-ascii-draw value min max width
5436 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5438 (defun org-table-get-remote-range (name-or-id form)
5439 "Get a field value or a list of values in a range from table at ID.
5441 NAME-OR-ID may be the name of a table in the current file as set
5442 by a \"#+NAME:\" directive. The first table following this line
5443 will then be used. Alternatively, it may be an ID referring to
5444 any entry, also in a different file. In this case, the first
5445 table in that entry will be referenced.
5446 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5447 \"@I$2..@II$2\". All the references must be absolute, not relative.
5449 The return value is either a single string for a single field, or a
5450 list of the fields in the rectangle."
5451 (save-match-data
5452 (let ((case-fold-search t) (id-loc nil)
5453 ;; Protect a bunch of variables from being overwritten by
5454 ;; the context of the remote table.
5455 org-table-column-names org-table-column-name-regexp
5456 org-table-local-parameters org-table-named-field-locations
5457 org-table-current-line-types
5458 org-table-current-begin-pos org-table-dlines
5459 org-table-current-ncol
5460 org-table-hlines org-table-last-alignment
5461 org-table-last-column-widths org-table-last-alignment
5462 org-table-last-column-widths
5463 buffer loc)
5464 (setq form (org-table-convert-refs-to-rc form))
5465 (org-with-wide-buffer
5466 (goto-char (point-min))
5467 (if (re-search-forward
5468 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5469 (regexp-quote name-or-id) "[ \t]*$")
5470 nil t)
5471 (setq buffer (current-buffer) loc (match-beginning 0))
5472 (setq id-loc (org-id-find name-or-id 'marker))
5473 (unless (and id-loc (markerp id-loc))
5474 (user-error "Can't find remote table \"%s\"" name-or-id))
5475 (setq buffer (marker-buffer id-loc)
5476 loc (marker-position id-loc))
5477 (move-marker id-loc nil))
5478 (with-current-buffer buffer
5479 (org-with-wide-buffer
5480 (goto-char loc)
5481 (forward-char 1)
5482 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5483 (not (match-beginning 1)))
5484 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5485 (org-table-analyze)
5486 (setq form (org-table-formula-substitute-names
5487 (org-table-formula-handle-first/last-rc form)))
5488 (if (and (string-match org-table-range-regexp form)
5489 (> (length (match-string 0 form)) 1))
5490 (org-table-get-range
5491 (match-string 0 form) org-table-current-begin-pos 1)
5492 form)))))))
5494 (defun org-table-remote-reference-indirection (form)
5495 "Return formula with table remote references substituted by indirection.
5496 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5497 This indirection works only with the format @ROW$COLUMN. The
5498 format \"B3\" is not supported because it can not be
5499 distinguished from a plain table name or ID."
5500 (let ((regexp
5501 ;; Same as in `org-table-eval-formula'.
5502 (concat "\\<remote([ \t]*\\("
5503 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5504 "[@$][^ \t,]+"
5505 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5506 (replace-regexp-in-string
5507 regexp
5508 (lambda (m)
5509 (save-match-data
5510 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5511 (org-table-get-range
5512 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5513 (concat "@0" eq)
5514 eq)))))
5515 form t t 1)))
5517 (defmacro org-define-lookup-function (mode)
5518 (let ((mode-str (symbol-name mode))
5519 (first-p (eq mode 'first))
5520 (all-p (eq mode 'all)))
5521 (let ((plural-str (if all-p "s" "")))
5522 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5523 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5524 If R-LIST is nil, return matching element%s of S-LIST.
5525 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5526 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5527 This function is generated by a call to the macro `org-define-lookup-function'."
5528 mode-str plural-str plural-str plural-str)
5529 (let ,(let ((lvars '((p (or predicate 'equal))
5530 (sl s-list)
5531 (rl (or r-list s-list))
5532 (ret nil))))
5533 (if first-p (cons '(match-p nil) lvars) lvars))
5534 (while ,(if first-p '(and (not match-p) sl) 'sl)
5535 (when (funcall p val (car sl))
5536 ,(when first-p '(setq match-p t))
5537 (let ((rval (car rl)))
5538 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5539 (setq sl (cdr sl) rl (cdr rl)))
5540 ret)))))
5542 (org-define-lookup-function first)
5543 (org-define-lookup-function last)
5544 (org-define-lookup-function all)
5546 (provide 'org-table)
5548 ;; Local variables:
5549 ;; generated-autoload-file: "org-loaddefs.el"
5550 ;; End:
5552 ;;; org-table.el ends here