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