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