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