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