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