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