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