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