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