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