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