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