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