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