Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-table.el
blob87060feb0dfd2c523549540f721b4fa263d4efaa
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 ((or (= 0 width) ;shrink to one character
3941 (>= 1 (org-string-width (buffer-substring start end))))
3942 (list (org-table--make-shrinking-overlay
3943 start end org-table-shrunk-column-indicator
3944 (if (eq 'hline contents) "" contents))))
3945 ((eq contents 'hline) ;no contents to hide
3946 (list (org-table--make-shrinking-overlay
3947 start end
3948 (concat (make-string (max 0 (1+ width)) ?-)
3949 org-table-shrunk-column-indicator)
3950 "")))
3952 ;; If the field is not empty, consider using two overlays: one for
3953 ;; the blanks at the beginning of the field, and another one at
3954 ;; the end of the field. The former ensures a shrunk field is
3955 ;; always displayed with a single white space character in front
3956 ;; of it -- e.g., so that even right-aligned fields appear to the
3957 ;; left -- and the latter cuts the field at WIDTH visible
3958 ;; characters.
3959 (let* ((pre-overlay
3960 (and (not (equal contents ""))
3961 (org-with-point-at start (looking-at "\\( [ \t]+\\)\\S-"))
3962 (org-table--make-shrinking-overlay
3963 start (match-end 1) org-table-separator-space nil 'pre)))
3964 (post-overlay
3965 (let* ((start (if pre-overlay (overlay-end pre-overlay)
3966 (1+ start)))
3967 (w (org-string-width (buffer-substring start (1- end)))))
3968 (if (>= width w)
3969 ;; Field is too short. Extend its size by adding
3970 ;; white space characters to the right overlay.
3971 (org-table--make-shrinking-overlay
3972 (1- end) end (concat (make-string (- width w) ?\s)
3973 org-table-shrunk-column-indicator)
3974 contents)
3975 ;; Find cut location so that WIDTH characters are visible.
3976 (org-table--make-shrinking-overlay
3977 (let* ((begin start)
3978 (lower begin)
3979 (upper (1- end)))
3980 (catch :exit
3981 (while (> (- upper lower) 1)
3982 (let ((mean (+ (ash lower -1)
3983 (ash upper -1)
3984 (logand lower upper 1))))
3985 (pcase (org-string-width (buffer-substring begin mean))
3986 ((pred (= width)) (throw :exit mean))
3987 ((pred (< width)) (setq upper mean))
3988 (_ (setq lower mean)))))
3989 upper))
3990 end org-table-shrunk-column-indicator contents)))))
3991 (delq nil (list pre-overlay post-overlay))))))
3993 (defun org-table--read-column-selection (select max)
3994 "Read column selection select as a list of numbers.
3996 SELECT is a string containing column ranges, separated by white
3997 space characters, see `org-table-hide-column' for details. MAX
3998 is the maximum column number.
4000 Return value is a sorted list of numbers. Ignore any number
4001 outside of the [1;MAX] range."
4002 (catch :all
4003 (sort
4004 (delete-dups
4005 (cl-mapcan
4006 (lambda (s)
4007 (cond
4008 ((member s '("-" "1-")) (throw :all (number-sequence 1 max)))
4009 ((string-match-p "\\`[0-9]+\\'" s)
4010 (let ((n (string-to-number s)))
4011 (and (> n 0) (<= n max) (list n))))
4012 ((string-match "\\`\\([0-9]+\\)?-\\([0-9]+\\)?\\'" s)
4013 (let ((n (match-string 1 s))
4014 (m (match-string 2 s)))
4015 (number-sequence (if n (max 1 (string-to-number n))
4017 (if m (min max (string-to-number m))
4018 max))))
4019 (t nil))) ;invalid specification
4020 (split-string select)))
4021 #'<)))
4023 (defun org-table--shrink-columns (columns beg end)
4024 "Shrink COLUMNS in a table.
4025 COLUMNS is a sorted list of column numbers. BEG and END are,
4026 respectively, the beginning position and the end position of the
4027 table."
4028 (org-with-wide-buffer
4029 (org-font-lock-ensure beg end)
4030 (dolist (c columns)
4031 (goto-char beg)
4032 (let ((width nil)
4033 (fields nil))
4034 (while (< (point) end)
4035 (catch :continue
4036 (let* ((hline? (org-at-table-hline-p))
4037 (separator (if hline? "+" "|")))
4038 ;; Move to COLUMN.
4039 (search-forward "|")
4040 (or (= c 1) ;already there
4041 (search-forward separator (line-end-position) t (1- c))
4042 (throw :continue nil)) ;skip invalid columns
4043 ;; Extract boundaries and contents from current field.
4044 ;; Also set the column's width if we encounter a width
4045 ;; cookie for the first time.
4046 (let* ((start (point))
4047 (end (progn
4048 (skip-chars-forward (concat "^|" separator)
4049 (line-end-position))
4050 (point)))
4051 (contents (if hline? 'hline
4052 (org-trim (buffer-substring start end)))))
4053 (push (list start end contents) fields)
4054 (when (and (null width)
4055 (not hline?)
4056 (string-match "\\`<[lrc]?\\([0-9]+\\)>\\'" contents))
4057 (setq width (string-to-number (match-string 1 contents)))))))
4058 (forward-line))
4059 ;; Link overlays for current field to the other overlays in the
4060 ;; same column.
4061 (let ((chain (list 'siblings)))
4062 (dolist (field fields)
4063 (dolist (new (apply #'org-table--shrink-field (or width 0) field))
4064 (push new (cdr chain))
4065 (overlay-put new 'org-table-column-overlays chain))))))))
4067 ;;;###autoload
4068 (defun org-table-toggle-column-width (&optional arg)
4069 "Shrink or expand current column in an Org table.
4071 If a width cookie specifies a width W for the column, the first
4072 W visible characters are displayed. Otherwise, the column is
4073 shrunk to a single character.
4075 When point is before the first column or after the last one, ask
4076 for the columns to shrink or expand, as a list of ranges.
4077 A column range can be one of the following patterns:
4079 N column N only
4080 N-M every column between N and M (both inclusive)
4081 N- every column between N (inclusive) and the last column
4082 -M every column between the first one and M (inclusive)
4083 - every column
4085 When optional argument ARG is a string, use it as white space
4086 separated list of column ranges.
4088 When called with `\\[universal-argument]' prefix, call \
4089 `org-table-shrink', i.e.,
4090 shrink columns with a width cookie and expand the others.
4092 When called with `\\[universal-argument] \\[universal-argument]' \
4093 prefix, expand all columns."
4094 (interactive "P")
4095 (unless (org-at-table-p) (user-error "Not in a table"))
4096 (let* ((begin (org-table-begin))
4097 (end (org-table-end))
4098 ;; Compute an upper bound for the number of columns.
4099 ;; Nonexistent columns are ignored anyway.
4100 (max-columns (/ (- (line-end-position) (line-beginning-position)) 2))
4101 (shrunk (org-table--list-shrunk-columns))
4102 (columns
4103 (pcase arg
4104 (`nil
4105 (if (save-excursion
4106 (skip-chars-backward "^|" (line-beginning-position))
4107 (or (bolp) (looking-at-p "[ \t]*$")))
4108 ;; Point is either before first column or past last
4109 ;; one. Ask for columns to operate on.
4110 (org-table--read-column-selection
4111 (read-string "Column ranges (e.g. 2-4 6-): ")
4112 max-columns)
4113 (list (org-table-current-column))))
4114 ((pred stringp) (org-table--read-column-selection arg max-columns))
4115 ((or `(4) `(16)) nil)
4116 (_ (user-error "Invalid argument: %S" arg)))))
4117 (pcase arg
4118 (`(4) (org-table-shrink begin end))
4119 (`(16) (org-table-expand begin end))
4121 (org-table-expand begin end)
4122 (org-table--shrink-columns
4123 (cl-set-exclusive-or columns shrunk) begin end)))))
4125 ;;;###autoload
4126 (defun org-table-shrink (&optional begin end)
4127 "Shrink all columns with a width cookie in the table at point.
4129 Columns without a width cookie are expanded.
4131 Optional arguments BEGIN and END, when non-nil, specify the
4132 beginning and end position of the current table."
4133 (interactive)
4134 (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
4135 (org-with-wide-buffer
4136 (let ((begin (or begin (org-table-begin)))
4137 (end (or end (org-table-end)))
4138 (regexp "|[ \t]*<[lrc]?[0-9]+>[ \t]*\\(|\\|$\\)")
4139 (columns))
4140 (goto-char begin)
4141 (while (re-search-forward regexp end t)
4142 (goto-char (match-beginning 1))
4143 (cl-pushnew (org-table-current-column) columns))
4144 (org-table-expand begin end)
4145 ;; Make sure invisible characters in the table are at the right
4146 ;; place since column widths take them into account.
4147 (org-font-lock-ensure begin end)
4148 (org-table--shrink-columns (sort columns #'<) begin end))))
4150 ;;;###autoload
4151 (defun org-table-expand (&optional begin end)
4152 "Expand all columns in the table at point.
4153 Optional arguments BEGIN and END, when non-nil, specify the
4154 beginning and end position of the current table."
4155 (interactive)
4156 (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
4157 (org-with-wide-buffer
4158 (let ((begin (or begin (org-table-begin)))
4159 (end (or end (org-table-end))))
4160 (remove-overlays begin end 'org-overlay-type 'table-column-hide))))
4164 ;;; Formula editing
4166 (defun org-table-fedit-convert-buffer (function)
4167 "Convert all references in this buffer, using FUNCTION."
4168 (let ((origin (copy-marker (line-beginning-position))))
4169 (goto-char (point-min))
4170 (while (not (eobp))
4171 (insert (funcall function (buffer-substring (point) (line-end-position))))
4172 (delete-region (point) (line-end-position))
4173 (forward-line))
4174 (goto-char origin)
4175 (set-marker origin nil)))
4177 (defun org-table-fedit-toggle-ref-type ()
4178 "Convert all references in the buffer from B3 to @3$2 and back."
4179 (interactive)
4180 (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
4181 (org-table-fedit-convert-buffer
4182 (if org-table-buffer-is-an
4183 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
4184 (message "Reference type switched to %s"
4185 (if org-table-buffer-is-an "A1 etc" "@row$column")))
4187 (defun org-table-fedit-ref-up ()
4188 "Shift the reference at point one row/hline up."
4189 (interactive)
4190 (org-table-fedit-shift-reference 'up))
4191 (defun org-table-fedit-ref-down ()
4192 "Shift the reference at point one row/hline down."
4193 (interactive)
4194 (org-table-fedit-shift-reference 'down))
4195 (defun org-table-fedit-ref-left ()
4196 "Shift the reference at point one field to the left."
4197 (interactive)
4198 (org-table-fedit-shift-reference 'left))
4199 (defun org-table-fedit-ref-right ()
4200 "Shift the reference at point one field to the right."
4201 (interactive)
4202 (org-table-fedit-shift-reference 'right))
4204 (defun org-table-fedit-shift-reference (dir)
4205 (cond
4206 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
4207 (if (memq dir '(left right))
4208 (org-rematch-and-replace 1 (eq dir 'left))
4209 (user-error "Cannot shift reference in this direction")))
4210 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
4211 ;; A B3-like reference
4212 (if (memq dir '(up down))
4213 (org-rematch-and-replace 2 (eq dir 'up))
4214 (org-rematch-and-replace 1 (eq dir 'left))))
4215 ((org-in-regexp
4216 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
4217 ;; An internal reference
4218 (if (memq dir '(up down))
4219 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
4220 (org-rematch-and-replace 5 (eq dir 'left))))))
4222 (defun org-rematch-and-replace (n &optional decr hline)
4223 "Re-match the group N, and replace it with the shifted reference."
4224 (or (match-end n) (user-error "Cannot shift reference in this direction"))
4225 (goto-char (match-beginning n))
4226 (and (looking-at (regexp-quote (match-string n)))
4227 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
4228 t t)))
4230 (defun org-table-shift-refpart (ref &optional decr hline)
4231 "Shift a reference part REF.
4232 If DECR is set, decrease the references row/column, else increase.
4233 If HLINE is set, this may be a hline reference, it certainly is not
4234 a translation reference."
4235 (save-match-data
4236 (let* ((sign (string-match "^[-+]" ref)) n)
4238 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
4239 (cond
4240 ((and hline (string-match "^I+" ref))
4241 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
4242 (setq n (+ n (if decr -1 1)))
4243 (if (= n 0) (setq n (+ n (if decr -1 1))))
4244 (if sign
4245 (setq sign (if (< n 0) "-" "+") n (abs n))
4246 (setq n (max 1 n)))
4247 (concat sign (make-string n ?I)))
4249 ((string-match "^[0-9]+" ref)
4250 (setq n (string-to-number (concat sign ref)))
4251 (setq n (+ n (if decr -1 1)))
4252 (if sign
4253 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
4254 (number-to-string (max 1 n))))
4256 ((string-match "^[a-zA-Z]+" ref)
4257 (org-number-to-letters
4258 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
4260 (t (user-error "Cannot shift reference"))))))
4262 (defun org-table-fedit-toggle-coordinates ()
4263 "Toggle the display of coordinates in the referenced table."
4264 (interactive)
4265 (let ((pos (marker-position org-pos)))
4266 (with-current-buffer (marker-buffer org-pos)
4267 (save-excursion
4268 (goto-char pos)
4269 (org-table-toggle-coordinate-overlays)))))
4271 (defun org-table-fedit-finish (&optional arg)
4272 "Parse the buffer for formula definitions and install them.
4273 With prefix ARG, apply the new formulas to the table."
4274 (interactive "P")
4275 (org-table-remove-rectangle-highlight)
4276 (when org-table-use-standard-references
4277 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
4278 (setq org-table-buffer-is-an nil))
4279 (let ((pos org-pos)
4280 (sel-win org-selected-window)
4281 (source org-table--fedit-source)
4282 eql)
4283 (goto-char (point-min))
4284 (while (re-search-forward
4285 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
4286 nil t)
4287 (let ((var (match-string 1))
4288 (form (org-trim (match-string 3))))
4289 (unless (equal form "")
4290 (while (string-match "[ \t]*\n[ \t]*" form)
4291 (setq form (replace-match " " t t form)))
4292 (when (assoc var eql)
4293 (user-error "Double formulas for %s" var))
4294 (push (cons var form) eql))))
4295 (set-window-configuration org-window-configuration)
4296 (select-window sel-win)
4297 (goto-char source)
4298 (org-table-store-formulas eql)
4299 (set-marker pos nil)
4300 (set-marker source nil)
4301 (kill-buffer "*Edit Formulas*")
4302 (if arg
4303 (org-table-recalculate 'all)
4304 (message "New formulas installed - press C-u C-c C-c to apply."))))
4306 (defun org-table-fedit-abort ()
4307 "Abort editing formulas, without installing the changes."
4308 (interactive)
4309 (org-table-remove-rectangle-highlight)
4310 (let ((pos org-pos) (sel-win org-selected-window))
4311 (set-window-configuration org-window-configuration)
4312 (select-window sel-win)
4313 (goto-char pos)
4314 (move-marker pos nil)
4315 (message "Formula editing aborted without installing changes")))
4317 (defun org-table-fedit-lisp-indent ()
4318 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
4319 (interactive)
4320 (let ((pos (point)) beg end ind)
4321 (beginning-of-line 1)
4322 (cond
4323 ((looking-at "[ \t]")
4324 (goto-char pos)
4325 (call-interactively 'lisp-indent-line))
4326 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
4327 ((not (fboundp 'pp-buffer))
4328 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
4329 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
4330 (goto-char (- (match-end 0) 2))
4331 (setq beg (point))
4332 (setq ind (make-string (current-column) ?\ ))
4333 (condition-case nil (forward-sexp 1)
4334 (error
4335 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
4336 (setq end (point))
4337 (save-restriction
4338 (narrow-to-region beg end)
4339 (if (eq last-command this-command)
4340 (progn
4341 (goto-char (point-min))
4342 (setq this-command nil)
4343 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
4344 (replace-match " ")))
4345 (pp-buffer)
4346 (untabify (point-min) (point-max))
4347 (goto-char (1+ (point-min)))
4348 (while (re-search-forward "^." nil t)
4349 (beginning-of-line 1)
4350 (insert ind))
4351 (goto-char (point-max))
4352 (org-delete-backward-char 1)))
4353 (goto-char beg))
4354 (t nil))))
4356 (defvar org-show-positions nil)
4358 (defun org-table-show-reference (&optional local)
4359 "Show the location/value of the $ expression at point.
4360 When LOCAL is non-nil, show references for the table at point."
4361 (interactive)
4362 (org-table-remove-rectangle-highlight)
4363 (when local (org-table-analyze))
4364 (catch 'exit
4365 (let ((pos (if local (point) org-pos))
4366 (face2 'highlight)
4367 (org-inhibit-highlight-removal t)
4368 (win (selected-window))
4369 (org-show-positions nil)
4370 var name e what match dest)
4371 (setq what (cond
4372 ((org-in-regexp "^@[0-9]+[ \t=]")
4373 (setq match (concat (substring (match-string 0) 0 -1)
4374 "$1.."
4375 (substring (match-string 0) 0 -1)
4376 "$100"))
4377 'range)
4378 ((or (org-in-regexp org-table-range-regexp2)
4379 (org-in-regexp org-table-translate-regexp)
4380 (org-in-regexp org-table-range-regexp))
4381 (setq match
4382 (save-match-data
4383 (org-table-convert-refs-to-rc (match-string 0))))
4384 'range)
4385 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
4386 ((org-in-regexp "\\$[0-9]+") 'column)
4387 ((not local) nil)
4388 (t (user-error "No reference at point")))
4389 match (and what (or match (match-string 0))))
4390 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
4391 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
4392 'secondary-selection))
4393 (add-hook 'before-change-functions
4394 #'org-table-remove-rectangle-highlight)
4395 (when (eq what 'name) (setq var (substring match 1)))
4396 (when (eq what 'range)
4397 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
4398 (setq match (org-table-formula-substitute-names match)))
4399 (unless local
4400 (save-excursion
4401 (end-of-line)
4402 (re-search-backward "^\\S-" nil t)
4403 (beginning-of-line)
4404 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4405 \\([0-9]+\\|&\\)\\) *=")
4406 (setq dest
4407 (save-match-data
4408 (org-table-convert-refs-to-rc (match-string 1))))
4409 (org-table-add-rectangle-overlay
4410 (match-beginning 1) (match-end 1) face2))))
4411 (if (and (markerp pos) (marker-buffer pos))
4412 (if (get-buffer-window (marker-buffer pos))
4413 (select-window (get-buffer-window (marker-buffer pos)))
4414 (org-switch-to-buffer-other-window (get-buffer-window
4415 (marker-buffer pos)))))
4416 (goto-char pos)
4417 (org-table-force-dataline)
4418 (let ((table-start
4419 (if local org-table-current-begin-pos (org-table-begin))))
4420 (when dest
4421 (setq name (substring dest 1))
4422 (cond
4423 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
4424 (org-table-goto-field dest))
4425 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4426 dest)
4427 (org-table-goto-field dest))
4428 (t (org-table-goto-column (string-to-number name))))
4429 (move-marker pos (point))
4430 (org-table-highlight-rectangle nil nil face2))
4431 (cond
4432 ((equal dest match))
4433 ((not match))
4434 ((eq what 'range)
4435 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
4436 ((setq e (assoc var org-table-named-field-locations))
4437 (org-table-goto-field var)
4438 (org-table-highlight-rectangle)
4439 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
4440 ((setq e (assoc var org-table-column-names))
4441 (org-table-goto-column (string-to-number (cdr e)))
4442 (org-table-highlight-rectangle)
4443 (goto-char table-start)
4444 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
4445 (org-table-end) t)
4446 (progn
4447 (goto-char (match-beginning 1))
4448 (org-table-highlight-rectangle)
4449 (message "Named column (column %s)" (cdr e)))
4450 (user-error "Column name not found")))
4451 ((eq what 'column)
4452 ;; Column number.
4453 (org-table-goto-column (string-to-number (substring match 1)))
4454 (org-table-highlight-rectangle)
4455 (message "Column %s" (substring match 1)))
4456 ((setq e (assoc var org-table-local-parameters))
4457 (goto-char table-start)
4458 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
4459 (progn
4460 (goto-char (match-beginning 1))
4461 (org-table-highlight-rectangle)
4462 (message "Local parameter."))
4463 (user-error "Parameter not found")))
4464 ((not var) (user-error "No reference at point"))
4465 ((setq e (assoc var org-table-formula-constants-local))
4466 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4467 var (cdr e)))
4468 ((setq e (assoc var org-table-formula-constants))
4469 (message "Constant: $%s=%s in `org-table-formula-constants'."
4470 var (cdr e)))
4471 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4472 (message "Constant: $%s=%s, from `constants.el'%s."
4473 var e (format " (%s units)" constants-unit-system)))
4474 (t (user-error "Undefined name $%s" var)))
4475 (goto-char pos)
4476 (when (and org-show-positions
4477 (not (memq this-command '(org-table-fedit-scroll
4478 org-table-fedit-scroll-down))))
4479 (push pos org-show-positions)
4480 (push table-start org-show-positions)
4481 (let ((min (apply 'min org-show-positions))
4482 (max (apply 'max org-show-positions)))
4483 (set-window-start (selected-window) min)
4484 (goto-char max)
4485 (or (pos-visible-in-window-p max)
4486 (set-window-start (selected-window) max)))))
4487 (select-window win))))
4489 (defun org-table-force-dataline ()
4490 "Move point to the closest data line in a table.
4491 Raise an error if the table contains no data line. Preserve
4492 column when moving point."
4493 (unless (org-match-line org-table-dataline-regexp)
4494 (let* ((re org-table-dataline-regexp)
4495 (column (current-column))
4496 (p1 (save-excursion (re-search-forward re (org-table-end) t)))
4497 (p2 (save-excursion (re-search-backward re (org-table-begin) t))))
4498 (cond ((and p1 p2)
4499 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4501 p2)))
4502 ((or p1 p2) (goto-char (or p1 p2)))
4503 (t (user-error "No table data line around here")))
4504 (org-move-to-column column))))
4506 (defun org-table-fedit-line-up ()
4507 "Move cursor one line up in the window showing the table."
4508 (interactive)
4509 (org-table-fedit-move 'previous-line))
4511 (defun org-table-fedit-line-down ()
4512 "Move cursor one line down in the window showing the table."
4513 (interactive)
4514 (org-table-fedit-move 'next-line))
4516 (defun org-table-fedit-move (command)
4517 "Move the cursor in the window showing the table.
4518 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4519 (let ((org-table-allow-automatic-line-recalculation nil)
4520 (pos org-pos) (win (selected-window)) p)
4521 (select-window (get-buffer-window (marker-buffer org-pos)))
4522 (setq p (point))
4523 (call-interactively command)
4524 (while (and (org-at-table-p)
4525 (org-at-table-hline-p))
4526 (call-interactively command))
4527 (or (org-at-table-p) (goto-char p))
4528 (move-marker pos (point))
4529 (select-window win)))
4531 (defun org-table-fedit-scroll (N)
4532 (interactive "p")
4533 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4534 (scroll-other-window N)))
4536 (defun org-table-fedit-scroll-down (N)
4537 (interactive "p")
4538 (org-table-fedit-scroll (- N)))
4540 (defvar org-table-rectangle-overlays nil)
4542 (defun org-table-add-rectangle-overlay (beg end &optional face)
4543 "Add a new overlay."
4544 (let ((ov (make-overlay beg end)))
4545 (overlay-put ov 'face (or face 'secondary-selection))
4546 (push ov org-table-rectangle-overlays)))
4548 (defun org-table-highlight-rectangle (&optional beg end face)
4549 "Highlight rectangular region in a table.
4550 When buffer positions BEG and END are provided, use them to
4551 delimit the region to highlight. Otherwise, refer to point. Use
4552 FACE, when non-nil, for the highlight."
4553 (let* ((beg (or beg (point)))
4554 (end (or end (point)))
4555 (b (min beg end))
4556 (e (max beg end))
4557 (start-coordinates
4558 (save-excursion
4559 (goto-char b)
4560 (cons (line-beginning-position) (org-table-current-column))))
4561 (end-coordinates
4562 (save-excursion
4563 (goto-char e)
4564 (cons (line-beginning-position) (org-table-current-column)))))
4565 (when (boundp 'org-show-positions)
4566 (setq org-show-positions (cons b (cons e org-show-positions))))
4567 (goto-char (car start-coordinates))
4568 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4569 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4570 (last-row (car end-coordinates)))
4571 (while (<= (point) last-row)
4572 (when (looking-at org-table-dataline-regexp)
4573 (org-table-goto-column column-start)
4574 (skip-chars-backward "^|\n")
4575 (let ((p (point)))
4576 (org-table-goto-column column-end)
4577 (skip-chars-forward "^|\n")
4578 (org-table-add-rectangle-overlay p (point) face)))
4579 (forward-line)))
4580 (goto-char (car start-coordinates)))
4581 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4583 (defun org-table-remove-rectangle-highlight (&rest _ignore)
4584 "Remove the rectangle overlays."
4585 (unless org-inhibit-highlight-removal
4586 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4587 (mapc 'delete-overlay org-table-rectangle-overlays)
4588 (setq org-table-rectangle-overlays nil)))
4590 (defvar-local org-table-coordinate-overlays nil
4591 "Collects the coordinate grid overlays, so that they can be removed.")
4593 (defun org-table-overlay-coordinates ()
4594 "Add overlays to the table at point, to show row/column coordinates."
4595 (interactive)
4596 (mapc 'delete-overlay org-table-coordinate-overlays)
4597 (setq org-table-coordinate-overlays nil)
4598 (save-excursion
4599 (let ((id 0) (ih 0) hline eol str ov)
4600 (goto-char (org-table-begin))
4601 (while (org-at-table-p)
4602 (setq eol (point-at-eol))
4603 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4604 (push ov org-table-coordinate-overlays)
4605 (setq hline (looking-at org-table-hline-regexp))
4606 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4607 (format "%4d" (setq id (1+ id)))))
4608 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4609 (when hline
4610 (let ((ic 0))
4611 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4612 (cl-incf ic)
4613 (let* ((beg (1+ (match-beginning 0)))
4614 (s1 (format "$%d" ic))
4615 (s2 (org-number-to-letters ic))
4616 (str (if (eq t org-table-use-standard-references) s2 s1))
4617 (ov (make-overlay beg (+ beg (length str)))))
4618 (push ov org-table-coordinate-overlays)
4619 (org-overlay-display ov str 'org-special-keyword 'evaporate)))))
4620 (forward-line)))))
4622 ;;;###autoload
4623 (defun org-table-toggle-coordinate-overlays ()
4624 "Toggle the display of Row/Column numbers in tables."
4625 (interactive)
4626 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4627 (message "Tables Row/Column numbers display turned %s"
4628 (if org-table-overlay-coordinates "on" "off"))
4629 (when (and (org-at-table-p) org-table-overlay-coordinates)
4630 (org-table-align))
4631 (unless org-table-overlay-coordinates
4632 (mapc 'delete-overlay org-table-coordinate-overlays)
4633 (setq org-table-coordinate-overlays nil)))
4635 ;;;###autoload
4636 (defun org-table-toggle-formula-debugger ()
4637 "Toggle the formula debugger in tables."
4638 (interactive)
4639 (setq org-table-formula-debug (not org-table-formula-debug))
4640 (message "Formula debugging has been turned %s"
4641 (if org-table-formula-debug "on" "off")))
4643 ;;; The orgtbl minor mode
4645 ;; Define a minor mode which can be used in other modes in order to
4646 ;; integrate the Org table editor.
4648 ;; This is really a hack, because the Org table editor uses several
4649 ;; keys which normally belong to the major mode, for example the TAB
4650 ;; and RET keys. Here is how it works: The minor mode defines all the
4651 ;; keys necessary to operate the table editor, but wraps the commands
4652 ;; into a function which tests if the cursor is currently inside
4653 ;; a table. If that is the case, the table editor command is
4654 ;; executed. However, when any of those keys is used outside a table,
4655 ;; the function uses `key-binding' to look up if the key has an
4656 ;; associated command in another currently active keymap (minor modes,
4657 ;; major mode, global), and executes that command. There might be
4658 ;; problems if any of the keys used by the table editor is otherwise
4659 ;; used as a prefix key.
4661 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4662 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4663 ;; addresses this by checking explicitly for both bindings.
4665 ;; The optimized version (see variable `orgtbl-optimized') takes over
4666 ;; all keys which are bound to `self-insert-command' in the *global map*.
4667 ;; Some modes bind other commands to simple characters, for example
4668 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4669 ;; active, this binding is ignored inside tables and replaced with a
4670 ;; modified self-insert.
4673 (defvar orgtbl-mode-map (make-keymap)
4674 "Keymap for `orgtbl-mode'.")
4676 (defvar org-old-auto-fill-inhibit-regexp nil
4677 "Local variable used by `orgtbl-mode'.")
4679 (defconst orgtbl-line-start-regexp
4680 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4681 "Matches a line belonging to an orgtbl.")
4683 (defconst orgtbl-extra-font-lock-keywords
4684 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4685 0 (quote 'org-table) 'prepend))
4686 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4688 ;; Install it as a minor mode.
4689 (put 'orgtbl-mode :included t)
4690 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4692 ;;;###autoload
4693 (define-minor-mode orgtbl-mode
4694 "The Org mode table editor as a minor mode for use in other modes."
4695 :lighter " OrgTbl" :keymap orgtbl-mode-map
4696 (org-load-modules-maybe)
4697 (cond
4698 ((derived-mode-p 'org-mode)
4699 ;; Exit without error, in case some hook functions calls this by
4700 ;; accident in Org mode.
4701 (message "Orgtbl mode is not useful in Org mode, command ignored"))
4702 (orgtbl-mode
4703 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4704 ;; Make sure we are first in minor-mode-map-alist
4705 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4706 ;; FIXME: maybe it should use emulation-mode-map-alists?
4707 (and c (setq minor-mode-map-alist
4708 (cons c (delq c minor-mode-map-alist)))))
4709 (setq-local org-table-may-need-update t)
4710 (add-hook 'before-change-functions 'org-before-change-function
4711 nil 'local)
4712 (setq-local org-old-auto-fill-inhibit-regexp
4713 auto-fill-inhibit-regexp)
4714 (setq-local auto-fill-inhibit-regexp
4715 (if auto-fill-inhibit-regexp
4716 (concat orgtbl-line-start-regexp "\\|"
4717 auto-fill-inhibit-regexp)
4718 orgtbl-line-start-regexp))
4719 (when (fboundp 'font-lock-add-keywords)
4720 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4721 (org-restart-font-lock))
4722 (easy-menu-add orgtbl-mode-menu))
4724 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4725 (remove-hook 'before-change-functions 'org-before-change-function t)
4726 (when (fboundp 'font-lock-remove-keywords)
4727 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4728 (org-restart-font-lock))
4729 (easy-menu-remove orgtbl-mode-menu)
4730 (force-mode-line-update 'all))))
4732 (defun orgtbl-make-binding (fun n &rest keys)
4733 "Create a function for binding in the table minor mode.
4734 FUN is the command to call inside a table. N is used to create a unique
4735 command name. KEYS are keys that should be checked in for a command
4736 to execute outside of tables."
4737 (eval
4738 (list 'defun
4739 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4740 '(arg)
4741 (concat "In tables, run `" (symbol-name fun) "'.\n"
4742 "Outside of tables, run the binding of `"
4743 (mapconcat #'key-description keys "' or `")
4744 "'.")
4745 '(interactive "p")
4746 (list 'if
4747 '(org-at-table-p)
4748 (list 'call-interactively (list 'quote fun))
4749 (list 'let '(orgtbl-mode)
4750 (list 'call-interactively
4751 (append '(or)
4752 (mapcar (lambda (k)
4753 (list 'key-binding k))
4754 keys)
4755 '('orgtbl-error))))))))
4757 (defun orgtbl-error ()
4758 "Error when there is no default binding for a table key."
4759 (interactive)
4760 (user-error "This key has no function outside tables"))
4762 (defun orgtbl-setup ()
4763 "Setup orgtbl keymaps."
4764 (let ((nfunc 0)
4765 (bindings
4766 '(([(meta shift left)] org-table-delete-column)
4767 ([(meta left)] org-table-move-column-left)
4768 ([(meta right)] org-table-move-column-right)
4769 ([(meta shift right)] org-table-insert-column)
4770 ([(meta shift up)] org-table-kill-row)
4771 ([(meta shift down)] org-table-insert-row)
4772 ([(meta up)] org-table-move-row-up)
4773 ([(meta down)] org-table-move-row-down)
4774 ("\C-c\C-w" org-table-cut-region)
4775 ("\C-c\M-w" org-table-copy-region)
4776 ("\C-c\C-y" org-table-paste-rectangle)
4777 ("\C-c\C-w" org-table-wrap-region)
4778 ("\C-c-" org-table-insert-hline)
4779 ("\C-c}" org-table-toggle-coordinate-overlays)
4780 ("\C-c{" org-table-toggle-formula-debugger)
4781 ("\C-m" org-table-next-row)
4782 ([(shift return)] org-table-copy-down)
4783 ("\C-c?" org-table-field-info)
4784 ("\C-c " org-table-blank-field)
4785 ("\C-c+" org-table-sum)
4786 ("\C-c=" org-table-eval-formula)
4787 ("\C-c'" org-table-edit-formulas)
4788 ("\C-c`" org-table-edit-field)
4789 ("\C-c*" org-table-recalculate)
4790 ("\C-c^" org-table-sort-lines)
4791 ("\M-a" org-table-beginning-of-field)
4792 ("\M-e" org-table-end-of-field)
4793 ([(control ?#)] org-table-rotate-recalc-marks)))
4794 elt key fun cmd)
4795 (while (setq elt (pop bindings))
4796 (setq nfunc (1+ nfunc))
4797 (setq key (org-key (car elt))
4798 fun (nth 1 elt)
4799 cmd (orgtbl-make-binding fun nfunc key))
4800 (org-defkey orgtbl-mode-map key cmd))
4802 ;; Special treatment needed for TAB, RET and DEL
4803 (org-defkey orgtbl-mode-map [(return)]
4804 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4805 (org-defkey orgtbl-mode-map "\C-m"
4806 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4807 (org-defkey orgtbl-mode-map [(tab)]
4808 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4809 (org-defkey orgtbl-mode-map "\C-i"
4810 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4811 (org-defkey orgtbl-mode-map [(shift tab)]
4812 (orgtbl-make-binding 'org-table-previous-field 104
4813 [(shift tab)] [(tab)] "\C-i"))
4814 (org-defkey orgtbl-mode-map [backspace]
4815 (orgtbl-make-binding 'org-delete-backward-char 109
4816 [backspace] (kbd "DEL")))
4818 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4819 (orgtbl-make-binding 'org-table-previous-field 107
4820 [S-iso-lefttab] [backtab] [(shift tab)]
4821 [(tab)] "\C-i"))
4823 (org-defkey orgtbl-mode-map [backtab]
4824 (orgtbl-make-binding 'org-table-previous-field 108
4825 [backtab] [S-iso-lefttab] [(shift tab)]
4826 [(tab)] "\C-i"))
4828 (org-defkey orgtbl-mode-map "\M-\C-m"
4829 (orgtbl-make-binding 'org-table-wrap-region 105
4830 "\M-\C-m" [(meta return)]))
4831 (org-defkey orgtbl-mode-map [(meta return)]
4832 (orgtbl-make-binding 'org-table-wrap-region 106
4833 [(meta return)] "\M-\C-m"))
4835 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4836 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4838 (when orgtbl-optimized
4839 ;; If the user wants maximum table support, we need to hijack
4840 ;; some standard editing functions
4841 (org-remap orgtbl-mode-map
4842 'self-insert-command 'orgtbl-self-insert-command
4843 'delete-char 'org-delete-char
4844 'delete-backward-char 'org-delete-backward-char)
4845 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4846 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4847 '("OrgTbl"
4848 ["Create or convert" org-table-create-or-convert-from-region
4849 :active (not (org-at-table-p)) :keys "C-c |" ]
4850 "--"
4851 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4852 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4853 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4854 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4855 "--"
4856 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4857 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4858 ["Copy Field from Above"
4859 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4860 "--"
4861 ("Column"
4862 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4863 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4864 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4865 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4866 ("Row"
4867 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4868 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4869 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4870 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4871 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4872 "--"
4873 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4874 ("Rectangle"
4875 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4876 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4877 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4878 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4879 "--"
4880 ("Radio tables"
4881 ["Insert table template" orgtbl-insert-radio-table
4882 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
4883 ["Comment/uncomment table" orgtbl-toggle-comment t])
4884 "--"
4885 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4886 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4887 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4888 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4889 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4890 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4891 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4892 ["Sum Column/Rectangle" org-table-sum
4893 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4894 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4895 ["Debug Formulas"
4896 org-table-toggle-formula-debugger :active (org-at-table-p)
4897 :keys "C-c {"
4898 :style toggle :selected org-table-formula-debug]
4899 ["Show Col/Row Numbers"
4900 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4901 :keys "C-c }"
4902 :style toggle :selected org-table-overlay-coordinates]
4903 "--"
4904 ("Plot"
4905 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4906 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4909 (defun orgtbl-ctrl-c-ctrl-c (arg)
4910 "If the cursor is inside a table, realign the table.
4911 If it is a table to be sent away to a receiver, do it.
4912 With prefix arg, also recompute table."
4913 (interactive "P")
4914 (let ((case-fold-search t) (pos (point)) action)
4915 (save-excursion
4916 (beginning-of-line 1)
4917 (setq action (cond
4918 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4919 ((looking-at "[ \t]*|") pos)
4920 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4921 (cond
4922 ((integerp action)
4923 (goto-char action)
4924 (org-table-maybe-eval-formula)
4925 (if arg
4926 (call-interactively 'org-table-recalculate)
4927 (org-table-maybe-recalculate-line))
4928 (call-interactively 'org-table-align)
4929 (when (orgtbl-send-table 'maybe)
4930 (run-hooks 'orgtbl-after-send-table-hook)))
4931 ((eq action 'recalc)
4932 (save-excursion
4933 (beginning-of-line 1)
4934 (skip-chars-backward " \r\n\t")
4935 (if (org-at-table-p)
4936 (org-call-with-arg 'org-table-recalculate t))))
4937 (t (let (orgtbl-mode)
4938 (call-interactively (key-binding "\C-c\C-c")))))))
4940 (defun orgtbl-create-or-convert-from-region (_arg)
4941 "Create table or convert region to table, if no conflicting binding.
4942 This installs the table binding `C-c |', but only if there is no
4943 conflicting binding to this key outside orgtbl-mode."
4944 (interactive "P")
4945 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4946 (if cmd
4947 (call-interactively cmd)
4948 (call-interactively 'org-table-create-or-convert-from-region))))
4950 (defun orgtbl-tab (arg)
4951 "Justification and field motion for `orgtbl-mode'."
4952 (interactive "P")
4953 (if arg (org-table-edit-field t)
4954 (org-table-justify-field-maybe)
4955 (org-table-next-field)))
4957 (defun orgtbl-ret ()
4958 "Justification and field motion for `orgtbl-mode'."
4959 (interactive)
4960 (if (bobp)
4961 (newline)
4962 (org-table-justify-field-maybe)
4963 (org-table-next-row)))
4965 (defun orgtbl-self-insert-command (N)
4966 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4967 If the cursor is in a table looking at whitespace, the whitespace is
4968 overwritten, and the table is not marked as requiring realignment."
4969 (interactive "p")
4970 (if (and (org-at-table-p)
4972 (and org-table-auto-blank-field
4973 (member last-command
4974 '(orgtbl-hijacker-command-100
4975 orgtbl-hijacker-command-101
4976 orgtbl-hijacker-command-102
4977 orgtbl-hijacker-command-103
4978 orgtbl-hijacker-command-104
4979 orgtbl-hijacker-command-105
4980 yas/expand))
4981 (org-table-blank-field))
4983 (eq N 1)
4984 (looking-at "[^|\n]* \\( \\)|"))
4985 (let (org-table-may-need-update)
4986 (delete-region (match-beginning 1) (match-end 1))
4987 (self-insert-command N))
4988 (setq org-table-may-need-update t)
4989 (let* (orgtbl-mode
4991 (cmd (or (key-binding
4992 (or (and (listp function-key-map)
4993 (setq a (assoc last-input-event function-key-map))
4994 (cdr a))
4995 (vector last-input-event)))
4996 'self-insert-command)))
4997 (call-interactively cmd)
4998 (if (and org-self-insert-cluster-for-undo
4999 (eq cmd 'self-insert-command))
5000 (if (not (eq last-command 'orgtbl-self-insert-command))
5001 (setq org-self-insert-command-undo-counter 1)
5002 (if (>= org-self-insert-command-undo-counter 20)
5003 (setq org-self-insert-command-undo-counter 1)
5004 (and (> org-self-insert-command-undo-counter 0)
5005 buffer-undo-list
5006 (not (cadr buffer-undo-list)) ; remove nil entry
5007 (setcdr buffer-undo-list (cddr buffer-undo-list)))
5008 (setq org-self-insert-command-undo-counter
5009 (1+ org-self-insert-command-undo-counter))))))))
5011 ;;;###autoload
5012 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
5013 "Regular expression matching exponentials as produced by calc.")
5015 (defun orgtbl-gather-send-defs ()
5016 "Gather a plist of :name, :transform, :params for each destination before
5017 a radio table."
5018 (save-excursion
5019 (goto-char (org-table-begin))
5020 (let (rtn)
5021 (beginning-of-line 0)
5022 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
5023 (let ((name (org-no-properties (match-string 1)))
5024 (transform (intern (match-string 2)))
5025 (params (if (match-end 3)
5026 (read (concat "(" (match-string 3) ")")))))
5027 (push (list :name name :transform transform :params params)
5028 rtn)
5029 (beginning-of-line 0)))
5030 rtn)))
5032 (defun orgtbl-send-replace-tbl (name text)
5033 "Find and replace table NAME with TEXT."
5034 (save-excursion
5035 (goto-char (point-min))
5036 (let* ((location-flag nil)
5037 (name (regexp-quote name))
5038 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
5039 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
5040 (while (re-search-forward begin-re nil t)
5041 (unless location-flag (setq location-flag t))
5042 (let ((beg (line-beginning-position 2)))
5043 (unless (re-search-forward end-re nil t)
5044 (user-error "Cannot find end of receiver location at %d" beg))
5045 (beginning-of-line)
5046 (delete-region beg (point))
5047 (insert text "\n")))
5048 (unless location-flag
5049 (user-error "No valid receiver location found in the buffer")))))
5051 ;;;###autoload
5052 (defun org-table-to-lisp (&optional txt)
5053 "Convert the table at point to a Lisp structure.
5054 The structure will be a list. Each item is either the symbol `hline'
5055 for a horizontal separator line, or a list of field values as strings.
5056 The table is taken from the parameter TXT, or from the buffer at point."
5057 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
5058 (let ((txt (or txt
5059 (buffer-substring-no-properties (org-table-begin)
5060 (org-table-end)))))
5061 (mapcar (lambda (x)
5062 (if (string-match org-table-hline-regexp x) 'hline
5063 (org-split-string (org-trim x) "\\s-*|\\s-*")))
5064 (org-split-string txt "[ \t]*\n[ \t]*"))))
5066 (defun orgtbl-send-table (&optional maybe)
5067 "Send a transformed version of table at point to the receiver position.
5068 With argument MAYBE, fail quietly if no transformation is defined
5069 for this table."
5070 (interactive)
5071 (catch 'exit
5072 (unless (org-at-table-p) (user-error "Not at a table"))
5073 ;; when non-interactive, we assume align has just happened.
5074 (when (called-interactively-p 'any) (org-table-align))
5075 (let ((dests (orgtbl-gather-send-defs))
5076 (table (org-table-to-lisp
5077 (buffer-substring-no-properties (org-table-begin)
5078 (org-table-end))))
5079 (ntbl 0))
5080 (unless dests
5081 (if maybe (throw 'exit nil)
5082 (user-error "Don't know how to transform this table")))
5083 (dolist (dest dests)
5084 (let ((name (plist-get dest :name))
5085 (transform (plist-get dest :transform))
5086 (params (plist-get dest :params)))
5087 (unless (fboundp transform)
5088 (user-error "No such transformation function %s" transform))
5089 (orgtbl-send-replace-tbl name (funcall transform table params)))
5090 (cl-incf ntbl))
5091 (message "Table converted and installed at %d receiver location%s"
5092 ntbl (if (> ntbl 1) "s" ""))
5093 (and (> ntbl 0) ntbl))))
5095 (defun org-remove-by-index (list indices &optional i0)
5096 "Remove the elements in LIST with indices in INDICES.
5097 First element has index 0, or I0 if given."
5098 (if (not indices)
5099 list
5100 (if (integerp indices) (setq indices (list indices)))
5101 (setq i0 (1- (or i0 0)))
5102 (delq :rm (mapcar (lambda (x)
5103 (setq i0 (1+ i0))
5104 (if (memq i0 indices) :rm x))
5105 list))))
5107 (defun orgtbl-toggle-comment ()
5108 "Comment or uncomment the orgtbl at point."
5109 (interactive)
5110 (let* ((case-fold-search t)
5111 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
5112 (re2 (concat "^" orgtbl-line-start-regexp))
5113 (commented (save-excursion (beginning-of-line 1)
5114 (cond ((looking-at re1) t)
5115 ((looking-at re2) nil)
5116 (t (user-error "Not at an org table")))))
5117 (re (if commented re1 re2))
5118 beg end)
5119 (save-excursion
5120 (beginning-of-line 1)
5121 (while (looking-at re) (beginning-of-line 0))
5122 (beginning-of-line 2)
5123 (setq beg (point))
5124 (while (looking-at re) (beginning-of-line 2))
5125 (setq end (point)))
5126 (comment-region beg end (if commented '(4) nil))))
5128 (defun orgtbl-insert-radio-table ()
5129 "Insert a radio table template appropriate for this major mode."
5130 (interactive)
5131 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
5132 (txt (nth 1 e))
5133 name pos)
5134 (unless e (user-error "No radio table setup defined for %s" major-mode))
5135 (setq name (read-string "Table name: "))
5136 (while (string-match "%n" txt)
5137 (setq txt (replace-match name t t txt)))
5138 (or (bolp) (insert "\n"))
5139 (setq pos (point))
5140 (insert txt)
5141 (goto-char pos)))
5143 ;;;###autoload
5144 (defun orgtbl-to-generic (table params)
5145 "Convert the orgtbl-mode TABLE to some other format.
5147 This generic routine can be used for many standard cases.
5149 TABLE is a list, each entry either the symbol `hline' for
5150 a horizontal separator line, or a list of fields for that
5151 line. PARAMS is a property list of parameters that can
5152 influence the conversion.
5154 Valid parameters are:
5156 :backend, :raw
5158 Export back-end used as a basis to transcode elements of the
5159 table, when no specific parameter applies to it. It is also
5160 used to translate cells contents. You can prevent this by
5161 setting :raw property to a non-nil value.
5163 :splice
5165 When non-nil, only convert rows, not the table itself. This is
5166 equivalent to setting to the empty string both :tstart
5167 and :tend, which see.
5169 :skip
5171 When set to an integer N, skip the first N lines of the table.
5172 Horizontal separation lines do count for this parameter!
5174 :skipcols
5176 List of columns that should be skipped. If the table has
5177 a column with calculation marks, that column is automatically
5178 discarded beforehand.
5180 :hline
5182 String to be inserted on horizontal separation lines. May be
5183 nil to ignore these lines altogether.
5185 :sep
5187 Separator between two fields, as a string.
5189 Each in the following group may be either a string or a function
5190 of no arguments returning a string:
5192 :tstart, :tend
5194 Strings to start and end the table. Ignored when :splice is t.
5196 :lstart, :lend
5198 Strings to start and end a new table line.
5200 :llstart, :llend
5202 Strings to start and end the last table line. Default,
5203 respectively, to :lstart and :lend.
5205 Each in the following group may be a string or a function of one
5206 argument (either the cells in the current row, as a list of
5207 strings, or the current cell) returning a string:
5209 :lfmt
5211 Format string for an entire row, with enough %s to capture all
5212 fields. When non-nil, :lstart, :lend, and :sep are ignored.
5214 :llfmt
5216 Format for the entire last line, defaults to :lfmt.
5218 :fmt
5220 A format to be used to wrap the field, should contain %s for
5221 the original field value. For example, to wrap everything in
5222 dollars, you could use :fmt \"$%s$\". This may also be
5223 a property list with column numbers and format strings, or
5224 functions, e.g.,
5226 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
5228 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
5230 Same as above, specific for the header lines in the table.
5231 All lines before the first hline are treated as header. If
5232 any of these is not present, the data line value is used.
5234 This may be either a string or a function of two arguments:
5236 :efmt
5238 Use this format to print numbers with exponential. The format
5239 should have %s twice for inserting mantissa and exponent, for
5240 example \"%s\\\\times10^{%s}\". This may also be a property
5241 list with column numbers and format strings or functions.
5242 :fmt will still be applied after :efmt."
5243 ;; Make sure `org-export-create-backend' is available.
5244 (require 'ox)
5245 (let* ((backend (plist-get params :backend))
5246 (custom-backend
5247 ;; Build a custom back-end according to PARAMS. Before
5248 ;; defining a translator, check if there is anything to do.
5249 ;; When there isn't, let BACKEND handle the element.
5250 (org-export-create-backend
5251 :parent (or backend 'org)
5252 :transcoders
5253 `((table . ,(org-table--to-generic-table params))
5254 (table-row . ,(org-table--to-generic-row params))
5255 (table-cell . ,(org-table--to-generic-cell params))
5256 ;; Macros are not going to be expanded. However, no
5257 ;; regular back-end has a transcoder for them. We
5258 ;; provide one so they are not ignored, but displayed
5259 ;; as-is instead.
5260 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
5261 data info)
5262 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
5263 ;; Initialize communication channel in INFO.
5264 (with-temp-buffer
5265 (let ((org-inhibit-startup t)) (org-mode))
5266 (let ((standard-output (current-buffer))
5267 (org-element-use-cache nil))
5268 (dolist (e table)
5269 (cond ((eq e 'hline) (princ "|--\n"))
5270 ((consp e)
5271 (princ "| ") (dolist (c e) (princ c) (princ " |"))
5272 (princ "\n")))))
5273 ;; Add back-end specific filters, but not user-defined ones. In
5274 ;; particular, make sure to call parse-tree filters on the
5275 ;; table.
5276 (setq info
5277 (let ((org-export-filters-alist nil))
5278 (org-export-install-filters
5279 (org-combine-plists
5280 (org-export-get-environment backend nil params)
5281 `(:back-end ,(org-export-get-backend backend))))))
5282 (setq data
5283 (org-export-filter-apply-functions
5284 (plist-get info :filter-parse-tree)
5285 (org-element-map (org-element-parse-buffer) 'table
5286 #'identity nil t)
5287 info)))
5288 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
5289 (user-error "Unknown :backend value"))
5290 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
5291 ;; Handle :skip parameter.
5292 (let ((skip (plist-get info :skip)))
5293 (when skip
5294 (unless (wholenump skip) (user-error "Wrong :skip value"))
5295 (let ((n 0))
5296 (org-element-map data 'table-row
5297 (lambda (row)
5298 (if (>= n skip) t
5299 (org-element-extract-element row)
5300 (cl-incf n)
5301 nil))
5302 nil t))))
5303 ;; Handle :skipcols parameter.
5304 (let ((skipcols (plist-get info :skipcols)))
5305 (when skipcols
5306 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
5307 (org-element-map data 'table
5308 (lambda (table)
5309 (let ((specialp (org-export-table-has-special-column-p table)))
5310 (dolist (row (org-element-contents table))
5311 (when (eq (org-element-property :type row) 'standard)
5312 (let ((c 1))
5313 (dolist (cell (nthcdr (if specialp 1 0)
5314 (org-element-contents row)))
5315 (when (memq c skipcols)
5316 (org-element-extract-element cell))
5317 (cl-incf c))))))))))
5318 ;; Since we are going to export using a low-level mechanism,
5319 ;; ignore special column and special rows manually.
5320 (let ((special? (org-export-table-has-special-column-p data))
5321 ignore)
5322 (org-element-map data (if special? '(table-cell table-row) 'table-row)
5323 (lambda (datum)
5324 (when (if (eq (org-element-type datum) 'table-row)
5325 (org-export-table-row-is-special-p datum nil)
5326 (org-export-first-sibling-p datum nil))
5327 (push datum ignore))))
5328 (setq info (plist-put info :ignore-list ignore)))
5329 ;; We use a low-level mechanism to export DATA so as to skip all
5330 ;; usual pre-processing and post-processing, i.e., hooks, Babel
5331 ;; code evaluation, include keywords and macro expansion. Only
5332 ;; back-end specific filters are retained.
5333 (let ((output (org-export-data-with-backend data custom-backend info)))
5334 ;; Remove final newline.
5335 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
5337 (defun org-table--generic-apply (value name &optional with-cons &rest args)
5338 (cond ((null value) nil)
5339 ((functionp value) `(funcall ',value ,@args))
5340 ((stringp value)
5341 (cond ((consp (car args)) `(apply #'format ,value ,@args))
5342 (args `(format ,value ,@args))
5343 (t value)))
5344 ((and with-cons (consp value))
5345 `(let ((val (cadr (memq column ',value))))
5346 (cond ((null val) contents)
5347 ((stringp val) (format val ,@args))
5348 ((functionp val) (funcall val ,@args))
5349 (t (user-error "Wrong %s value" ,name)))))
5350 (t (user-error "Wrong %s value" name))))
5352 (defun org-table--to-generic-table (params)
5353 "Return custom table transcoder according to PARAMS.
5354 PARAMS is a plist. See `orgtbl-to-generic' for more
5355 information."
5356 (let ((backend (plist-get params :backend))
5357 (splice (plist-get params :splice))
5358 (tstart (plist-get params :tstart))
5359 (tend (plist-get params :tend)))
5360 `(lambda (table contents info)
5361 (concat
5362 ,(and tstart (not splice)
5363 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
5364 ,(if (or (not backend) tstart tend splice) 'contents
5365 `(org-export-with-backend ',backend table contents info))
5366 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
5368 (defun org-table--to-generic-row (params)
5369 "Return custom table row transcoder according to PARAMS.
5370 PARAMS is a plist. See `orgtbl-to-generic' for more
5371 information."
5372 (let* ((backend (plist-get params :backend))
5373 (lstart (plist-get params :lstart))
5374 (llstart (plist-get params :llstart))
5375 (hlstart (plist-get params :hlstart))
5376 (hllstart (plist-get params :hllstart))
5377 (lend (plist-get params :lend))
5378 (llend (plist-get params :llend))
5379 (hlend (plist-get params :hlend))
5380 (hllend (plist-get params :hllend))
5381 (lfmt (plist-get params :lfmt))
5382 (llfmt (plist-get params :llfmt))
5383 (hlfmt (plist-get params :hlfmt))
5384 (hllfmt (plist-get params :hllfmt)))
5385 `(lambda (row contents info)
5386 (if (eq (org-element-property :type row) 'rule)
5387 ,(cond
5388 ((plist-member params :hline)
5389 (org-table--generic-apply (plist-get params :hline) ":hline"))
5390 (backend `(org-export-with-backend ',backend row nil info)))
5391 (let ((headerp ,(and (or hlfmt hlstart hlend)
5392 '(org-export-table-row-in-header-p row info)))
5393 (last-header-p
5394 ,(and (or hllfmt hllstart hllend)
5395 '(org-export-table-row-ends-header-p row info)))
5396 (lastp (not (org-export-get-next-element row info))))
5397 (when contents
5398 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5399 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5400 ;; `:lstart', `:lend' and their relatives.
5401 ,(let ((cells
5402 '(org-element-map row 'table-cell
5403 (lambda (cell)
5404 ;; Export all cells, without separators.
5406 ;; Use `org-export-data-with-backend'
5407 ;; instead of `org-export-data' to eschew
5408 ;; cached values, which
5409 ;; ignore :orgtbl-ignore-sep parameter.
5410 (org-export-data-with-backend
5411 cell
5412 (plist-get info :back-end)
5413 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5414 info)))
5415 `(cond
5416 ,(and hllfmt
5417 `(last-header-p ,(org-table--generic-apply
5418 hllfmt ":hllfmt" nil cells)))
5419 ,(and hlfmt
5420 `(headerp ,(org-table--generic-apply
5421 hlfmt ":hlfmt" nil cells)))
5422 ,(and llfmt
5423 `(lastp ,(org-table--generic-apply
5424 llfmt ":llfmt" nil cells)))
5426 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5427 `(concat
5428 (cond
5429 ,(and
5430 (or hllstart hllend)
5431 `(last-header-p
5432 (concat
5433 ,(org-table--generic-apply hllstart ":hllstart")
5434 contents
5435 ,(org-table--generic-apply hllend ":hllend"))))
5436 ,(and
5437 (or hlstart hlend)
5438 `(headerp
5439 (concat
5440 ,(org-table--generic-apply hlstart ":hlstart")
5441 contents
5442 ,(org-table--generic-apply hlend ":hlend"))))
5443 ,(and
5444 (or llstart llend)
5445 `(lastp
5446 (concat
5447 ,(org-table--generic-apply llstart ":llstart")
5448 contents
5449 ,(org-table--generic-apply llend ":llend"))))
5451 ,(cond
5452 ((or lstart lend)
5453 `(concat
5454 ,(org-table--generic-apply lstart ":lstart")
5455 contents
5456 ,(org-table--generic-apply lend ":lend")))
5457 (backend
5458 `(org-export-with-backend
5459 ',backend row contents info))
5460 (t 'contents)))))))))))))))
5462 (defun org-table--to-generic-cell (params)
5463 "Return custom table cell transcoder according to PARAMS.
5464 PARAMS is a plist. See `orgtbl-to-generic' for more
5465 information."
5466 (let* ((backend (plist-get params :backend))
5467 (efmt (plist-get params :efmt))
5468 (fmt (plist-get params :fmt))
5469 (hfmt (plist-get params :hfmt))
5470 (sep (plist-get params :sep))
5471 (hsep (plist-get params :hsep)))
5472 `(lambda (cell contents info)
5473 ;; Make sure that contents are exported as Org data when :raw
5474 ;; parameter is non-nil.
5475 ,(when (and backend (plist-get params :raw))
5476 `(setq contents
5477 ;; Since we don't know what are the pseudo object
5478 ;; types defined in backend, we cannot pass them to
5479 ;; `org-element-interpret-data'. As a consequence,
5480 ;; they will be treated as pseudo elements, and will
5481 ;; have newlines appended instead of spaces.
5482 ;; Therefore, we must make sure :post-blank value is
5483 ;; really turned into spaces.
5484 (replace-regexp-in-string
5485 "\n" " "
5486 (org-trim
5487 (org-element-interpret-data
5488 (org-element-contents cell))))))
5490 (let ((headerp ,(and (or hfmt hsep)
5491 '(org-export-table-row-in-header-p
5492 (org-export-get-parent-element cell) info)))
5493 (column
5494 ;; Call costly `org-export-table-cell-address' only if
5495 ;; absolutely necessary, i.e., if one
5496 ;; of :fmt :efmt :hfmt has a "plist type" value.
5497 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5498 (list efmt hfmt fmt))
5499 '(1+ (cdr (org-export-table-cell-address cell info))))))
5500 (when contents
5501 ;; Check if we can apply `:efmt' on CONTENTS.
5502 ,(when efmt
5503 `(when (string-match orgtbl-exp-regexp contents)
5504 (let ((mantissa (match-string 1 contents))
5505 (exponent (match-string 2 contents)))
5506 (setq contents ,(org-table--generic-apply
5507 efmt ":efmt" t 'mantissa 'exponent)))))
5508 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5509 (cond
5510 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5511 hfmt ":hfmt" t 'contents))))
5512 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5513 fmt ":fmt" t 'contents))))))
5514 ;; If a separator is provided, use it instead of BACKEND's.
5515 ;; Separators are ignored when LFMT (or equivalent) is
5516 ;; provided.
5517 ,(cond
5518 ((or hsep sep)
5519 `(if (or ,(and (not sep) '(not headerp))
5520 (plist-get info :orgtbl-ignore-sep)
5521 (not (org-export-get-next-element cell info)))
5522 ,(if (not backend) 'contents
5523 `(org-export-with-backend ',backend cell contents info))
5524 (concat contents
5525 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5526 (or hsep sep)))))
5527 (backend `(org-export-with-backend ',backend cell contents info))
5528 (t 'contents))))))
5530 ;;;###autoload
5531 (defun orgtbl-to-tsv (table params)
5532 "Convert the orgtbl-mode table to TAB separated material."
5533 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5535 ;;;###autoload
5536 (defun orgtbl-to-csv (table params)
5537 "Convert the orgtbl-mode table to CSV material.
5538 This does take care of the proper quoting of fields with comma or quotes."
5539 (orgtbl-to-generic table
5540 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5541 params)))
5543 ;;;###autoload
5544 (defun orgtbl-to-latex (table params)
5545 "Convert the orgtbl-mode TABLE to LaTeX.
5547 TABLE is a list, each entry either the symbol `hline' for
5548 a horizontal separator line, or a list of fields for that line.
5549 PARAMS is a property list of parameters that can influence the
5550 conversion. All parameters from `orgtbl-to-generic' are
5551 supported. It is also possible to use the following ones:
5553 :booktabs
5555 When non-nil, use formal \"booktabs\" style.
5557 :environment
5559 Specify environment to use, as a string. If you use
5560 \"longtable\", you may also want to specify :language property,
5561 as a string, to get proper continuation strings."
5562 (require 'ox-latex)
5563 (orgtbl-to-generic
5564 table
5565 (org-combine-plists
5566 ;; Provide sane default values.
5567 (list :backend 'latex
5568 :latex-default-table-mode 'table
5569 :latex-tables-centered nil
5570 :latex-tables-booktabs (plist-get params :booktabs)
5571 :latex-table-scientific-notation nil
5572 :latex-default-table-environment
5573 (or (plist-get params :environment) "tabular"))
5574 params)))
5576 ;;;###autoload
5577 (defun orgtbl-to-html (table params)
5578 "Convert the orgtbl-mode TABLE to HTML.
5580 TABLE is a list, each entry either the symbol `hline' for
5581 a horizontal separator line, or a list of fields for that line.
5582 PARAMS is a property list of parameters that can influence the
5583 conversion. All parameters from `orgtbl-to-generic' are
5584 supported. It is also possible to use the following one:
5586 :attributes
5588 Attributes and values, as a plist, which will be used in
5589 <table> tag."
5590 (require 'ox-html)
5591 (orgtbl-to-generic
5592 table
5593 (org-combine-plists
5594 ;; Provide sane default values.
5595 (list :backend 'html
5596 :html-table-data-tags '("<td%s>" . "</td>")
5597 :html-table-use-header-tags-for-first-column nil
5598 :html-table-align-individual-fields t
5599 :html-table-row-tags '("<tr>" . "</tr>")
5600 :html-table-attributes
5601 (if (plist-member params :attributes)
5602 (plist-get params :attributes)
5603 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5604 :frame "hsides")))
5605 params)))
5607 ;;;###autoload
5608 (defun orgtbl-to-texinfo (table params)
5609 "Convert the orgtbl-mode TABLE to Texinfo.
5611 TABLE is a list, each entry either the symbol `hline' for
5612 a horizontal separator line, or a list of fields for that line.
5613 PARAMS is a property list of parameters that can influence the
5614 conversion. All parameters from `orgtbl-to-generic' are
5615 supported. It is also possible to use the following one:
5617 :columns
5619 Column widths, as a string. When providing column fractions,
5620 \"@columnfractions\" command can be omitted."
5621 (require 'ox-texinfo)
5622 (let ((output
5623 (orgtbl-to-generic
5624 table
5625 (org-combine-plists
5626 (list :backend 'texinfo
5627 :texinfo-tables-verbatim nil
5628 :texinfo-table-scientific-notation nil)
5629 params)))
5630 (columns (let ((w (plist-get params :columns)))
5631 (cond ((not w) nil)
5632 ((string-match-p "{\\|@columnfractions " w) w)
5633 (t (concat "@columnfractions " w))))))
5634 (if (not columns) output
5635 (replace-regexp-in-string
5636 "@multitable \\(.*\\)" columns output t nil 1))))
5638 ;;;###autoload
5639 (defun orgtbl-to-orgtbl (table params)
5640 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5642 TABLE is a list, each entry either the symbol `hline' for
5643 a horizontal separator line, or a list of fields for that line.
5644 PARAMS is a property list of parameters that can influence the
5645 conversion. All parameters from `orgtbl-to-generic' are
5646 supported.
5648 Useful when slicing one table into many. The :hline, :sep,
5649 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5650 be set to provide ORGTBL directives for the generated table."
5651 (require 'ox-org)
5652 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5654 (defun orgtbl-to-table.el (table params)
5655 "Convert the orgtbl-mode TABLE into a table.el table.
5656 TABLE is a list, each entry either the symbol `hline' for
5657 a horizontal separator line, or a list of fields for that line.
5658 PARAMS is a property list of parameters that can influence the
5659 conversion. All parameters from `orgtbl-to-generic' are
5660 supported."
5661 (with-temp-buffer
5662 (insert (orgtbl-to-orgtbl table params))
5663 (org-table-align)
5664 (replace-regexp-in-string
5665 "-|" "-+"
5666 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5668 (defun orgtbl-to-unicode (table params)
5669 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5671 TABLE is a list, each entry either the symbol `hline' for
5672 a horizontal separator line, or a list of fields for that line.
5673 PARAMS is a property list of parameters that can influence the
5674 conversion. All parameters from `orgtbl-to-generic' are
5675 supported. It is also possible to use the following ones:
5677 :ascii-art
5679 When non-nil, use \"ascii-art-to-unicode\" package to translate
5680 the table. You can download it here:
5681 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5683 :narrow
5685 When non-nil, narrow columns width than provided width cookie,
5686 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5687 (require 'ox-ascii)
5688 (orgtbl-to-generic
5689 table
5690 (org-combine-plists
5691 (list :backend 'ascii
5692 :ascii-charset 'utf-8
5693 :ascii-table-widen-columns (not (plist-get params :narrow))
5694 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5695 params)))
5697 ;; Put the cursor in a column containing numerical values
5698 ;; of an Org table,
5699 ;; type C-c " a
5700 ;; A new column is added with a bar plot.
5701 ;; When the table is refreshed (C-u C-c *),
5702 ;; the plot is updated to reflect the new values.
5704 (defun orgtbl-ascii-draw (value min max &optional width characters)
5705 "Draw an ascii bar in a table.
5706 VALUE is the value to plot, it determines the width of the bar to draw.
5707 MIN is the value that will be displayed as empty (zero width bar).
5708 MAX is the value that will draw a bar filling all the WIDTH.
5709 WIDTH is the span in characters from MIN to MAX.
5710 CHARACTERS is a string that will compose the bar, with shades of grey
5711 from pure white to pure black. It defaults to a 10 characters string
5712 of regular ascii characters."
5713 (let* ((width (ceiling (or width 12)))
5714 (characters (or characters " .:;c!lhVHW"))
5715 (len (1- (length characters)))
5716 (value (float (if (numberp value)
5717 value (string-to-number value))))
5718 (relative (/ (- value min) (- max min)))
5719 (steps (round (* relative width len))))
5720 (cond ((< steps 0) "too small")
5721 ((> steps (* width len)) "too large")
5722 (t (let* ((int-division (/ steps len))
5723 (remainder (- steps (* int-division len))))
5724 (concat (make-string int-division (elt characters len))
5725 (string (elt characters remainder))))))))
5727 ;;;###autoload
5728 (defun orgtbl-ascii-plot (&optional ask)
5729 "Draw an ASCII bar plot in a column.
5731 With cursor in a column containing numerical values, this function
5732 will draw a plot in a new column.
5734 ASK, if given, is a numeric prefix to override the default 12
5735 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5736 prefix,
5737 which will prompt for the width."
5738 (interactive "P")
5739 (let ((col (org-table-current-column))
5740 (min 1e999) ; 1e999 will be converted to infinity
5741 (max -1e999) ; which is the desired result
5742 (table (org-table-to-lisp))
5743 (length
5744 (cond ((consp ask)
5745 (read-number "Length of column " 12))
5746 ((numberp ask) ask)
5747 (t 12))))
5748 ;; Skip any hline a the top of table.
5749 (while (eq (car table) 'hline) (setq table (cdr table)))
5750 ;; Skip table header if any.
5751 (dolist (x (or (cdr (memq 'hline table)) table))
5752 (when (consp x)
5753 (setq x (nth (1- col) x))
5754 (when (string-match
5755 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5757 (setq x (string-to-number x))
5758 (when (> min x) (setq min x))
5759 (when (< max x) (setq max x)))))
5760 (org-table-insert-column)
5761 (org-table-move-column-right)
5762 (org-table-store-formulas
5763 (cons
5764 (cons
5765 (concat "$" (number-to-string (1+ col)))
5766 (format "'(%s $%s %s %s %s)"
5767 "orgtbl-ascii-draw" col min max length))
5768 (org-table-get-stored-formulas)))
5769 (org-table-recalculate t)))
5771 ;; Example of extension: unicode characters
5772 ;; Here are two examples of different styles.
5774 ;; Unicode block characters are used to give a smooth effect.
5775 ;; See http://en.wikipedia.org/wiki/Block_Elements
5776 ;; Use one of those drawing functions
5777 ;; - orgtbl-ascii-draw (the default ascii)
5778 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5779 ;; - orgtbl-uc-draw-cont (smooth unicode)
5781 ;; This is best viewed with the "DejaVu Sans Mono" font
5782 ;; (use M-x set-frame-font).
5784 (defun orgtbl-uc-draw-grid (value min max &optional width)
5785 "Draw a bar in a table using block unicode characters.
5786 It is a variant of orgtbl-ascii-draw with Unicode block
5787 characters, for a smooth display. Bars appear as grids (to the
5788 extent the font allows)."
5789 ;; http://en.wikipedia.org/wiki/Block_Elements
5790 ;; best viewed with the "DejaVu Sans Mono" font.
5791 (orgtbl-ascii-draw value min max width
5792 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5794 (defun orgtbl-uc-draw-cont (value min max &optional width)
5795 "Draw a bar in a table using block unicode characters.
5796 It is a variant of orgtbl-ascii-draw with Unicode block
5797 characters, for a smooth display. Bars are solid (to the extent
5798 the font allows)."
5799 (orgtbl-ascii-draw value min max width
5800 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5802 (defun org-table-get-remote-range (name-or-id form)
5803 "Get a field value or a list of values in a range from table at ID.
5805 NAME-OR-ID may be the name of a table in the current file as set
5806 by a \"#+NAME:\" directive. The first table following this line
5807 will then be used. Alternatively, it may be an ID referring to
5808 any entry, also in a different file. In this case, the first
5809 table in that entry will be referenced.
5810 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5811 \"@I$2..@II$2\". All the references must be absolute, not relative.
5813 The return value is either a single string for a single field, or a
5814 list of the fields in the rectangle."
5815 (save-match-data
5816 (let ((case-fold-search t) (id-loc nil)
5817 ;; Protect a bunch of variables from being overwritten by
5818 ;; the context of the remote table.
5819 org-table-column-names org-table-column-name-regexp
5820 org-table-local-parameters org-table-named-field-locations
5821 org-table-current-line-types
5822 org-table-current-begin-pos org-table-dlines
5823 org-table-current-ncol
5824 org-table-hlines
5825 org-table-last-column-widths
5826 org-table-last-alignment
5827 buffer loc)
5828 (setq form (org-table-convert-refs-to-rc form))
5829 (org-with-wide-buffer
5830 (goto-char (point-min))
5831 (if (re-search-forward
5832 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5833 (regexp-quote name-or-id) "[ \t]*$")
5834 nil t)
5835 (setq buffer (current-buffer) loc (match-beginning 0))
5836 (setq id-loc (org-id-find name-or-id 'marker))
5837 (unless (and id-loc (markerp id-loc))
5838 (user-error "Can't find remote table \"%s\"" name-or-id))
5839 (setq buffer (marker-buffer id-loc)
5840 loc (marker-position id-loc))
5841 (move-marker id-loc nil))
5842 (with-current-buffer buffer
5843 (org-with-wide-buffer
5844 (goto-char loc)
5845 (forward-char 1)
5846 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5847 (not (match-beginning 1)))
5848 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5849 (org-table-analyze)
5850 (setq form (org-table-formula-substitute-names
5851 (org-table-formula-handle-first/last-rc form)))
5852 (if (and (string-match org-table-range-regexp form)
5853 (> (length (match-string 0 form)) 1))
5854 (org-table-get-range
5855 (match-string 0 form) org-table-current-begin-pos 1)
5856 form)))))))
5858 (defun org-table-remote-reference-indirection (form)
5859 "Return formula with table remote references substituted by indirection.
5860 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5861 This indirection works only with the format @ROW$COLUMN. The
5862 format \"B3\" is not supported because it can not be
5863 distinguished from a plain table name or ID."
5864 (let ((regexp
5865 ;; Same as in `org-table-eval-formula'.
5866 (concat "\\<remote([ \t]*\\("
5867 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5868 "[@$][^ \t,]+"
5869 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5870 (replace-regexp-in-string
5871 regexp
5872 (lambda (m)
5873 (save-match-data
5874 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5875 (org-table-get-range
5876 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5877 (concat "@0" eq)
5878 eq)))))
5879 form t t 1)))
5881 (defmacro org-define-lookup-function (mode)
5882 (let ((mode-str (symbol-name mode))
5883 (first-p (eq mode 'first))
5884 (all-p (eq mode 'all)))
5885 (let ((plural-str (if all-p "s" "")))
5886 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5887 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5888 If R-LIST is nil, return matching element%s of S-LIST.
5889 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5890 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5891 This function is generated by a call to the macro `org-define-lookup-function'."
5892 mode-str plural-str plural-str plural-str)
5893 (let ,(let ((lvars '((p (or predicate 'equal))
5894 (sl s-list)
5895 (rl (or r-list s-list))
5896 (ret nil))))
5897 (if first-p (cons '(match-p nil) lvars) lvars))
5898 (while ,(if first-p '(and (not match-p) sl) 'sl)
5899 (when (funcall p val (car sl))
5900 ,(when first-p '(setq match-p t))
5901 (let ((rval (car rl)))
5902 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5903 (setq sl (cdr sl) rl (cdr rl)))
5904 ret)))))
5906 (org-define-lookup-function first)
5907 (org-define-lookup-function last)
5908 (org-define-lookup-function all)
5910 (provide 'org-table)
5912 ;; Local variables:
5913 ;; generated-autoload-file: "org-loaddefs.el"
5914 ;; End:
5916 ;;; org-table.el ends here