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