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