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