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