Merge branch 'maint'
[org-mode.git] / lisp / org-table.el
blobb89d13306cb1c4f086ec270fae2ce2e469f13a87
1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2015 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, trailing spaces, be sure to catch the correct
931 ;; ending at its beginning. In any other case, ending is
932 ;; expected to be 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 (fequation (or (assoc name eql) (assoc ref eql)))
1290 (cequation (assoc (int-to-string col) eql))
1291 (eqn (or fequation cequation)))
1292 (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
1293 (when p (setq eqn p)))
1294 (goto-char pos)
1295 (ignore-errors (org-table-show-reference 'local))
1296 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1297 dline col
1298 (if cname (concat " or $" cname) "")
1299 dline col ref1
1300 (if name (concat " or $" name) "")
1301 ;; FIXME: formula info not correct if special table line
1302 (if eqn
1303 (concat ", formula: "
1304 (org-table-formula-to-user
1305 (concat
1306 (if (string-match "^[$@]"(car eqn)) "" "$")
1307 (car eqn) "=" (cdr eqn))))
1308 "")))))
1310 (defun org-table-current-column ()
1311 "Find out which column we are in."
1312 (interactive)
1313 (when (org-called-interactively-p 'any) (org-table-check-inside-data-field))
1314 (save-excursion
1315 (let ((column 0) (pos (point)))
1316 (beginning-of-line)
1317 (while (search-forward "|" pos t) (incf column))
1318 (when (org-called-interactively-p 'interactive)
1319 (message "In table column %d" column))
1320 column)))
1322 ;;;###autoload
1323 (defun org-table-current-dline ()
1324 "Find out what table data line we are in.
1325 Only data lines count for this."
1326 (interactive)
1327 (when (org-called-interactively-p 'any)
1328 (org-table-check-inside-data-field))
1329 (save-excursion
1330 (let ((c 0)
1331 (pos (point)))
1332 (goto-char (org-table-begin))
1333 (while (<= (point) pos)
1334 (when (looking-at org-table-dataline-regexp) (incf c))
1335 (forward-line))
1336 (when (org-called-interactively-p 'any)
1337 (message "This is table line %d" c))
1338 c)))
1340 ;;;###autoload
1341 (defun org-table-goto-column (n &optional on-delim force)
1342 "Move the cursor to the Nth column in the current table line.
1343 With optional argument ON-DELIM, stop with point before the left delimiter
1344 of the field.
1345 If there are less than N fields, just go to after the last delimiter.
1346 However, when FORCE is non-nil, create new columns if necessary."
1347 (interactive "p")
1348 (beginning-of-line 1)
1349 (when (> n 0)
1350 (while (and (> (setq n (1- n)) -1)
1351 (or (search-forward "|" (point-at-eol) t)
1352 (and force
1353 (progn (end-of-line 1)
1354 (skip-chars-backward "^|")
1355 (insert " | ")
1356 t)))))
1357 (when (and force (not (looking-at ".*|")))
1358 (save-excursion (end-of-line 1) (insert " | ")))
1359 (if on-delim
1360 (backward-char 1)
1361 (if (looking-at " ") (forward-char 1)))))
1363 ;;;###autoload
1364 (defun org-table-insert-column ()
1365 "Insert a new column into the table."
1366 (interactive)
1367 (unless (org-at-table-p) (user-error "Not at a table"))
1368 (org-table-find-dataline)
1369 (let* ((col (max 1 (org-table-current-column)))
1370 (beg (org-table-begin))
1371 (end (copy-marker (org-table-end))))
1372 (org-table-save-field
1373 (goto-char beg)
1374 (while (< (point) end)
1375 (unless (org-at-table-hline-p)
1376 (org-table-goto-column col t)
1377 (insert "| "))
1378 (forward-line)))
1379 (set-marker end nil)
1380 (org-table-align)
1381 (when (or (not org-table-fix-formulas-confirm)
1382 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1383 (org-table-fix-formulas "$" nil (1- col) 1)
1384 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1386 (defun org-table-find-dataline ()
1387 "Find a data line in the current table, which is needed for column commands."
1388 (if (and (org-at-table-p)
1389 (not (org-at-table-hline-p)))
1391 (let ((col (current-column))
1392 (end (org-table-end)))
1393 (org-move-to-column col)
1394 (while (and (< (point) end)
1395 (or (not (= (current-column) col))
1396 (org-at-table-hline-p)))
1397 (beginning-of-line 2)
1398 (org-move-to-column col))
1399 (if (and (org-at-table-p)
1400 (not (org-at-table-hline-p)))
1402 (user-error
1403 "Please position cursor in a data line for column operations")))))
1405 (defun org-table-line-to-dline (line &optional above)
1406 "Turn a buffer line number into a data line number.
1408 If there is no data line in this line, return nil.
1410 If there is no matching dline (most likely the reference was
1411 a hline), the first dline below it is used. When ABOVE is
1412 non-nil, the one above is used."
1413 (let ((min 1)
1414 (max (1- (length org-table-dlines))))
1415 (cond ((or (> (aref org-table-dlines min) line)
1416 (< (aref org-table-dlines max) line))
1417 nil)
1418 ((= (aref org-table-dlines max) line) max)
1419 (t (catch 'exit
1420 (while (> (- max min) 1)
1421 (let* ((mean (/ (+ max min) 2))
1422 (v (aref org-table-dlines mean)))
1423 (cond ((= v line) (throw 'exit mean))
1424 ((> v line) (setq max mean))
1425 (t (setq min mean)))))
1426 (if above min max))))))
1428 ;;;###autoload
1429 (defun org-table-delete-column ()
1430 "Delete a column from the table."
1431 (interactive)
1432 (unless (org-at-table-p) (user-error "Not at a table"))
1433 (org-table-find-dataline)
1434 (org-table-check-inside-data-field)
1435 (let ((col (org-table-current-column))
1436 (beg (org-table-begin))
1437 (end (copy-marker (org-table-end))))
1438 (org-table-save-field
1439 (goto-char beg)
1440 (while (< (point) end)
1441 (if (org-at-table-hline-p)
1443 (org-table-goto-column col t)
1444 (and (looking-at "|[^|\n]+|")
1445 (replace-match "|")))
1446 (forward-line)))
1447 (set-marker end nil)
1448 (org-table-goto-column (max 1 (1- col)))
1449 (org-table-align)
1450 (when (or (not org-table-fix-formulas-confirm)
1451 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1452 (org-table-fix-formulas
1453 "$" (list (cons (number-to-string col) "INVALID")) col -1 col)
1454 (org-table-fix-formulas
1455 "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col))))
1457 ;;;###autoload
1458 (defun org-table-move-column-right ()
1459 "Move column to the right."
1460 (interactive)
1461 (org-table-move-column nil))
1462 ;;;###autoload
1463 (defun org-table-move-column-left ()
1464 "Move column to the left."
1465 (interactive)
1466 (org-table-move-column 'left))
1468 ;;;###autoload
1469 (defun org-table-move-column (&optional left)
1470 "Move the current column to the right. With arg LEFT, move to the left."
1471 (interactive "P")
1472 (unless (org-at-table-p) (user-error "Not at a table"))
1473 (org-table-find-dataline)
1474 (org-table-check-inside-data-field)
1475 (let* ((col (org-table-current-column))
1476 (col1 (if left (1- col) col))
1477 (colpos (if left (1- col) (1+ col)))
1478 (beg (org-table-begin))
1479 (end (copy-marker (org-table-end))))
1480 (when (and left (= col 1))
1481 (user-error "Cannot move column further left"))
1482 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1483 (user-error "Cannot move column further right"))
1484 (org-table-save-field
1485 (goto-char beg)
1486 (while (< (point) end)
1487 (unless (org-at-table-hline-p)
1488 (org-table-goto-column col1 t)
1489 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1490 (replace-match "|\\2|\\1|")))
1491 (forward-line)))
1492 (set-marker end nil)
1493 (org-table-goto-column colpos)
1494 (org-table-align)
1495 (when (or (not org-table-fix-formulas-confirm)
1496 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1497 (org-table-fix-formulas
1498 "$" (list (cons (number-to-string col) (number-to-string colpos))
1499 (cons (number-to-string colpos) (number-to-string col))))
1500 (org-table-fix-formulas
1501 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1502 (cons (number-to-string colpos) (number-to-string col)))))))
1504 ;;;###autoload
1505 (defun org-table-move-row-down ()
1506 "Move table row down."
1507 (interactive)
1508 (org-table-move-row nil))
1509 ;;;###autoload
1510 (defun org-table-move-row-up ()
1511 "Move table row up."
1512 (interactive)
1513 (org-table-move-row 'up))
1515 ;;;###autoload
1516 (defun org-table-move-row (&optional up)
1517 "Move the current table line down. With arg UP, move it up."
1518 (interactive "P")
1519 (let* ((col (current-column))
1520 (pos (point))
1521 (hline1p (save-excursion (beginning-of-line 1)
1522 (looking-at org-table-hline-regexp)))
1523 (dline1 (org-table-current-dline))
1524 (dline2 (+ dline1 (if up -1 1)))
1525 (tonew (if up 0 2))
1526 txt hline2p)
1527 (beginning-of-line tonew)
1528 (unless (org-at-table-p)
1529 (goto-char pos)
1530 (user-error "Cannot move row further"))
1531 (setq hline2p (looking-at org-table-hline-regexp))
1532 (goto-char pos)
1533 (beginning-of-line 1)
1534 (setq pos (point))
1535 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1536 (delete-region (point) (1+ (point-at-eol)))
1537 (beginning-of-line tonew)
1538 (insert txt)
1539 (beginning-of-line 0)
1540 (org-move-to-column col)
1541 (unless (or hline1p hline2p
1542 (not (or (not org-table-fix-formulas-confirm)
1543 (funcall org-table-fix-formulas-confirm
1544 "Fix formulas? "))))
1545 (org-table-fix-formulas
1546 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1547 (cons (number-to-string dline2) (number-to-string dline1)))))))
1549 ;;;###autoload
1550 (defun org-table-insert-row (&optional arg)
1551 "Insert a new row above the current line into the table.
1552 With prefix ARG, insert below the current line."
1553 (interactive "P")
1554 (if (not (org-at-table-p))
1555 (user-error "Not at a table"))
1556 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1557 (new (org-table-clean-line line)))
1558 ;; Fix the first field if necessary
1559 (if (string-match "^[ \t]*| *[#$] *|" line)
1560 (setq new (replace-match (match-string 0 line) t t new)))
1561 (beginning-of-line (if arg 2 1))
1562 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1563 (beginning-of-line 0)
1564 (re-search-forward "| ?" (point-at-eol) t)
1565 (and (or org-table-may-need-update org-table-overlay-coordinates)
1566 (org-table-align))
1567 (when (or (not org-table-fix-formulas-confirm)
1568 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1569 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1571 ;;;###autoload
1572 (defun org-table-insert-hline (&optional above)
1573 "Insert a horizontal-line below the current line into the table.
1574 With prefix ABOVE, insert above the current line."
1575 (interactive "P")
1576 (if (not (org-at-table-p))
1577 (user-error "Not at a table"))
1578 (when (eobp) (insert "\n") (backward-char 1))
1579 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1580 (org-table-align))
1581 (let ((line (org-table-clean-line
1582 (buffer-substring (point-at-bol) (point-at-eol))))
1583 (col (current-column)))
1584 (while (string-match "|\\( +\\)|" line)
1585 (setq line (replace-match
1586 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1587 ?-) "|") t t line)))
1588 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1589 (beginning-of-line (if above 1 2))
1590 (insert line "\n")
1591 (beginning-of-line (if above 1 -1))
1592 (org-move-to-column col)
1593 (and org-table-overlay-coordinates (org-table-align))))
1595 ;;;###autoload
1596 (defun org-table-hline-and-move (&optional same-column)
1597 "Insert a hline and move to the row below that line."
1598 (interactive "P")
1599 (let ((col (org-table-current-column)))
1600 (org-table-maybe-eval-formula)
1601 (org-table-maybe-recalculate-line)
1602 (org-table-insert-hline)
1603 (end-of-line 2)
1604 (if (looking-at "\n[ \t]*|-")
1605 (progn (insert "\n|") (org-table-align))
1606 (org-table-next-field))
1607 (if same-column (org-table-goto-column col))))
1609 (defun org-table-clean-line (s)
1610 "Convert a table line S into a string with only \"|\" and space.
1611 In particular, this does handle wide and invisible characters."
1612 (if (string-match "^[ \t]*|-" s)
1613 ;; It's a hline, just map the characters
1614 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1615 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1616 (setq s (replace-match
1617 (concat "|" (make-string (org-string-width (match-string 1 s))
1618 ?\ ) "|")
1619 t t s)))
1622 ;;;###autoload
1623 (defun org-table-kill-row ()
1624 "Delete the current row or horizontal line from the table."
1625 (interactive)
1626 (if (not (org-at-table-p))
1627 (user-error "Not at a table"))
1628 (let ((col (current-column))
1629 (dline (org-table-current-dline)))
1630 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1631 (if (not (org-at-table-p)) (beginning-of-line 0))
1632 (org-move-to-column col)
1633 (when (or (not org-table-fix-formulas-confirm)
1634 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1635 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1636 dline -1 dline))))
1638 ;;;###autoload
1639 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func)
1640 "Sort table lines according to the column at point.
1642 The position of point indicates the column to be used for
1643 sorting, and the range of lines is the range between the nearest
1644 horizontal separator lines, or the entire table of no such lines
1645 exist. If point is before the first column, you will be prompted
1646 for the sorting column. If there is an active region, the mark
1647 specifies the first line and the sorting column, while point
1648 should be in the last line to be included into the sorting.
1650 The command then prompts for the sorting type which can be
1651 alphabetically, numerically, or by time (as given in a time stamp
1652 in the field, or as a HH:MM value). Sorting in reverse order is
1653 also possible.
1655 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1657 If SORTING-TYPE is specified when this function is called from a Lisp
1658 program, no prompting will take place. SORTING-TYPE must be a character,
1659 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1660 sorting should be done in reverse order.
1662 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1663 a function to be called to extract the key. It must return either
1664 a string or a number that should serve as the sorting key for that
1665 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1666 is specified interactively, the comparison will be either a string or
1667 numeric compare based on the type of the first key in the table."
1668 (interactive "P")
1669 (when (org-region-active-p) (goto-char (region-beginning)))
1670 ;; Point must be either within a field or before a data line.
1671 (save-excursion
1672 (skip-chars-backward " \t")
1673 (when (bolp) (search-forward "|" (line-end-position) t))
1674 (org-table-check-inside-data-field))
1675 ;; Set appropriate case sensitivity and column used for sorting.
1676 (let ((column (let ((c (org-table-current-column)))
1677 (cond ((> c 0) c)
1678 ((org-called-interactively-p 'any)
1679 (read-number "Use column N for sorting: "))
1680 (t 1))))
1681 (sorting-type
1682 (or sorting-type
1683 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1684 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1685 (save-restriction
1686 ;; Narrow buffer to appropriate sorting area.
1687 (if (org-region-active-p)
1688 (progn (goto-char (region-beginning))
1689 (narrow-to-region
1690 (point)
1691 (save-excursion (goto-char (region-end))
1692 (line-beginning-position 2))))
1693 (let ((start (org-table-begin))
1694 (end (org-table-end)))
1695 (narrow-to-region
1696 (save-excursion
1697 (if (re-search-backward org-table-hline-regexp start t)
1698 (line-beginning-position 2)
1699 start))
1700 (if (save-excursion (re-search-forward org-table-hline-regexp end t))
1701 (match-beginning 0)
1702 end))))
1703 ;; Determine arguments for `sort-subr'. Also record original
1704 ;; position. `org-table-save-field' cannot help here since
1705 ;; sorting is too much destructive.
1706 (let* ((sort-fold-case (not with-case))
1707 (coordinates
1708 (cons (count-lines (point-min) (line-beginning-position))
1709 (current-column)))
1710 (extract-key-from-field
1711 ;; Function to be called on the contents of the field
1712 ;; used for sorting in the current row.
1713 (case sorting-type
1714 ((?n ?N) #'string-to-number)
1715 ((?a ?A) #'org-sort-remove-invisible)
1716 ((?t ?T)
1717 (lambda (f)
1718 (cond ((string-match org-ts-regexp-both f)
1719 (org-float-time
1720 (org-time-string-to-time (match-string 0 f))))
1721 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" f)
1722 (org-hh:mm-string-to-minutes f))
1723 (t 0))))
1724 ((?f ?F)
1725 (or getkey-func
1726 (and (org-called-interactively-p 'any)
1727 (intern
1728 (completing-read "Sort using function: "
1729 obarray #'fboundp t)))
1730 (error "Missing key extractor to sort rows")))
1731 (t (user-error "Invalid sorting type `%c'" sorting-type))))
1732 (predicate
1733 (case sorting-type
1734 ((?n ?N ?t ?T) #'<)
1735 ((?a ?A) #'string<)
1736 ((?f ?F) compare-func))))
1737 (goto-char (point-min))
1738 (sort-subr (memq sorting-type '(?A ?N ?T ?F))
1739 (lambda ()
1740 (forward-line)
1741 (while (and (not (eobp))
1742 (not (looking-at org-table-dataline-regexp)))
1743 (forward-line)))
1744 #'end-of-line
1745 (lambda ()
1746 (funcall extract-key-from-field
1747 (org-trim (org-table-get-field column))))
1749 predicate)
1750 ;; Move back to initial field.
1751 (forward-line (car coordinates))
1752 (move-to-column (cdr coordinates))))))
1754 ;;;###autoload
1755 (defun org-table-cut-region (beg end)
1756 "Copy region in table to the clipboard and blank all relevant fields.
1757 If there is no active region, use just the field at point."
1758 (interactive (list
1759 (if (org-region-active-p) (region-beginning) (point))
1760 (if (org-region-active-p) (region-end) (point))))
1761 (org-table-copy-region beg end 'cut))
1763 ;;;###autoload
1764 (defun org-table-copy-region (beg end &optional cut)
1765 "Copy rectangular region in table to clipboard.
1766 A special clipboard is used which can only be accessed
1767 with `org-table-paste-rectangle'."
1768 (interactive (list
1769 (if (org-region-active-p) (region-beginning) (point))
1770 (if (org-region-active-p) (region-end) (point))
1771 current-prefix-arg))
1772 (goto-char (min beg end))
1773 (org-table-check-inside-data-field)
1774 (let ((beg (line-beginning-position))
1775 (c01 (org-table-current-column))
1776 region)
1777 (goto-char (max beg end))
1778 (org-table-check-inside-data-field)
1779 (let* ((end (copy-marker (line-end-position)))
1780 (c02 (org-table-current-column))
1781 (column-start (min c01 c02))
1782 (column-end (max c01 c02))
1783 (column-number (1+ (- column-end column-start)))
1784 (rpl (and cut " ")))
1785 (goto-char beg)
1786 (while (< (point) end)
1787 (unless (org-at-table-hline-p)
1788 ;; Collect every cell between COLUMN-START and COLUMN-END.
1789 (let (cols)
1790 (dotimes (c column-number)
1791 (push (org-table-get-field (+ c column-start) rpl) cols))
1792 (push (nreverse cols) region)))
1793 (forward-line))
1794 (set-marker end nil))
1795 (when cut (org-table-align))
1796 (setq org-table-clip (nreverse region))))
1798 ;;;###autoload
1799 (defun org-table-paste-rectangle ()
1800 "Paste a rectangular region into a table.
1801 The upper right corner ends up in the current field. All involved fields
1802 will be overwritten. If the rectangle does not fit into the present table,
1803 the table is enlarged as needed. The process ignores horizontal separator
1804 lines."
1805 (interactive)
1806 (unless (consp org-table-clip)
1807 (user-error "First cut/copy a region to paste!"))
1808 (org-table-check-inside-data-field)
1809 (let* ((column (org-table-current-column))
1810 (org-enable-table-editor t)
1811 (org-table-automatic-realign nil))
1812 (org-table-save-field
1813 (dolist (row org-table-clip)
1814 (while (org-at-table-hline-p) (forward-line))
1815 ;; If we left the table, create a new row.
1816 (when (and (bolp) (not (looking-at "[ \t]*|")))
1817 (end-of-line 0)
1818 (org-table-next-field))
1819 (let ((c column))
1820 (dolist (field row)
1821 (org-table-goto-column c nil 'force)
1822 (org-table-get-field nil field)
1823 (incf c)))
1824 (forward-line)))
1825 (org-table-align)))
1827 ;;;###autoload
1828 (defun org-table-convert ()
1829 "Convert from `org-mode' table to table.el and back.
1830 Obviously, this only works within limits. When an Org-mode table is
1831 converted to table.el, all horizontal separator lines get lost, because
1832 table.el uses these as cell boundaries and has no notion of horizontal lines.
1833 A table.el table can be converted to an Org-mode table only if it does not
1834 do row or column spanning. Multiline cells will become multiple cells.
1835 Beware, Org-mode does not test if the table can be successfully converted - it
1836 blindly applies a recipe that works for simple tables."
1837 (interactive)
1838 (require 'table)
1839 (if (org-at-table.el-p)
1840 ;; convert to Org-mode table
1841 (let ((beg (copy-marker (org-table-begin t)))
1842 (end (copy-marker (org-table-end t))))
1843 (table-unrecognize-region beg end)
1844 (goto-char beg)
1845 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1846 (replace-match ""))
1847 (goto-char beg))
1848 (if (org-at-table-p)
1849 ;; convert to table.el table
1850 (let ((beg (copy-marker (org-table-begin)))
1851 (end (copy-marker (org-table-end))))
1852 ;; first, get rid of all horizontal lines
1853 (goto-char beg)
1854 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1855 (replace-match ""))
1856 ;; insert a hline before first
1857 (goto-char beg)
1858 (org-table-insert-hline 'above)
1859 (beginning-of-line -1)
1860 ;; insert a hline after each line
1861 (while (progn (beginning-of-line 3) (< (point) end))
1862 (org-table-insert-hline))
1863 (goto-char beg)
1864 (setq end (move-marker end (org-table-end)))
1865 ;; replace "+" at beginning and ending of hlines
1866 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1867 (replace-match "\\1+-"))
1868 (goto-char beg)
1869 (while (re-search-forward "-|[ \t]*$" end t)
1870 (replace-match "-+"))
1871 (goto-char beg)))))
1873 (defun org-table-transpose-table-at-point ()
1874 "Transpose Org table at point and eliminate hlines.
1875 So a table like
1877 | 1 | 2 | 4 | 5 |
1878 |---+---+---+---|
1879 | a | b | c | d |
1880 | e | f | g | h |
1882 will be transposed as
1884 | 1 | a | e |
1885 | 2 | b | f |
1886 | 4 | c | g |
1887 | 5 | d | h |
1889 Note that horizontal lines disappear."
1890 (interactive)
1891 (let* ((table (delete 'hline (org-table-to-lisp)))
1892 (dline_old (org-table-current-line))
1893 (col_old (org-table-current-column))
1894 (contents (mapcar (lambda (_)
1895 (let ((tp table))
1896 (mapcar
1897 (lambda (_)
1898 (prog1
1899 (pop (car tp))
1900 (setq tp (cdr tp))))
1901 table)))
1902 (car table))))
1903 (goto-char (org-table-begin))
1904 (re-search-forward "|")
1905 (backward-char)
1906 (delete-region (point) (org-table-end))
1907 (insert (mapconcat
1908 (lambda(x)
1909 (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1910 contents ""))
1911 (org-table-goto-line col_old)
1912 (org-table-goto-column dline_old))
1913 (org-table-align))
1915 ;;;###autoload
1916 (defun org-table-wrap-region (arg)
1917 "Wrap several fields in a column like a paragraph.
1918 This is useful if you'd like to spread the contents of a field over several
1919 lines, in order to keep the table compact.
1921 If there is an active region, and both point and mark are in the same column,
1922 the text in the column is wrapped to minimum width for the given number of
1923 lines. Generally, this makes the table more compact. A prefix ARG may be
1924 used to change the number of desired lines. For example, \
1925 `C-2 \\[org-table-wrap-region]'
1926 formats the selected text to two lines. If the region was longer than two
1927 lines, the remaining lines remain empty. A negative prefix argument reduces
1928 the current number of lines by that amount. The wrapped text is pasted back
1929 into the table. If you formatted it to more lines than it was before, fields
1930 further down in the table get overwritten - so you might need to make space in
1931 the table first.
1933 If there is no region, the current field is split at the cursor position and
1934 the text fragment to the right of the cursor is prepended to the field one
1935 line down.
1937 If there is no region, but you specify a prefix ARG, the current field gets
1938 blank, and the content is appended to the field above."
1939 (interactive "P")
1940 (org-table-check-inside-data-field)
1941 (if (org-region-active-p)
1942 ;; There is a region: fill as a paragraph.
1943 (let ((start (region-beginning)))
1944 (org-table-cut-region (region-beginning) (region-end))
1945 (when (> (length (car org-table-clip)) 1)
1946 (user-error "Region must be limited to single column"))
1947 (let ((nlines (cond ((not arg) (length org-table-clip))
1948 ((< arg 1) (+ (length org-table-clip) arg))
1949 (t arg))))
1950 (setq org-table-clip
1951 (mapcar #'list
1952 (org-wrap (mapconcat #'car org-table-clip " ")
1954 nlines))))
1955 (goto-char start)
1956 (org-table-paste-rectangle))
1957 ;; No region, split the current field at point.
1958 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1959 (skip-chars-forward "^\r\n|"))
1960 (cond
1961 (arg ; Combine with field above.
1962 (let ((s (org-table-blank-field))
1963 (col (org-table-current-column)))
1964 (forward-line -1)
1965 (while (org-at-table-hline-p) (forward-line -1))
1966 (org-table-goto-column col)
1967 (skip-chars-forward "^|")
1968 (skip-chars-backward " ")
1969 (insert " " (org-trim s))
1970 (org-table-align)))
1971 ((looking-at "\\([^|]+\\)+|") ; Split field.
1972 (let ((s (match-string 1)))
1973 (replace-match " |")
1974 (goto-char (match-beginning 0))
1975 (org-table-next-row)
1976 (insert (org-trim s) " ")
1977 (org-table-align)))
1978 (t (org-table-next-row)))))
1980 (defvar org-field-marker nil)
1982 ;;;###autoload
1983 (defun org-table-edit-field (arg)
1984 "Edit table field in a different window.
1985 This is mainly useful for fields that contain hidden parts.
1986 When called with a \\[universal-argument] prefix, just make the full field visible so that
1987 it can be edited in place."
1988 (interactive "P")
1989 (cond
1990 ((equal arg '(16))
1991 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1992 (arg
1993 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1994 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1995 (remove-text-properties b e '(org-cwidth t invisible t
1996 display t intangible t))
1997 (if (and (boundp 'font-lock-mode) font-lock-mode)
1998 (font-lock-fontify-block))))
2000 (let ((pos (point-marker))
2001 (coord
2002 (if (eq org-table-use-standard-references t)
2003 (concat (org-number-to-letters (org-table-current-column))
2004 (int-to-string (org-table-current-dline)))
2005 (concat "@" (int-to-string (org-table-current-dline))
2006 "$" (int-to-string (org-table-current-column)))))
2007 (field (org-table-get-field))
2008 (cw (current-window-configuration))
2010 (goto-char pos)
2011 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2012 (when (and (local-variable-p 'org-field-marker)
2013 (markerp org-field-marker))
2014 (move-marker org-field-marker nil))
2015 (erase-buffer)
2016 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
2017 (let ((org-inhibit-startup t)) (org-mode))
2018 (auto-fill-mode -1)
2019 (setq truncate-lines nil)
2020 (setq word-wrap t)
2021 (goto-char (setq p (point-max)))
2022 (insert (org-trim field))
2023 (remove-text-properties p (point-max)
2024 '(invisible t org-cwidth t display t
2025 intangible t))
2026 (goto-char p)
2027 (setq-local org-finish-function 'org-table-finish-edit-field)
2028 (setq-local org-window-configuration cw)
2029 (setq-local org-field-marker pos)
2030 (message "Edit and finish with C-c C-c")))))
2032 (defun org-table-finish-edit-field ()
2033 "Finish editing a table data field.
2034 Remove all newline characters, insert the result into the table, realign
2035 the table and kill the editing buffer."
2036 (let ((pos org-field-marker)
2037 (cw org-window-configuration)
2038 (cb (current-buffer))
2039 text)
2040 (goto-char (point-min))
2041 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
2042 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
2043 (replace-match " "))
2044 (setq text (org-trim (buffer-string)))
2045 (set-window-configuration cw)
2046 (kill-buffer cb)
2047 (select-window (get-buffer-window (marker-buffer pos)))
2048 (goto-char pos)
2049 (move-marker pos nil)
2050 (org-table-check-inside-data-field)
2051 (org-table-get-field nil text)
2052 (org-table-align)
2053 (message "New field value inserted")))
2055 (define-minor-mode org-table-follow-field-mode
2056 "Minor mode to make the table field editor window follow the cursor.
2057 When this mode is active, the field editor window will always show the
2058 current field. The mode exits automatically when the cursor leaves the
2059 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2060 nil " TblFollow" nil
2061 (if org-table-follow-field-mode
2062 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
2063 'append 'local)
2064 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
2065 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2066 (win (and buf (get-buffer-window buf))))
2067 (when win (delete-window win))
2068 (when buf
2069 (with-current-buffer buf
2070 (move-marker org-field-marker nil))
2071 (kill-buffer buf)))))
2073 (defun org-table-follow-fields-with-editor ()
2074 (if (and org-table-exit-follow-field-mode-when-leaving-table
2075 (not (org-at-table-p)))
2076 ;; We have left the table, exit the follow mode
2077 (org-table-follow-field-mode -1)
2078 (when (org-table-check-inside-data-field 'noerror)
2079 (let ((win (selected-window)))
2080 (org-table-edit-field nil)
2081 (org-fit-window-to-buffer)
2082 (select-window win)))))
2084 (defvar org-timecnt) ; dynamically scoped parameter
2086 ;;;###autoload
2087 (defun org-table-sum (&optional beg end nlast)
2088 "Sum numbers in region of current table column.
2089 The result will be displayed in the echo area, and will be available
2090 as kill to be inserted with \\[yank].
2092 If there is an active region, it is interpreted as a rectangle and all
2093 numbers in that rectangle will be summed. If there is no active
2094 region and point is located in a table column, sum all numbers in that
2095 column.
2097 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2098 numbers are assumed to be times as well (in decimal hours) and the
2099 numbers are added as such.
2101 If NLAST is a number, only the NLAST fields will actually be summed."
2102 (interactive)
2103 (save-excursion
2104 (let (col (org-timecnt 0) diff h m s org-table-clip)
2105 (cond
2106 ((and beg end)) ; beg and end given explicitly
2107 ((org-region-active-p)
2108 (setq beg (region-beginning) end (region-end)))
2110 (setq col (org-table-current-column))
2111 (goto-char (org-table-begin))
2112 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2113 (user-error "No table data"))
2114 (org-table-goto-column col)
2115 (setq beg (point))
2116 (goto-char (org-table-end))
2117 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2118 (user-error "No table data"))
2119 (org-table-goto-column col)
2120 (setq end (point))))
2121 (let* ((items (apply 'append (org-table-copy-region beg end)))
2122 (items1 (cond ((not nlast) items)
2123 ((>= nlast (length items)) items)
2124 (t (setq items (reverse items))
2125 (setcdr (nthcdr (1- nlast) items) nil)
2126 (nreverse items))))
2127 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2128 items1)))
2129 (res (apply '+ numbers))
2130 (sres (if (= org-timecnt 0)
2131 (number-to-string res)
2132 (setq diff (* 3600 res)
2133 h (floor (/ diff 3600)) diff (mod diff 3600)
2134 m (floor (/ diff 60)) diff (mod diff 60)
2135 s diff)
2136 (format "%.0f:%02.0f:%02.0f" h m s))))
2137 (kill-new sres)
2138 (if (org-called-interactively-p 'interactive)
2139 (message "%s"
2140 (substitute-command-keys
2141 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2142 (length numbers) sres))))
2143 sres))))
2145 (defun org-table-get-number-for-summing (s)
2146 (let (n)
2147 (if (string-match "^ *|? *" s)
2148 (setq s (replace-match "" nil nil s)))
2149 (if (string-match " *|? *$" s)
2150 (setq s (replace-match "" nil nil s)))
2151 (setq n (string-to-number s))
2152 (cond
2153 ((and (string-match "0" s)
2154 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2155 ((string-match "\\`[ \t]+\\'" s) nil)
2156 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2157 (let ((h (string-to-number (or (match-string 1 s) "0")))
2158 (m (string-to-number (or (match-string 2 s) "0")))
2159 (s (string-to-number (or (match-string 4 s) "0"))))
2160 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2161 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2162 ((equal n 0) nil)
2163 (t n))))
2165 (defun org-table-current-field-formula (&optional key noerror)
2166 "Return the formula active for the current field.
2168 Assumes that table is already analyzed. If KEY is given, return
2169 the key to this formula. Otherwise return the formula preceded
2170 with \"=\" or \":=\"."
2171 (let* ((col (org-table-current-column))
2172 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2173 (line-beginning-position))
2174 col)
2175 org-table-named-field-locations)))
2176 (scol (int-to-string col))
2177 (ref (format "@%d$%d" (org-table-current-dline) col))
2178 (stored-list (org-table-get-stored-formulas noerror))
2179 (ass (or (assoc name stored-list)
2180 (assoc ref stored-list)
2181 (assoc scol stored-list))))
2182 (cond (key (car ass))
2183 (ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2184 (cdr ass))))))
2186 (defun org-table-get-formula (&optional equation named)
2187 "Read a formula from the minibuffer, offer stored formula as default.
2188 When NAMED is non-nil, look for a named equation."
2189 (let* ((stored-list (org-table-get-stored-formulas))
2190 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2191 (line-beginning-position))
2192 (org-table-current-column))
2193 org-table-named-field-locations)))
2194 (ref (format "@%d$%d" (org-table-current-dline)
2195 (org-table-current-column)))
2196 (scol (if named
2197 (if (and name (not (string-match "^LR[0-9]+$" name)))
2198 name
2199 ref)
2200 (int-to-string (org-table-current-column))))
2201 (name (or name ref))
2202 (org-table-may-need-update nil)
2203 (stored (cdr (assoc scol stored-list)))
2204 (eq (cond
2205 ((and stored equation (string-match "^ *=? *$" equation))
2206 stored)
2207 ((stringp equation)
2208 equation)
2209 (t (org-table-formula-from-user
2210 (read-string
2211 (org-table-formula-to-user
2212 (format "%s formula %s%s="
2213 (if named "Field" "Column")
2214 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2215 scol))
2216 (if stored (org-table-formula-to-user stored) "")
2217 'org-table-formula-history
2218 )))))
2219 mustsave)
2220 (when (not (string-match "\\S-" eq))
2221 ;; remove formula
2222 (setq stored-list (delq (assoc scol stored-list) stored-list))
2223 (org-table-store-formulas stored-list)
2224 (user-error "Formula removed"))
2225 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2226 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2227 (if (and name (not named))
2228 ;; We set the column equation, delete the named one.
2229 (setq stored-list (delq (assoc name stored-list) stored-list)
2230 mustsave t))
2231 (if stored
2232 (setcdr (assoc scol stored-list) eq)
2233 (setq stored-list (cons (cons scol eq) stored-list)))
2234 (if (or mustsave (not (equal stored eq)))
2235 (org-table-store-formulas stored-list))
2236 eq))
2238 (defun org-table-store-formulas (alist)
2239 "Store the list of formulas below the current table."
2240 (setq alist (sort alist 'org-table-formula-less-p))
2241 (let ((case-fold-search t))
2242 (save-excursion
2243 (goto-char (org-table-end))
2244 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2245 (progn
2246 ;; don't overwrite TBLFM, we might use text properties to store stuff
2247 (goto-char (match-beginning 3))
2248 (delete-region (match-beginning 3) (match-end 0)))
2249 (org-indent-line)
2250 (insert (or (match-string 2) "#+TBLFM:")))
2251 (insert " "
2252 (mapconcat (lambda (x)
2253 (concat
2254 (if (equal (string-to-char (car x)) ?@) "" "$")
2255 (car x) "=" (cdr x)))
2256 alist "::")
2257 "\n"))))
2259 (defsubst org-table-formula-make-cmp-string (a)
2260 (when (string-match "\\`$[<>]" a)
2261 (let ((arrow (string-to-char (substring a 1))))
2262 ;; Fake a high number to make sure this is sorted at the end.
2263 (setq a (org-table-formula-handle-first/last-rc a))
2264 (setq a (format "$%d" (+ 10000
2265 (if (= arrow ?<) -1000 0)
2266 (string-to-number (substring a 1)))))))
2267 (when (string-match
2268 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2270 (concat
2271 (if (match-end 2)
2272 (format "@%05d" (string-to-number (match-string 2 a))) "")
2273 (if (match-end 4)
2274 (format "$%05d" (string-to-number (match-string 4 a))) "")
2275 (if (match-end 5)
2276 (concat "@@" (match-string 5 a))))))
2278 (defun org-table-formula-less-p (a b)
2279 "Compare two formulas for sorting."
2280 (let ((as (org-table-formula-make-cmp-string (car a)))
2281 (bs (org-table-formula-make-cmp-string (car b))))
2282 (and as bs (string< as bs))))
2284 ;;;###autoload
2285 (defun org-table-get-stored-formulas (&optional noerror)
2286 "Return an alist with the stored formulas directly after current table."
2287 (interactive) ;; FIXME interactive?
2288 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2289 (save-excursion
2290 (goto-char (org-table-end))
2291 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2292 (setq strings (org-split-string (org-match-string-no-properties 2)
2293 " *:: *"))
2294 (while (setq string (pop strings))
2295 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2296 (setq scol (if (match-end 2)
2297 (match-string 2 string)
2298 (match-string 1 string))
2299 scol (if (member (string-to-char scol) '(?< ?>))
2300 (concat "$" scol) scol)
2301 eq (match-string 3 string)
2302 eq-alist (cons (cons scol eq) eq-alist))
2303 (if (member scol seen)
2304 (if noerror
2305 (progn
2306 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2307 (ding)
2308 (sit-for 2))
2309 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2310 (push scol seen))))))
2311 (nreverse eq-alist)))
2313 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2314 "Modify the equations after the table structure has been edited.
2315 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2316 For all numbers larger than LIMIT, shift them by DELTA."
2317 (save-excursion
2318 (goto-char (org-table-end))
2319 (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2320 (let ((msg "The formulas in #+TBLFM have been updated")
2321 (re (concat key "\\([0-9]+\\)"))
2322 (re2
2323 (when remove
2324 (if (or (equal key "$") (equal key "$LR"))
2325 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2326 (regexp-quote key) remove)
2327 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2328 s n a)
2329 (when remove
2330 (while (re-search-forward re2 (point-at-eol) t)
2331 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2332 (if (equal (char-before (match-beginning 0)) ?.)
2333 (user-error
2334 "Change makes TBLFM term %s invalid, use undo to recover"
2335 (match-string 0))
2336 (replace-match "")))))
2337 (while (re-search-forward re (point-at-eol) t)
2338 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2339 (setq s (match-string 1) n (string-to-number s))
2340 (cond
2341 ((setq a (assoc s replace))
2342 (replace-match (concat key (cdr a)) t t)
2343 (message msg))
2344 ((and limit (> n limit))
2345 (replace-match (concat key (int-to-string (+ n delta))) t t)
2346 (message msg))))))
2347 (forward-line))))
2349 ;;;###autoload
2350 (defun org-table-maybe-eval-formula ()
2351 "Check if the current field starts with \"=\" or \":=\".
2352 If yes, store the formula and apply it."
2353 ;; We already know we are in a table. Get field will only return a formula
2354 ;; when appropriate. It might return a separator line, but no problem.
2355 (when org-table-formula-evaluate-inline
2356 (let* ((field (org-trim (or (org-table-get-field) "")))
2357 named eq)
2358 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2359 (setq named (equal (string-to-char field) ?:)
2360 eq (match-string 1 field))
2361 (if (or (fboundp 'calc-eval)
2362 (equal (substring eq 0 (min 2 (length eq))) "'("))
2363 (org-table-eval-formula (if named '(4) nil)
2364 (org-table-formula-from-user eq))
2365 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2367 (defvar org-recalc-commands nil
2368 "List of commands triggering the recalculation of a line.
2369 Will be filled automatically during use.")
2371 (defvar org-recalc-marks
2372 '((" " . "Unmarked: no special line, no automatic recalculation")
2373 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2374 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2375 ("!" . "Column name definition line. Reference in formula as $name.")
2376 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2377 ("_" . "Names for values in row below this one.")
2378 ("^" . "Names for values in row above this one.")))
2380 ;;;###autoload
2381 (defun org-table-rotate-recalc-marks (&optional newchar)
2382 "Rotate the recalculation mark in the first column.
2383 If in any row, the first field is not consistent with a mark,
2384 insert a new column for the markers.
2385 When there is an active region, change all the lines in the region,
2386 after prompting for the marking character.
2387 After each change, a message will be displayed indicating the meaning
2388 of the new mark."
2389 (interactive)
2390 (unless (org-at-table-p) (user-error "Not at a table"))
2391 (let* ((region (org-region-active-p))
2392 (l1 (and region
2393 (save-excursion (goto-char (region-beginning))
2394 (copy-marker (line-beginning-position)))))
2395 (l2 (and region
2396 (save-excursion (goto-char (region-end))
2397 (copy-marker (line-beginning-position)))))
2398 (l (copy-marker (line-beginning-position)))
2399 (col (org-table-current-column))
2400 (newchar (if region
2401 (char-to-string
2402 (read-char-exclusive
2403 "Change region to what mark? Type # * ! $ or SPC: "))
2404 newchar))
2405 (no-special-column
2406 (save-excursion
2407 (goto-char (org-table-begin))
2408 (re-search-forward
2409 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
2410 (when (and newchar (not (assoc newchar org-recalc-marks)))
2411 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2412 newchar))
2413 (when l1 (goto-char l1))
2414 (save-excursion
2415 (beginning-of-line)
2416 (unless (looking-at org-table-dataline-regexp)
2417 (user-error "Not at a table data line")))
2418 (when no-special-column
2419 (org-table-goto-column 1)
2420 (org-table-insert-column))
2421 (let ((previous-line-end (line-end-position))
2422 (newchar
2423 (save-excursion
2424 (beginning-of-line)
2425 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2426 (newchar)
2427 (t (cadr (member (match-string 1)
2428 (append (mapcar #'car org-recalc-marks)
2429 '(" ")))))))))
2430 ;; Rotate mark in first row.
2431 (org-table-get-field 1 (format " %s " newchar))
2432 ;; Rotate marks in additional rows if a region is active.
2433 (when region
2434 (save-excursion
2435 (forward-line)
2436 (while (<= (point) l2)
2437 (when (looking-at org-table-dataline-regexp)
2438 (org-table-get-field 1 (format " %s " newchar)))
2439 (forward-line))))
2440 ;; Only align if rotation actually changed lines' length.
2441 (when (/= previous-line-end (line-end-position)) (org-table-align)))
2442 (goto-char l)
2443 (org-table-goto-column (if no-special-column (1+ col) col))
2444 (when l1 (set-marker l1 nil))
2445 (when l2 (set-marker l2 nil))
2446 (set-marker l nil)
2447 (when (org-called-interactively-p 'interactive)
2448 (message "%s" (cdr (assoc newchar org-recalc-marks))))))
2450 ;;;###autoload
2451 (defun org-table-analyze ()
2452 "Analyze table at point and store results.
2454 This function sets up the following dynamically scoped variables:
2456 `org-table-column-name-regexp',
2457 `org-table-column-names',
2458 `org-table-current-begin-pos',
2459 `org-table-current-line-types',
2460 `org-table-current-ncol',
2461 `org-table-dlines',
2462 `org-table-hlines',
2463 `org-table-local-parameters',
2464 `org-table-named-field-locations'."
2465 (let ((beg (org-table-begin))
2466 (end (org-table-end)))
2467 (save-excursion
2468 (goto-char beg)
2469 ;; Extract column names.
2470 (setq org-table-column-names nil)
2471 (when (save-excursion
2472 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
2473 (let ((c 1))
2474 (dolist (name (org-split-string (match-string 1) " *| *"))
2475 (incf c)
2476 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
2477 (push (cons name (int-to-string c)) org-table-column-names)))))
2478 (setq org-table-column-names (nreverse org-table-column-names))
2479 (setq org-table-column-name-regexp
2480 (format "\\$\\(%s\\)\\>"
2481 (regexp-opt (mapcar #'car org-table-column-names) t)))
2482 ;; Extract local parameters.
2483 (setq org-table-local-parameters nil)
2484 (save-excursion
2485 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2486 (dolist (field (org-split-string (match-string 1) " *| *"))
2487 (when (string-match
2488 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2489 (push (cons (match-string 1 field) (match-string 2 field))
2490 org-table-local-parameters)))))
2491 ;; Update named fields locations. We minimize `count-lines'
2492 ;; processing by storing last known number of lines in LAST.
2493 (setq org-table-named-field-locations nil)
2494 (save-excursion
2495 (let ((last (cons (point) 0)))
2496 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2497 (let ((c (match-string 1))
2498 (fields (org-split-string (match-string 2) " *| *")))
2499 (save-excursion
2500 (forward-line (if (equal c "_") 1 -1))
2501 (let ((fields1
2502 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2503 (org-split-string (match-string 1) " *| *")))
2504 (line (incf (cdr last) (count-lines (car last) (point))))
2505 (col 1))
2506 (setcar last (point)) ; Update last known position.
2507 (while (and fields fields1)
2508 (let ((field (pop fields))
2509 (v (pop fields1)))
2510 (incf col)
2511 (when (and (stringp field)
2512 (stringp v)
2513 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2514 field))
2515 (push (cons field v) org-table-local-parameters)
2516 (push (list field line col)
2517 org-table-named-field-locations))))))))))
2518 ;; Re-use existing markers when possible.
2519 (if (markerp org-table-current-begin-pos)
2520 (move-marker org-table-current-begin-pos (point))
2521 (setq org-table-current-begin-pos (point-marker)))
2522 ;; Analyze the line types.
2523 (let ((l 0) hlines dlines types)
2524 (while (looking-at "[ \t]*|\\(-\\)?")
2525 (push (if (match-end 1) 'hline 'dline) types)
2526 (if (match-end 1) (push l hlines) (push l dlines))
2527 (forward-line)
2528 (incf l))
2529 (push 'hline types) ; Add an imaginary extra hline to the end.
2530 (setq org-table-current-line-types (apply #'vector (nreverse types)))
2531 (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
2532 (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
2533 ;; Get the number of columns from the first data line in table.
2534 (goto-char beg)
2535 (forward-line (aref org-table-dlines 0))
2536 (let* ((fields
2537 (org-split-string
2538 (buffer-substring (line-beginning-position) (line-end-position))
2539 "[ \t]*|[ \t]*"))
2540 (nfields (length fields))
2541 al al2)
2542 (setq org-table-current-ncol nfields)
2543 (let ((last-dline
2544 (aref org-table-dlines (1- (length org-table-dlines)))))
2545 (dotimes (i nfields)
2546 (let ((column (1+ i)))
2547 (push (list (format "LR%d" column) last-dline column) al)
2548 (push (cons (format "LR%d" column) (nth i fields)) al2))))
2549 (setq org-table-named-field-locations
2550 (append org-table-named-field-locations al))
2551 (setq org-table-local-parameters
2552 (append org-table-local-parameters al2))))))
2554 (defun org-table-goto-field (ref &optional create-column-p)
2555 "Move point to a specific field in the current table.
2557 REF is either the name of a field its absolute reference, as
2558 a string. No column is created unless CREATE-COLUMN-P is
2559 non-nil. If it is a function, it is called with the column
2560 number as its argument as is used as a predicate to know if the
2561 column can be created.
2563 This function assumes the table is already analyzed (i.e., using
2564 `org-table-analyze')."
2565 (let* ((coordinates
2566 (cond
2567 ((cdr (assoc ref org-table-named-field-locations)))
2568 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
2569 (list (condition-case nil
2570 (aref org-table-dlines
2571 (string-to-number (match-string 1 ref)))
2572 (error (user-error "Invalid row number in %s" ref)))
2573 (string-to-number (match-string 2 ref))))
2574 (t (user-error "Unknown field: %s" ref))))
2575 (line (car coordinates))
2576 (column (nth 1 coordinates))
2577 (create-new-column (if (functionp create-column-p)
2578 (funcall create-column-p column)
2579 create-column-p)))
2580 (when coordinates
2581 (goto-char org-table-current-begin-pos)
2582 (forward-line line)
2583 (org-table-goto-column column nil create-new-column))))
2585 ;;;###autoload
2586 (defun org-table-maybe-recalculate-line ()
2587 "Recompute the current line if marked for it, and if we haven't just done it."
2588 (interactive)
2589 (and org-table-allow-automatic-line-recalculation
2590 (not (and (memq last-command org-recalc-commands)
2591 (eq org-last-recalc-line (line-beginning-position))))
2592 (save-excursion (beginning-of-line 1)
2593 (looking-at org-table-auto-recalculate-regexp))
2594 (org-table-recalculate) t))
2596 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2597 (defsubst org-set-calc-mode (var &optional value)
2598 (if (stringp var)
2599 (setq var (assoc var '(("D" calc-angle-mode deg)
2600 ("R" calc-angle-mode rad)
2601 ("F" calc-prefer-frac t)
2602 ("S" calc-symbolic-mode t)))
2603 value (nth 2 var) var (nth 1 var)))
2604 (if (memq var org-tbl-calc-modes)
2605 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2606 (cons var (cons value org-tbl-calc-modes)))
2607 org-tbl-calc-modes)
2609 ;;;###autoload
2610 (defun org-table-eval-formula (&optional arg equation
2611 suppress-align suppress-const
2612 suppress-store suppress-analysis)
2613 "Replace the table field value at the cursor by the result of a calculation.
2615 This function makes use of Dave Gillespie's Calc package, in my view the
2616 most exciting program ever written for GNU Emacs. So you need to have Calc
2617 installed in order to use this function.
2619 In a table, this command replaces the value in the current field with the
2620 result of a formula. It also installs the formula as the \"current\" column
2621 formula, by storing it in a special line below the table. When called
2622 with a `C-u' prefix, the current field must be a named field, and the
2623 formula is installed as valid in only this specific field.
2625 When called with two `C-u' prefixes, insert the active equation
2626 for the field back into the current field, so that it can be
2627 edited there. This is useful in order to use \\[org-table-show-reference]
2628 to check the referenced fields.
2630 When called, the command first prompts for a formula, which is read in
2631 the minibuffer. Previously entered formulas are available through the
2632 history list, and the last used formula is offered as a default.
2633 These stored formulas are adapted correctly when moving, inserting, or
2634 deleting columns with the corresponding commands.
2636 The formula can be any algebraic expression understood by the Calc package.
2637 For details, see the Org-mode manual.
2639 This function can also be called from Lisp programs and offers
2640 additional arguments: EQUATION can be the formula to apply. If this
2641 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2642 used to speed-up recursive calls by by-passing unnecessary aligns.
2643 SUPPRESS-CONST suppresses the interpretation of constants in the
2644 formula, assuming that this has been done already outside the function.
2645 SUPPRESS-STORE means the formula should not be stored, either because
2646 it is already stored, or because it is a modified equation that should
2647 not overwrite the stored one."
2648 (interactive "P")
2649 (org-table-check-inside-data-field)
2650 (or suppress-analysis (org-table-analyze))
2651 (if (equal arg '(16))
2652 (let ((eq (org-table-current-field-formula)))
2653 (or eq (user-error "No equation active for current field"))
2654 (org-table-get-field nil eq)
2655 (org-table-align)
2656 (setq org-table-may-need-update t))
2657 (let* (fields
2658 (ndown (if (integerp arg) arg 1))
2659 (org-table-automatic-realign nil)
2660 (case-fold-search nil)
2661 (down (> ndown 1))
2662 (formula (if (and equation suppress-store)
2663 equation
2664 (org-table-get-formula equation (equal arg '(4)))))
2665 (n0 (org-table-current-column))
2666 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2667 (numbers nil) ; was a variable, now fixed default
2668 (keep-empty nil)
2669 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2670 duration duration-output-format)
2671 ;; Parse the format string. Since we have a lot of modes, this is
2672 ;; a lot of work. However, I think calc still uses most of the time.
2673 (if (string-match ";" formula)
2674 (let ((tmp (org-split-string formula ";")))
2675 (setq formula (car tmp)
2676 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2677 (nth 1 tmp)))
2678 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2679 (setq c (string-to-char (match-string 1 fmt))
2680 n (string-to-number (match-string 2 fmt)))
2681 (if (= c ?p)
2682 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2683 (setq org-tbl-calc-modes
2684 (org-set-calc-mode
2685 'calc-float-format
2686 (list (cdr (assoc c '((?n . float) (?f . fix)
2687 (?s . sci) (?e . eng))))
2688 n))))
2689 (setq fmt (replace-match "" t t fmt)))
2690 (if (string-match "T" fmt)
2691 (setq duration t numbers t
2692 duration-output-format nil
2693 fmt (replace-match "" t t fmt)))
2694 (if (string-match "t" fmt)
2695 (setq duration t
2696 duration-output-format org-table-duration-custom-format
2697 numbers t
2698 fmt (replace-match "" t t fmt)))
2699 (if (string-match "N" fmt)
2700 (setq numbers t
2701 fmt (replace-match "" t t fmt)))
2702 (if (string-match "L" fmt)
2703 (setq literal t
2704 fmt (replace-match "" t t fmt)))
2705 (if (string-match "E" fmt)
2706 (setq keep-empty t
2707 fmt (replace-match "" t t fmt)))
2708 (while (string-match "[DRFS]" fmt)
2709 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2710 (setq fmt (replace-match "" t t fmt)))
2711 (unless (string-match "\\S-" fmt)
2712 (setq fmt nil))))
2713 (if (and (not suppress-const) org-table-formula-use-constants)
2714 (setq formula (org-table-formula-substitute-names formula)))
2715 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2716 (while (> ndown 0)
2717 (setq fields (org-split-string
2718 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2719 " *| *"))
2720 ;; replace fields with duration values if relevant
2721 (if duration
2722 (setq fields
2723 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2724 fields)))
2725 (if (eq numbers t)
2726 (setq fields (mapcar
2727 (lambda (x)
2728 (if (string-match "\\S-" x)
2729 (number-to-string (string-to-number x))
2731 fields)))
2732 (setq ndown (1- ndown))
2733 (setq form (copy-sequence formula)
2734 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2735 (if (and lispp literal) (setq lispp 'literal))
2737 ;; Insert row and column number of formula result field
2738 (while (string-match "[@$]#" form)
2739 (setq form
2740 (replace-match
2741 (format "%d"
2742 (save-match-data
2743 (if (equal (substring form (match-beginning 0)
2744 (1+ (match-beginning 0)))
2745 "@")
2746 (org-table-current-dline)
2747 (org-table-current-column))))
2748 t t form)))
2750 ;; Check for old vertical references
2751 (org-table--error-on-old-row-references form)
2752 ;; Insert remote references
2753 (setq form (org-table-remote-reference-indirection form))
2754 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2755 (setq form
2756 (replace-match
2757 (save-match-data
2758 (org-table-make-reference
2759 (let ((rmtrng (org-table-get-remote-range
2760 (match-string 1 form) (match-string 2 form))))
2761 (if duration
2762 (if (listp rmtrng)
2763 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2764 (org-table-time-string-to-seconds rmtrng))
2765 rmtrng))
2766 keep-empty numbers lispp))
2767 t t form)))
2768 ;; Insert complex ranges
2769 (while (and (string-match org-table-range-regexp form)
2770 (> (length (match-string 0 form)) 1))
2771 (setq formrg
2772 (save-match-data
2773 (org-table-get-range
2774 (match-string 0 form) org-table-current-begin-pos n0)))
2775 (setq formrpl
2776 (save-match-data
2777 (org-table-make-reference
2778 ;; possibly handle durations
2779 (if duration
2780 (if (listp formrg)
2781 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2782 (org-table-time-string-to-seconds formrg))
2783 formrg)
2784 keep-empty numbers lispp)))
2785 (if (not (save-match-data
2786 (string-match (regexp-quote form) formrpl)))
2787 (setq form (replace-match formrpl t t form))
2788 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2789 ;; Insert simple ranges, i.e. included in the current row.
2790 (while (string-match
2791 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2792 form)
2793 (setq form
2794 (replace-match
2795 (save-match-data
2796 (org-table-make-reference
2797 (cl-subseq fields
2798 (+ (if (match-end 2) n0 0)
2799 (string-to-number (match-string 1 form))
2801 (+ (if (match-end 4) n0 0)
2802 (string-to-number (match-string 3 form))))
2803 keep-empty numbers lispp))
2804 t t form)))
2805 (setq form0 form)
2806 ;; Insert the references to fields in same row
2807 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2808 (setq n (+ (string-to-number (match-string 1 form))
2809 (if (match-end 2) n0 0))
2810 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2811 formrpl (save-match-data
2812 (org-table-make-reference
2813 x keep-empty numbers lispp)))
2814 (when (or (not x)
2815 (save-match-data
2816 (string-match (regexp-quote formula) formrpl)))
2817 (user-error "Invalid field specifier \"%s\""
2818 (match-string 0 form)))
2819 (setq form (replace-match formrpl t t form)))
2821 (if lispp
2822 (setq ev (condition-case nil
2823 (eval (eval (read form)))
2824 (error "#ERROR"))
2825 ev (if (numberp ev) (number-to-string ev) ev)
2826 ev (if duration (org-table-time-seconds-to-string
2827 (string-to-number ev)
2828 duration-output-format) ev))
2829 (or (fboundp 'calc-eval)
2830 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2831 ;; Use <...> time-stamps so that Calc can handle them
2832 (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
2833 (setq form (replace-match "<\\1>" nil nil form)))
2834 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2835 (when (string-match org-ts-regexp2 form)
2836 (let* ((ts (match-string 0 form))
2837 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2838 (system-time-locale "C")
2839 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2840 (cdr org-time-stamp-formats))
2841 (car org-time-stamp-formats))))
2842 (setq form (replace-match (format-time-string tf tsp) t t form))))
2844 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2845 form
2846 (calc-eval (cons form org-tbl-calc-modes)
2847 (when (and (not keep-empty) numbers) 'num)))
2848 ev (if duration (org-table-time-seconds-to-string
2849 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2850 (string-to-number (org-table-time-string-to-seconds ev))
2851 (string-to-number ev))
2852 duration-output-format)
2853 ev)))
2855 (when org-table-formula-debug
2856 (with-output-to-temp-buffer "*Substitution History*"
2857 (princ (format "Substitution history of formula
2858 Orig: %s
2859 $xyz-> %s
2860 @r$c-> %s
2861 $1-> %s\n" orig formula form0 form))
2862 (if (consp ev)
2863 (princ (format " %s^\nError: %s"
2864 (make-string (car ev) ?\-) (nth 1 ev)))
2865 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2866 ev (or fmt "NONE")
2867 (if fmt (format fmt (string-to-number ev)) ev)))))
2868 (setq bw (get-buffer-window "*Substitution History*"))
2869 (org-fit-window-to-buffer bw)
2870 (unless (and (org-called-interactively-p 'any) (not ndown))
2871 (unless (let (inhibit-redisplay)
2872 (y-or-n-p "Debugging Formula. Continue to next? "))
2873 (org-table-align)
2874 (user-error "Abort"))
2875 (delete-window bw)
2876 (message "")))
2877 (when (consp ev) (setq fmt nil ev "#ERROR"))
2878 (org-table-justify-field-maybe
2879 (format org-table-formula-field-format
2880 (if fmt (format fmt (string-to-number ev)) ev)))
2881 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2882 (call-interactively 'org-return)
2883 (setq ndown 0)))
2884 (and down (org-table-maybe-recalculate-line))
2885 (or suppress-align (and org-table-may-need-update
2886 (org-table-align))))))
2888 (defun org-table-put-field-property (prop value)
2889 (save-excursion
2890 (put-text-property (progn (skip-chars-backward "^|") (point))
2891 (progn (skip-chars-forward "^|") (point))
2892 prop value)))
2894 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2895 "Get a calc vector from a column, according to descriptor DESC.
2897 Optional arguments TBEG and COL can give the beginning of the table and
2898 the current column, to avoid unnecessary parsing.
2900 HIGHLIGHT means just highlight the range.
2902 When CORNERS-ONLY is set, only return the corners of the range as
2903 a list (line1 column1 line2 column2) where line1 and line2 are
2904 line numbers relative to beginning of table, or TBEG, and column1
2905 and column2 are table column numbers."
2906 (let* ((desc (if (eq (string-to-char desc) ?@) desc (concat "@" desc)))
2907 (col (or col (org-table-current-column)))
2908 (tbeg (or tbeg (org-table-begin)))
2909 (thisline (count-lines tbeg (line-beginning-position))))
2910 (unless (string-match org-table-range-regexp desc)
2911 (user-error "Invalid table range specifier `%s'" desc))
2912 (let ((rangep (match-end 3))
2913 (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
2914 (or (save-match-data
2915 (and (org-string-nw-p r)
2916 (org-table--descriptor-line r thisline)))
2917 thisline)))
2918 (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
2919 (or (save-match-data
2920 (and (org-string-nw-p r)
2921 (org-table--descriptor-line r thisline)))
2922 thisline)))
2923 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
2924 (if (or (not c) (= (string-to-number c) 0)) col
2925 (+ (string-to-number c)
2926 (if (memq (string-to-char c) '(?- ?+)) col 0)))))
2927 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
2928 (if (or (not c) (= (string-to-number c) 0)) col
2929 (+ (string-to-number c)
2930 (if (memq (string-to-char c) '(?- ?+)) col 0))))))
2931 (save-excursion
2932 (if (and (not corners-only)
2933 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2934 ;; Just one field.
2935 (progn
2936 (forward-line (- r1 thisline))
2937 (while (not (looking-at org-table-dataline-regexp))
2938 (forward-line))
2939 (prog1 (org-trim (org-table-get-field c1))
2940 (when highlight (org-table-highlight-rectangle))))
2941 ;; A range, return a vector. First sort the numbers to get
2942 ;; a regular rectangle.
2943 (let ((first-row (min r1 r2))
2944 (last-row (max r1 r2))
2945 (first-column (min c1 c2))
2946 (last-column (max c1 c2)))
2947 (if corners-only (list first-row first-column last-row last-column)
2948 ;; Copy the range values into a list.
2949 (forward-line (- first-row thisline))
2950 (while (not (looking-at org-table-dataline-regexp))
2951 (forward-line)
2952 (incf first-row))
2953 (org-table-goto-column first-column)
2954 (let ((beg (point)))
2955 (forward-line (- last-row first-row))
2956 (while (not (looking-at org-table-dataline-regexp))
2957 (forward-line -1))
2958 (org-table-goto-column last-column)
2959 (let ((end (point)))
2960 (when highlight
2961 (org-table-highlight-rectangle
2962 beg (progn (skip-chars-forward "^|\n") (point))))
2963 ;; Return string representation of calc vector.
2964 (mapcar #'org-trim
2965 (apply #'append
2966 (org-table-copy-region beg end))))))))))))
2968 (defun org-table--descriptor-line (desc cline)
2969 "Return relative line number corresponding to descriptor DESC.
2970 The cursor is currently in relative line number CLINE."
2971 (if (string-match "\\`[0-9]+\\'" desc)
2972 (aref org-table-dlines (string-to-number desc))
2973 (when (or (not (string-match
2974 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
2975 ;; 1 2 3 4 5 6
2976 desc))
2977 (and (not (match-end 3)) (not (match-end 6)))
2978 (and (match-end 3) (match-end 6) (not (match-end 5))))
2979 (user-error "Invalid row descriptor `%s'" desc))
2980 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
2981 (hdir (match-string 2 desc))
2982 (odir (match-string 5 desc))
2983 (on (and (match-end 6) (string-to-number (match-string 6 desc))))
2984 (rel (and (match-end 6)
2985 (or (and (match-end 1) (not (match-end 3)))
2986 (match-end 5)))))
2987 (when (and hn (not hdir))
2988 (setq cline 0)
2989 (setq hdir "+")
2990 (when (eq (aref org-table-current-line-types 0) 'hline) (decf hn)))
2991 (when (and (not hn) on (not odir)) (user-error "Should never happen"))
2992 (when hn
2993 (setq cline
2994 (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
2995 (when on
2996 (setq cline
2997 (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
2998 cline)))
3000 (defun org-table--row-type (type n i backwards relative desc)
3001 "Return relative line of Nth row with type TYPE.
3002 Search starts from relative line I. When BACKWARDS in non-nil,
3003 look before I. When RELATIVE is non-nil, the reference is
3004 relative. DESC is the original descriptor that started the
3005 search, as a string."
3006 (let ((l (length org-table-current-line-types)))
3007 (catch :exit
3008 (dotimes (_ n)
3009 (while (and (incf i (if backwards -1 1))
3010 (>= i 0)
3011 (< i l)
3012 (not (eq (aref org-table-current-line-types i) type))
3013 ;; We are going to cross a hline. Check if this is
3014 ;; an authorized move.
3015 (cond
3016 ((not relative))
3017 ((not (eq (aref org-table-current-line-types i) 'hline)))
3018 ((eq org-table-relative-ref-may-cross-hline t))
3019 ((eq org-table-relative-ref-may-cross-hline 'error)
3020 (user-error "Row descriptor %s crosses hline" desc))
3021 (t (decf i (if backwards -1 1)) ; Step back.
3022 (throw :exit nil)))))))
3023 (cond ((or (< i 0) (>= i l))
3024 (user-error "Row descriptor %s leads outside table" desc))
3025 ;; The last hline doesn't exist. Instead, point to last row
3026 ;; in table.
3027 ((= i (1- l)) (1- i))
3028 (t i))))
3030 (defun org-table--error-on-old-row-references (s)
3031 (when (string-match "&[-+0-9I]" s)
3032 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3034 (defun org-table-make-reference (elements keep-empty numbers lispp)
3035 "Convert list ELEMENTS to something appropriate to insert into formula.
3036 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3037 NUMBERS indicates that everything should be converted to numbers.
3038 LISPP non-nil means to return something appropriate for a Lisp
3039 list, `literal' is for the format specifier L."
3040 ;; Calc nan (not a number) is used for the conversion of the empty
3041 ;; field to a reference for several reasons: (i) It is accepted in a
3042 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3043 ;; (ii) In a single field (not in range) it can be distinguished
3044 ;; from "(nan)" which is the reference made from a single field
3045 ;; containing "nan".
3046 (if (stringp elements)
3047 ;; field reference
3048 (if lispp
3049 (if (eq lispp 'literal)
3050 elements
3051 (if (and (eq elements "") (not keep-empty))
3053 (prin1-to-string
3054 (if numbers (string-to-number elements) elements))))
3055 (if (string-match "\\S-" elements)
3056 (progn
3057 (when numbers (setq elements (number-to-string
3058 (string-to-number elements))))
3059 (concat "(" elements ")"))
3060 (if (or (not keep-empty) numbers) "(0)" "nan")))
3061 ;; range reference
3062 (unless keep-empty
3063 (setq elements
3064 (delq nil
3065 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3066 elements))))
3067 (setq elements (or elements '())) ; if delq returns nil then we need '()
3068 (if lispp
3069 (mapconcat
3070 (lambda (x)
3071 (if (eq lispp 'literal)
3073 (prin1-to-string (if numbers (string-to-number x) x))))
3074 elements " ")
3075 (concat "[" (mapconcat
3076 (lambda (x)
3077 (if (string-match "\\S-" x)
3078 (if numbers
3079 (number-to-string (string-to-number x))
3081 (if (or (not keep-empty) numbers) "0" "nan")))
3082 elements
3083 ",") "]"))))
3085 (defun org-table-message-once-per-second (t1 &rest args)
3086 "If there has been more than one second since T1, display message.
3087 ARGS are passed as arguments to the `message' function. Returns
3088 current time if a message is printed, otherwise returns T1. If
3089 T1 is nil, always messages."
3090 (let ((curtime (current-time)))
3091 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3092 (progn (apply 'message args)
3093 curtime)
3094 t1)))
3096 ;;;###autoload
3097 (defun org-table-recalculate (&optional all noalign)
3098 "Recalculate the current table line by applying all stored formulas.
3099 With prefix arg ALL, do this for all lines in the table.
3100 With the prefix argument ALL is `(16)' \
3101 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3102 it is the symbol `iterate', recompute the table until it no longer changes.
3103 If NOALIGN is not nil, do not re-align the table after the computations
3104 are done. This is typically used internally to save time, if it is
3105 known that the table will be realigned a little later anyway."
3106 (interactive "P")
3107 (unless (memq this-command org-recalc-commands)
3108 (push this-command org-recalc-commands))
3109 (unless (org-at-table-p) (user-error "Not at a table"))
3110 (if (or (eq all 'iterate) (equal all '(16)))
3111 (org-table-iterate)
3112 (org-table-analyze)
3113 (let* ((eqlist (sort (org-table-get-stored-formulas)
3114 (lambda (a b) (string< (car a) (car b)))))
3115 (eqlist1 (copy-sequence eqlist))
3116 (inhibit-redisplay (not debug-on-error))
3117 (line-re org-table-dataline-regexp)
3118 (log-first-time (current-time))
3119 (log-last-time log-first-time)
3120 (cnt 0)
3121 beg end eqlnum eqlname)
3122 ;; Insert constants in all formulas
3123 (when eqlist
3124 (org-table-save-field
3125 (setq eqlist
3126 (mapcar
3127 (lambda (x)
3128 (when (string-match "\\`@-?I+" (car x))
3129 (user-error "Can't assign to hline relative reference"))
3130 (when (string-match "\\`$[<>]" (car x))
3131 (let ((old-lhs (car x)))
3132 (setq x
3133 (cons
3134 (substring
3135 (org-table-formula-handle-first/last-rc old-lhs)
3137 (cdr x)))
3138 (when (assoc (car x) eqlist1)
3139 (user-error "\"%s=\" formula tries to overwrite \
3140 existing formula for column %s"
3141 old-lhs
3142 (car x)))))
3143 (cons (org-table-formula-handle-first/last-rc (car x))
3144 (org-table-formula-substitute-names
3145 (org-table-formula-handle-first/last-rc (cdr x)))))
3146 eqlist))
3147 ;; Split the equation list.
3148 (dolist (eq eqlist)
3149 (if (<= (string-to-char (car eq)) ?9)
3150 (push eq eqlnum)
3151 (push eq eqlname)))
3152 (setq eqlnum (nreverse eqlnum))
3153 ;; Expand ranges in lhs of formulas
3154 (setq eqlname (org-table-expand-lhs-ranges (nreverse eqlname)))
3155 ;; Get the correct line range to process
3156 (if all
3157 (progn
3158 (setq end (copy-marker (org-table-end)))
3159 (goto-char (setq beg org-table-current-begin-pos))
3160 (cond
3161 ((re-search-forward org-table-calculate-mark-regexp end t)
3162 ;; This is a table with marked lines, compute selected
3163 ;; lines.
3164 (setq line-re org-table-recalculate-regexp))
3165 ;; Move forward to the first non-header line.
3166 ((and (re-search-forward org-table-dataline-regexp end t)
3167 (re-search-forward org-table-hline-regexp end t)
3168 (re-search-forward org-table-dataline-regexp end t))
3169 (setq beg (match-beginning 0)))
3170 ;; Just leave BEG where it is.
3171 (t nil)))
3172 (setq beg (line-beginning-position)
3173 end (copy-marker (line-beginning-position 2))))
3174 (goto-char beg)
3175 ;; Mark named fields untouchable. Also check if several
3176 ;; field/range formulas try to set the same field.
3177 (remove-text-properties beg end '(org-untouchable t))
3178 (let ((current-line (count-lines org-table-current-begin-pos
3179 (line-beginning-position)))
3180 seen-fields)
3181 (dolist (eq eqlname)
3182 (let* ((name (car eq))
3183 (location (assoc name org-table-named-field-locations))
3184 (eq-line (or (nth 1 location)
3185 (and (string-match "\\`@\\([0-9]+\\)" name)
3186 (aref org-table-dlines
3187 (string-to-number
3188 (match-string 1 name))))))
3189 (reference
3190 (if location
3191 ;; Turn field coordinates associated to NAME
3192 ;; into an absolute reference.
3193 (format "@%d$%d"
3194 (org-table-line-to-dline eq-line)
3195 (nth 2 location))
3196 name)))
3197 (when (member reference seen-fields)
3198 (user-error "Several field/range formulas try to set %s"
3199 reference))
3200 (push reference seen-fields)
3201 (when (or all (eq eq-line current-line))
3202 (org-table-goto-field name)
3203 (org-table-put-field-property :org-untouchable t)))))
3204 ;; Evaluate the column formulas, but skip fields covered by
3205 ;; field formulas.
3206 (goto-char beg)
3207 (while (re-search-forward line-re end t)
3208 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3209 ;; Unprotected line, recalculate.
3210 (incf cnt)
3211 (when all
3212 (setq log-last-time
3213 (org-table-message-once-per-second
3214 log-last-time
3215 "Re-applying formulas to full table...(line %d)" cnt)))
3216 (if (markerp org-last-recalc-line)
3217 (move-marker org-last-recalc-line (line-beginning-position))
3218 (setq org-last-recalc-line
3219 (copy-marker (line-beginning-position))))
3220 (dolist (entry eqlnum)
3221 (goto-char org-last-recalc-line)
3222 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3223 (unless (get-text-property (point) :org-untouchable)
3224 (org-table-eval-formula
3225 nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
3226 ;; Evaluate the field formulas.
3227 (dolist (eq eqlname)
3228 (let ((reference (car eq))
3229 (formula (cdr eq)))
3230 (setq log-last-time
3231 (org-table-message-once-per-second
3232 (and all log-last-time)
3233 "Re-applying formula to field: %s" (car eq)))
3234 (org-table-goto-field
3235 reference
3236 ;; Possibly create a new column, as long as
3237 ;; `org-table-formula-create-columns' allows it.
3238 (let ((column-count (progn (end-of-line)
3239 (1- (org-table-current-column)))))
3240 `(lambda (column)
3241 (when (> column 1000)
3242 (user-error "Formula column target too large"))
3243 (and (> column ,column-count)
3244 (or (eq org-table-formula-create-columns t)
3245 (and (eq org-table-formula-create-columns 'warn)
3246 (progn
3247 (org-display-warning
3248 "Out-of-bounds formula added columns")
3250 (and (eq org-table-formula-create-columns 'prompt)
3251 (yes-or-no-p
3252 "Out-of-bounds formula. Add columns? ")))))))
3253 (org-table-eval-formula nil formula t t t t))))
3254 ;; Clean up markers and internal text property.
3255 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3256 (set-marker end nil)
3257 (unless noalign
3258 (when org-table-may-need-update (org-table-align))
3259 (when all
3260 (org-table-message-once-per-second
3261 log-first-time "Re-applying formulas to %d lines... done" cnt)))
3262 (org-table-message-once-per-second
3263 (and all log-first-time) "Re-applying formulas... done")))))
3265 ;;;###autoload
3266 (defun org-table-iterate (&optional arg)
3267 "Recalculate the table until it does not change anymore.
3268 The maximum number of iterations is 10, but you can choose a different value
3269 with the prefix ARG."
3270 (interactive "P")
3271 (let ((imax (if arg (prefix-numeric-value arg) 10))
3272 (i 0)
3273 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3274 thistbl)
3275 (catch 'exit
3276 (while (< i imax)
3277 (setq i (1+ i))
3278 (org-table-recalculate 'all)
3279 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3280 (if (not (string= lasttbl thistbl))
3281 (setq lasttbl thistbl)
3282 (if (> i 1)
3283 (message "Convergence after %d iterations" i)
3284 (message "Table was already stable"))
3285 (throw 'exit t)))
3286 (user-error "No convergence after %d iterations" i))))
3288 ;;;###autoload
3289 (defun org-table-recalculate-buffer-tables ()
3290 "Recalculate all tables in the current buffer."
3291 (interactive)
3292 (save-excursion
3293 (save-restriction
3294 (widen)
3295 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3297 ;;;###autoload
3298 (defun org-table-iterate-buffer-tables ()
3299 "Iterate all tables in the buffer, to converge inter-table dependencies."
3300 (interactive)
3301 (let* ((imax 10)
3302 (i imax)
3303 (checksum (md5 (buffer-string)))
3305 (save-excursion
3306 (save-restriction
3307 (widen)
3308 (catch 'exit
3309 (while (> i 0)
3310 (setq i (1- i))
3311 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3312 (if (equal checksum (setq c1 (md5 (buffer-string))))
3313 (progn
3314 (message "Convergence after %d iterations" (- imax i))
3315 (throw 'exit t))
3316 (setq checksum c1)))
3317 (user-error "No convergence after %d iterations" imax))))))
3319 (defun org-table-calc-current-TBLFM (&optional arg)
3320 "Apply the #+TBLFM in the line at point to the table."
3321 (interactive "P")
3322 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3323 (let ((formula (buffer-substring
3324 (line-beginning-position)
3325 (line-end-position))))
3326 (save-excursion
3327 ;; Insert a temporary formula at right after the table
3328 (goto-char (org-table-TBLFM-begin))
3329 (let ((s (point-marker)))
3330 (insert formula "\n")
3331 (let ((e (point-marker)))
3332 ;; Recalculate the table.
3333 (beginning-of-line 0) ; move to the inserted line
3334 (skip-chars-backward " \r\n\t")
3335 (unwind-protect
3336 (org-call-with-arg #'org-table-recalculate (or arg t))
3337 ;; Delete the formula inserted temporarily.
3338 (delete-region s e)
3339 (set-marker s nil)
3340 (set-marker e nil)))))))
3342 (defun org-table-TBLFM-begin ()
3343 "Find the beginning of the TBLFM lines and return its position.
3344 Return nil when the beginning of TBLFM line was not found."
3345 (save-excursion
3346 (when (progn (forward-line 1)
3347 (re-search-backward org-table-TBLFM-begin-regexp nil t))
3348 (line-beginning-position 2))))
3350 (defun org-table-expand-lhs-ranges (equations)
3351 "Expand list of formulas.
3352 If some of the RHS in the formulas are ranges or a row reference, expand
3353 them to individual field equations for each field."
3354 (let (res)
3355 (dolist (e equations (nreverse res))
3356 (let ((lhs (car e))
3357 (rhs (cdr e)))
3358 (cond
3359 ((string-match "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
3360 ;; This just refers to one fixed field.
3361 (push e res))
3362 ((string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
3363 ;; This just refers to one fixed named field.
3364 (push e res))
3365 ((string-match "\\`@[0-9]+\\'" lhs)
3366 (dotimes (ic org-table-current-ncol)
3367 (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
3368 rhs)
3369 res)))
3371 (let* ((range (org-table-get-range
3372 lhs org-table-current-begin-pos 1 nil 'corners))
3373 (r1 (org-table-line-to-dline (nth 0 range)))
3374 (c1 (nth 1 range))
3375 (r2 (org-table-line-to-dline (nth 2 range) 'above))
3376 (c2 (nth 3 range)))
3377 (loop for ir from r1 to r2 do
3378 (loop for ic from c1 to c2 do
3379 (push
3380 (cons (propertize (format "@%d$%d" ir ic) :orig-eqn e)
3381 rhs)
3382 res))))))))))
3384 (defun org-table-formula-handle-first/last-rc (s)
3385 "Replace @<, @>, $<, $> with first/last row/column of the table.
3386 So @< and $< will always be replaced with @1 and $1, respectively.
3387 The advantage of these special markers are that structure editing of
3388 the table will not change them, while @1 and $1 will be modified
3389 when a line/row is swapped out of that privileged position. So for
3390 formulas that use a range of rows or columns, it may often be better
3391 to anchor the formula with \"I\" row markers, or to offset from the
3392 borders of the table using the @< @> $< $> makers."
3393 (let (n nmax len char (start 0))
3394 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3395 s start)
3396 (if (match-end 3)
3397 (setq start (match-end 3))
3398 (setq nmax (if (equal (match-string 1 s) "@")
3399 (1- (length org-table-dlines))
3400 org-table-current-ncol)
3401 len (- (match-end 2) (match-beginning 2))
3402 char (string-to-char (match-string 2 s))
3403 n (if (= char ?<)
3405 (- nmax len -1)))
3406 (if (or (< n 1) (> n nmax))
3407 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3408 (match-string 0 s) s))
3409 (setq start (match-beginning 0))
3410 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3413 (defun org-table-formula-substitute-names (f)
3414 "Replace $const with values in string F."
3415 (let ((start 0)
3416 (pp (/= (string-to-char f) ?'))
3417 (duration (org-string-match-p ";.*[Tt].*\\'" f))
3418 (new (replace-regexp-in-string ; Check for column names.
3419 org-table-column-name-regexp
3420 (lambda (m)
3421 (concat "$" (cdr (assoc (match-string 1 m)
3422 org-table-column-names))))
3423 f t t)))
3424 ;; Parameters and constants.
3425 (while (setq start
3426 (string-match
3427 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3428 new start))
3429 (if (match-end 2) (setq start (match-end 2))
3430 (incf start)
3431 ;; When a duration is expected, convert value on the fly.
3432 (let ((value
3433 (save-match-data
3434 (let ((v (org-table-get-constant (match-string 1 new))))
3435 (if (and (org-string-nw-p v) duration)
3436 (org-table-time-string-to-seconds v)
3437 v)))))
3438 (when value
3439 (setq new (replace-match
3440 (concat (and pp "(") value (and pp ")")) t t new))))))
3441 (if org-table-formula-debug (org-propertize new :orig-formula f)) new))
3443 (defun org-table-get-constant (const)
3444 "Find the value for a parameter or constant in a formula.
3445 Parameters get priority."
3446 (or (cdr (assoc const org-table-local-parameters))
3447 (cdr (assoc const org-table-formula-constants-local))
3448 (cdr (assoc const org-table-formula-constants))
3449 (and (fboundp 'constants-get) (constants-get const))
3450 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3451 (org-entry-get nil (substring const 5) 'inherit))
3452 "#UNDEFINED_NAME"))
3454 (defvar org-table-fedit-map
3455 (let ((map (make-sparse-keymap)))
3456 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3457 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3458 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3459 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3460 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3461 (org-defkey map "\C-c?" 'org-table-show-reference)
3462 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3463 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3464 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3465 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3466 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3467 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3468 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3469 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3470 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3471 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3472 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3473 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3474 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3475 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3476 map))
3478 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3479 '("Edit-Formulas"
3480 ["Finish and Install" org-table-fedit-finish t]
3481 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3482 ["Abort" org-table-fedit-abort t]
3483 "--"
3484 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3485 ["Complete Lisp Symbol" lisp-complete-symbol t]
3486 "--"
3487 "Shift Reference at Point"
3488 ["Up" org-table-fedit-ref-up t]
3489 ["Down" org-table-fedit-ref-down t]
3490 ["Left" org-table-fedit-ref-left t]
3491 ["Right" org-table-fedit-ref-right t]
3493 "Change Test Row for Column Formulas"
3494 ["Up" org-table-fedit-line-up t]
3495 ["Down" org-table-fedit-line-down t]
3496 "--"
3497 ["Scroll Table Window" org-table-fedit-scroll t]
3498 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3499 ["Show Table Grid" org-table-fedit-toggle-coordinates
3500 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3501 org-table-overlay-coordinates)]
3502 "--"
3503 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3504 :style toggle :selected org-table-buffer-is-an]))
3506 (defvar org-pos)
3508 ;;;###autoload
3509 (defun org-table-edit-formulas ()
3510 "Edit the formulas of the current table in a separate buffer."
3511 (interactive)
3512 (when (save-excursion (beginning-of-line)
3513 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3514 (beginning-of-line 0))
3515 (unless (org-at-table-p) (user-error "Not at a table"))
3516 (org-table-analyze)
3517 (let ((key (org-table-current-field-formula 'key 'noerror))
3518 (eql (sort (org-table-get-stored-formulas 'noerror)
3519 #'org-table-formula-less-p))
3520 (pos (point-marker))
3521 (startline 1)
3522 (wc (current-window-configuration))
3523 (sel-win (selected-window))
3524 (titles '((column . "# Column Formulas\n")
3525 (field . "# Field and Range Formulas\n")
3526 (named . "# Named Field Formulas\n"))))
3527 (org-switch-to-buffer-other-window "*Edit Formulas*")
3528 (erase-buffer)
3529 ;; Keep global-font-lock-mode from turning on font-lock-mode
3530 (let ((font-lock-global-modes '(not fundamental-mode)))
3531 (fundamental-mode))
3532 (setq-local font-lock-global-modes (list 'not major-mode))
3533 (setq-local org-pos pos)
3534 (setq-local org-window-configuration wc)
3535 (setq-local org-selected-window sel-win)
3536 (use-local-map org-table-fedit-map)
3537 (org-add-hook 'post-command-hook #'org-table-fedit-post-command t t)
3538 (easy-menu-add org-table-fedit-menu)
3539 (setq startline (org-current-line))
3540 (dolist (entry eql)
3541 (let* ((type (cond
3542 ((string-match "\\`$[<>]" (car entry)) 'column)
3543 ((equal (string-to-char (car entry)) ?@) 'field)
3544 ((string-match "\\'[0-9]" (car entry)) 'column)
3545 (t 'named)))
3546 (title (assq type titles)))
3547 (when title
3548 (unless (bobp) (insert "\n"))
3549 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3550 (setq titles (remove title titles)))
3551 (when (equal key (car entry)) (setq startline (org-current-line)))
3552 (let ((s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3553 (car entry) " = " (cdr entry) "\n")))
3554 (remove-text-properties 0 (length s) '(face nil) s)
3555 (insert s))))
3556 (when (eq org-table-use-standard-references t)
3557 (org-table-fedit-toggle-ref-type))
3558 (org-goto-line startline)
3559 (message
3560 (substitute-command-keys "\\<org-mode-map>\
3561 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3562 See menu for more commands."))))
3564 (defun org-table-fedit-post-command ()
3565 (when (not (memq this-command '(lisp-complete-symbol)))
3566 (let ((win (selected-window)))
3567 (save-excursion
3568 (ignore-errors (org-table-show-reference))
3569 (select-window win)))))
3571 (defun org-table-formula-to-user (s)
3572 "Convert a formula from internal to user representation."
3573 (if (eq org-table-use-standard-references t)
3574 (org-table-convert-refs-to-an s)
3577 (defun org-table-formula-from-user (s)
3578 "Convert a formula from user to internal representation."
3579 (if org-table-use-standard-references
3580 (org-table-convert-refs-to-rc s)
3583 (defun org-table-convert-refs-to-rc (s)
3584 "Convert spreadsheet references from A7 to @7$28.
3585 Works for single references, but also for entire formulas and even the
3586 full TBLFM line."
3587 (let ((start 0))
3588 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3589 (cond
3590 ((match-end 3)
3591 ;; format match, just advance
3592 (setq start (match-end 0)))
3593 ((and (> (match-beginning 0) 0)
3594 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3595 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3596 ;; 3.e5 or something like this.
3597 (setq start (match-end 0)))
3598 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3599 ;; (member (match-string 1 s)
3600 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3602 ;; function name, just advance
3603 (setq start (match-end 0)))
3605 (setq start (match-beginning 0)
3606 s (replace-match
3607 (if (equal (match-string 2 s) "&")
3608 (format "$%d" (org-letters-to-number (match-string 1 s)))
3609 (format "@%d$%d"
3610 (string-to-number (match-string 2 s))
3611 (org-letters-to-number (match-string 1 s))))
3612 t t s)))))
3615 (defun org-table-convert-refs-to-an (s)
3616 "Convert spreadsheet references from to @7$28 to AB7.
3617 Works for single references, but also for entire formulas and even the
3618 full TBLFM line."
3619 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3620 (setq s (replace-match
3621 (format "%s%d"
3622 (org-number-to-letters
3623 (string-to-number (match-string 2 s)))
3624 (string-to-number (match-string 1 s)))
3625 t t s)))
3626 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3627 (setq s (replace-match (concat "\\1"
3628 (org-number-to-letters
3629 (string-to-number (match-string 2 s))) "&")
3630 t nil s)))
3633 (defun org-letters-to-number (s)
3634 "Convert a base 26 number represented by letters into an integer.
3635 For example: AB -> 28."
3636 (let ((n 0))
3637 (setq s (upcase s))
3638 (while (> (length s) 0)
3639 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3640 s (substring s 1)))
3643 (defun org-number-to-letters (n)
3644 "Convert an integer into a base 26 number represented by letters.
3645 For example: 28 -> AB."
3646 (let ((s ""))
3647 (while (> n 0)
3648 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3649 n (/ (1- n) 26)))
3652 (defun org-table-time-string-to-seconds (s)
3653 "Convert a time string into numerical duration in seconds.
3654 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3655 If S is a string representing a number, keep this number."
3656 (if (equal s "")
3658 (let (hour minus min sec res)
3659 (cond
3660 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3661 (setq minus (< 0 (length (match-string 1 s)))
3662 hour (string-to-number (match-string 2 s))
3663 min (string-to-number (match-string 3 s))
3664 sec (string-to-number (match-string 4 s)))
3665 (if minus
3666 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3667 (setq res (+ (* hour 3600) (* min 60) sec))))
3668 ((and (not (string-match org-ts-regexp-both s))
3669 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3670 (setq minus (< 0 (length (match-string 1 s)))
3671 hour (string-to-number (match-string 2 s))
3672 min (string-to-number (match-string 3 s)))
3673 (if minus
3674 (setq res (- (+ (* hour 3600) (* min 60))))
3675 (setq res (+ (* hour 3600) (* min 60)))))
3676 (t (setq res (string-to-number s))))
3677 (number-to-string res))))
3679 (defun org-table-time-seconds-to-string (secs &optional output-format)
3680 "Convert a number of seconds to a time string.
3681 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3682 minutes or seconds."
3683 (let* ((secs0 (abs secs))
3684 (res
3685 (cond ((eq output-format 'days)
3686 (format "%.3f" (/ (float secs0) 86400)))
3687 ((eq output-format 'hours)
3688 (format "%.2f" (/ (float secs0) 3600)))
3689 ((eq output-format 'minutes)
3690 (format "%.1f" (/ (float secs0) 60)))
3691 ((eq output-format 'seconds)
3692 (format "%d" secs0))
3693 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3694 (if (< secs 0) (concat "-" res) res)))
3696 (defun org-table-fedit-convert-buffer (function)
3697 "Convert all references in this buffer, using FUNCTION."
3698 (let ((origin (copy-marker (line-beginning-position))))
3699 (goto-char (point-min))
3700 (while (not (eobp))
3701 (insert (funcall function (buffer-substring (point) (line-end-position))))
3702 (delete-region (point) (line-end-position))
3703 (forward-line))
3704 (goto-char origin)
3705 (set-marker origin nil)))
3707 (defun org-table-fedit-toggle-ref-type ()
3708 "Convert all references in the buffer from B3 to @3$2 and back."
3709 (interactive)
3710 (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
3711 (org-table-fedit-convert-buffer
3712 (if org-table-buffer-is-an
3713 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3714 (message "Reference type switched to %s"
3715 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3717 (defun org-table-fedit-ref-up ()
3718 "Shift the reference at point one row/hline up."
3719 (interactive)
3720 (org-table-fedit-shift-reference 'up))
3721 (defun org-table-fedit-ref-down ()
3722 "Shift the reference at point one row/hline down."
3723 (interactive)
3724 (org-table-fedit-shift-reference 'down))
3725 (defun org-table-fedit-ref-left ()
3726 "Shift the reference at point one field to the left."
3727 (interactive)
3728 (org-table-fedit-shift-reference 'left))
3729 (defun org-table-fedit-ref-right ()
3730 "Shift the reference at point one field to the right."
3731 (interactive)
3732 (org-table-fedit-shift-reference 'right))
3734 (defun org-table-fedit-shift-reference (dir)
3735 (cond
3736 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3737 (if (memq dir '(left right))
3738 (org-rematch-and-replace 1 (eq dir 'left))
3739 (user-error "Cannot shift reference in this direction")))
3740 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3741 ;; A B3-like reference
3742 (if (memq dir '(up down))
3743 (org-rematch-and-replace 2 (eq dir 'up))
3744 (org-rematch-and-replace 1 (eq dir 'left))))
3745 ((org-in-regexp
3746 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3747 ;; An internal reference
3748 (if (memq dir '(up down))
3749 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3750 (org-rematch-and-replace 5 (eq dir 'left))))))
3752 (defun org-rematch-and-replace (n &optional decr hline)
3753 "Re-match the group N, and replace it with the shifted reference."
3754 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3755 (goto-char (match-beginning n))
3756 (and (looking-at (regexp-quote (match-string n)))
3757 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3758 t t)))
3760 (defun org-table-shift-refpart (ref &optional decr hline)
3761 "Shift a reference part REF.
3762 If DECR is set, decrease the references row/column, else increase.
3763 If HLINE is set, this may be a hline reference, it certainly is not
3764 a translation reference."
3765 (save-match-data
3766 (let* ((sign (string-match "^[-+]" ref)) n)
3768 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3769 (cond
3770 ((and hline (string-match "^I+" ref))
3771 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3772 (setq n (+ n (if decr -1 1)))
3773 (if (= n 0) (setq n (+ n (if decr -1 1))))
3774 (if sign
3775 (setq sign (if (< n 0) "-" "+") n (abs n))
3776 (setq n (max 1 n)))
3777 (concat sign (make-string n ?I)))
3779 ((string-match "^[0-9]+" ref)
3780 (setq n (string-to-number (concat sign ref)))
3781 (setq n (+ n (if decr -1 1)))
3782 (if sign
3783 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3784 (number-to-string (max 1 n))))
3786 ((string-match "^[a-zA-Z]+" ref)
3787 (org-number-to-letters
3788 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3790 (t (user-error "Cannot shift reference"))))))
3792 (defun org-table-fedit-toggle-coordinates ()
3793 "Toggle the display of coordinates in the referenced table."
3794 (interactive)
3795 (let ((pos (marker-position org-pos)))
3796 (with-current-buffer (marker-buffer org-pos)
3797 (save-excursion
3798 (goto-char pos)
3799 (org-table-toggle-coordinate-overlays)))))
3801 (defun org-table-fedit-finish (&optional arg)
3802 "Parse the buffer for formula definitions and install them.
3803 With prefix ARG, apply the new formulas to the table."
3804 (interactive "P")
3805 (org-table-remove-rectangle-highlight)
3806 (if org-table-use-standard-references
3807 (progn
3808 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3809 (setq org-table-buffer-is-an nil)))
3810 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3811 (goto-char (point-min))
3812 (while (re-search-forward
3813 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3814 nil t)
3815 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3816 form (match-string 3))
3817 (setq form (org-trim form))
3818 (when (not (equal form ""))
3819 (while (string-match "[ \t]*\n[ \t]*" form)
3820 (setq form (replace-match " " t t form)))
3821 (when (assoc var eql)
3822 (user-error "Double formulas for %s" var))
3823 (push (cons var form) eql)))
3824 (setq org-pos nil)
3825 (set-window-configuration org-window-configuration)
3826 (select-window sel-win)
3827 (goto-char pos)
3828 (unless (org-at-table-p)
3829 (user-error "Lost table position - cannot install formulas"))
3830 (org-table-store-formulas eql)
3831 (move-marker pos nil)
3832 (kill-buffer "*Edit Formulas*")
3833 (if arg
3834 (org-table-recalculate 'all)
3835 (message "New formulas installed - press C-u C-c C-c to apply."))))
3837 (defun org-table-fedit-abort ()
3838 "Abort editing formulas, without installing the changes."
3839 (interactive)
3840 (org-table-remove-rectangle-highlight)
3841 (let ((pos org-pos) (sel-win org-selected-window))
3842 (set-window-configuration org-window-configuration)
3843 (select-window sel-win)
3844 (goto-char pos)
3845 (move-marker pos nil)
3846 (message "Formula editing aborted without installing changes")))
3848 (defun org-table-fedit-lisp-indent ()
3849 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3850 (interactive)
3851 (let ((pos (point)) beg end ind)
3852 (beginning-of-line 1)
3853 (cond
3854 ((looking-at "[ \t]")
3855 (goto-char pos)
3856 (call-interactively 'lisp-indent-line))
3857 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3858 ((not (fboundp 'pp-buffer))
3859 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3860 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3861 (goto-char (- (match-end 0) 2))
3862 (setq beg (point))
3863 (setq ind (make-string (current-column) ?\ ))
3864 (condition-case nil (forward-sexp 1)
3865 (error
3866 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3867 (setq end (point))
3868 (save-restriction
3869 (narrow-to-region beg end)
3870 (if (eq last-command this-command)
3871 (progn
3872 (goto-char (point-min))
3873 (setq this-command nil)
3874 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3875 (replace-match " ")))
3876 (pp-buffer)
3877 (untabify (point-min) (point-max))
3878 (goto-char (1+ (point-min)))
3879 (while (re-search-forward "^." nil t)
3880 (beginning-of-line 1)
3881 (insert ind))
3882 (goto-char (point-max))
3883 (org-delete-backward-char 1)))
3884 (goto-char beg))
3885 (t nil))))
3887 (defvar org-show-positions nil)
3889 (defun org-table-show-reference (&optional local)
3890 "Show the location/value of the $ expression at point."
3891 (interactive)
3892 (org-table-remove-rectangle-highlight)
3893 (when local (org-table-analyze))
3894 (catch 'exit
3895 (let ((pos (if local (point) org-pos))
3896 (table-start (if local org-table-current-begin-pos (org-table-begin)))
3897 (face2 'highlight)
3898 (org-inhibit-highlight-removal t)
3899 (win (selected-window))
3900 (org-show-positions nil)
3901 var name e what match dest)
3902 (setq what (cond
3903 ((org-in-regexp "^@[0-9]+[ \t=]")
3904 (setq match (concat (substring (match-string 0) 0 -1)
3905 "$1.."
3906 (substring (match-string 0) 0 -1)
3907 "$100"))
3908 'range)
3909 ((or (org-in-regexp org-table-range-regexp2)
3910 (org-in-regexp org-table-translate-regexp)
3911 (org-in-regexp org-table-range-regexp))
3912 (setq match
3913 (save-match-data
3914 (org-table-convert-refs-to-rc (match-string 0))))
3915 'range)
3916 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3917 ((org-in-regexp "\\$[0-9]+") 'column)
3918 ((not local) nil)
3919 (t (user-error "No reference at point")))
3920 match (and what (or match (match-string 0))))
3921 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3922 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3923 'secondary-selection))
3924 (org-add-hook 'before-change-functions
3925 #'org-table-remove-rectangle-highlight)
3926 (when (eq what 'name) (setq var (substring match 1)))
3927 (when (eq what 'range)
3928 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
3929 (setq match (org-table-formula-substitute-names match)))
3930 (unless local
3931 (save-excursion
3932 (end-of-line)
3933 (re-search-backward "^\\S-" nil t)
3934 (beginning-of-line)
3935 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3936 \\([0-9]+\\|&\\)\\) *=")
3937 (setq dest
3938 (save-match-data
3939 (org-table-convert-refs-to-rc (match-string 1))))
3940 (org-table-add-rectangle-overlay
3941 (match-beginning 1) (match-end 1) face2))))
3942 (if (and (markerp pos) (marker-buffer pos))
3943 (if (get-buffer-window (marker-buffer pos))
3944 (select-window (get-buffer-window (marker-buffer pos)))
3945 (org-switch-to-buffer-other-window (get-buffer-window
3946 (marker-buffer pos)))))
3947 (goto-char pos)
3948 (org-table-force-dataline)
3949 (when dest
3950 (setq name (substring dest 1))
3951 (cond
3952 ((org-string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3953 (org-table-goto-field dest))
3954 ((org-string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
3955 dest)
3956 (org-table-goto-field dest))
3957 (t (org-table-goto-column (string-to-number name))))
3958 (move-marker pos (point))
3959 (org-table-highlight-rectangle nil nil face2))
3960 (cond
3961 ((equal dest match))
3962 ((not match))
3963 ((eq what 'range)
3964 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
3965 ((setq e (assoc var org-table-named-field-locations))
3966 (org-table-goto-field var)
3967 (org-table-highlight-rectangle)
3968 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3969 ((setq e (assoc var org-table-column-names))
3970 (org-table-goto-column (string-to-number (cdr e)))
3971 (org-table-highlight-rectangle)
3972 (goto-char table-start)
3973 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3974 (org-table-end) t)
3975 (progn
3976 (goto-char (match-beginning 1))
3977 (org-table-highlight-rectangle)
3978 (message "Named column (column %s)" (cdr e)))
3979 (user-error "Column name not found")))
3980 ((eq what 'column)
3981 ;; Column number.
3982 (org-table-goto-column (string-to-number (substring match 1)))
3983 (org-table-highlight-rectangle)
3984 (message "Column %s" (substring match 1)))
3985 ((setq e (assoc var org-table-local-parameters))
3986 (goto-char table-start)
3987 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3988 (progn
3989 (goto-char (match-beginning 1))
3990 (org-table-highlight-rectangle)
3991 (message "Local parameter."))
3992 (user-error "Parameter not found")))
3993 ((not var) (user-error "No reference at point"))
3994 ((setq e (assoc var org-table-formula-constants-local))
3995 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3996 var (cdr e)))
3997 ((setq e (assoc var org-table-formula-constants))
3998 (message "Constant: $%s=%s in `org-table-formula-constants'."
3999 var (cdr e)))
4000 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4001 (message "Constant: $%s=%s, from `constants.el'%s."
4002 var e (format " (%s units)" constants-unit-system)))
4003 (t (user-error "Undefined name $%s" var)))
4004 (goto-char pos)
4005 (when (and org-show-positions
4006 (not (memq this-command '(org-table-fedit-scroll
4007 org-table-fedit-scroll-down))))
4008 (push pos org-show-positions)
4009 (push table-start org-show-positions)
4010 (let ((min (apply 'min org-show-positions))
4011 (max (apply 'max org-show-positions)))
4012 (set-window-start (selected-window) min)
4013 (goto-char max)
4014 (or (pos-visible-in-window-p max)
4015 (set-window-start (selected-window) max))))
4016 (select-window win))))
4018 (defun org-table-force-dataline ()
4019 "Make sure the cursor is in a dataline in a table."
4020 (unless (save-excursion
4021 (beginning-of-line 1)
4022 (looking-at org-table-dataline-regexp))
4023 (let* ((re org-table-dataline-regexp)
4024 (p1 (save-excursion (re-search-forward re nil 'move)))
4025 (p2 (save-excursion (re-search-backward re nil 'move))))
4026 (cond ((and p1 p2)
4027 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4028 p1 p2)))
4029 ((or p1 p2) (goto-char (or p1 p2)))
4030 (t (user-error "No table dataline around here"))))))
4032 (defun org-table-fedit-line-up ()
4033 "Move cursor one line up in the window showing the table."
4034 (interactive)
4035 (org-table-fedit-move 'previous-line))
4037 (defun org-table-fedit-line-down ()
4038 "Move cursor one line down in the window showing the table."
4039 (interactive)
4040 (org-table-fedit-move 'next-line))
4042 (defun org-table-fedit-move (command)
4043 "Move the cursor in the window showing the table.
4044 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4045 (let ((org-table-allow-automatic-line-recalculation nil)
4046 (pos org-pos) (win (selected-window)) p)
4047 (select-window (get-buffer-window (marker-buffer org-pos)))
4048 (setq p (point))
4049 (call-interactively command)
4050 (while (and (org-at-table-p)
4051 (org-at-table-hline-p))
4052 (call-interactively command))
4053 (or (org-at-table-p) (goto-char p))
4054 (move-marker pos (point))
4055 (select-window win)))
4057 (defun org-table-fedit-scroll (N)
4058 (interactive "p")
4059 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4060 (scroll-other-window N)))
4062 (defun org-table-fedit-scroll-down (N)
4063 (interactive "p")
4064 (org-table-fedit-scroll (- N)))
4066 (defvar org-table-rectangle-overlays nil)
4068 (defun org-table-add-rectangle-overlay (beg end &optional face)
4069 "Add a new overlay."
4070 (let ((ov (make-overlay beg end)))
4071 (overlay-put ov 'face (or face 'secondary-selection))
4072 (push ov org-table-rectangle-overlays)))
4074 (defun org-table-highlight-rectangle (&optional beg end face)
4075 "Highlight rectangular region in a table.
4076 When buffer positions BEG and END are provided, use them to
4077 delimit the region to highlight. Otherwise, refer to point. Use
4078 FACE, when non-nil, for the highlight."
4079 (let* ((beg (or beg (point)))
4080 (end (or end (point)))
4081 (b (min beg end))
4082 (e (max beg end))
4083 (start-coordinates
4084 (save-excursion
4085 (goto-char b)
4086 (cons (line-beginning-position) (org-table-current-column))))
4087 (end-coordinates
4088 (save-excursion
4089 (goto-char e)
4090 (cons (line-beginning-position) (org-table-current-column)))))
4091 (when (boundp 'org-show-positions)
4092 (setq org-show-positions (cons b (cons e org-show-positions))))
4093 (goto-char (car start-coordinates))
4094 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4095 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4096 (last-row (car end-coordinates)))
4097 (while (<= (point) last-row)
4098 (when (looking-at org-table-dataline-regexp)
4099 (org-table-goto-column column-start)
4100 (skip-chars-backward "^|\n")
4101 (let ((p (point)))
4102 (org-table-goto-column column-end)
4103 (skip-chars-forward "^|\n")
4104 (org-table-add-rectangle-overlay p (point) face)))
4105 (forward-line)))
4106 (goto-char (car start-coordinates)))
4107 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4109 (defun org-table-remove-rectangle-highlight (&rest _ignore)
4110 "Remove the rectangle overlays."
4111 (unless org-inhibit-highlight-removal
4112 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4113 (mapc 'delete-overlay org-table-rectangle-overlays)
4114 (setq org-table-rectangle-overlays nil)))
4116 (defvar-local org-table-coordinate-overlays nil
4117 "Collects the coordinate grid overlays, so that they can be removed.")
4119 (defun org-table-overlay-coordinates ()
4120 "Add overlays to the table at point, to show row/column coordinates."
4121 (interactive)
4122 (mapc 'delete-overlay org-table-coordinate-overlays)
4123 (setq org-table-coordinate-overlays nil)
4124 (save-excursion
4125 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4126 (goto-char (org-table-begin))
4127 (while (org-at-table-p)
4128 (setq eol (point-at-eol))
4129 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4130 (push ov org-table-coordinate-overlays)
4131 (setq hline (looking-at org-table-hline-regexp))
4132 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4133 (format "%4d" (setq id (1+ id)))))
4134 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4135 (when hline
4136 (setq ic 0)
4137 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4138 (setq beg (1+ (match-beginning 0))
4139 ic (1+ ic)
4140 s1 (concat "$" (int-to-string ic))
4141 s2 (org-number-to-letters ic)
4142 str (if (eq org-table-use-standard-references t) s2 s1))
4143 (setq ov (make-overlay beg (+ beg (length str))))
4144 (push ov org-table-coordinate-overlays)
4145 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4146 (beginning-of-line 2)))))
4148 ;;;###autoload
4149 (defun org-table-toggle-coordinate-overlays ()
4150 "Toggle the display of Row/Column numbers in tables."
4151 (interactive)
4152 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4153 (message "Tables Row/Column numbers display turned %s"
4154 (if org-table-overlay-coordinates "on" "off"))
4155 (if (and (org-at-table-p) org-table-overlay-coordinates)
4156 (org-table-align))
4157 (unless org-table-overlay-coordinates
4158 (mapc 'delete-overlay org-table-coordinate-overlays)
4159 (setq org-table-coordinate-overlays nil)))
4161 ;;;###autoload
4162 (defun org-table-toggle-formula-debugger ()
4163 "Toggle the formula debugger in tables."
4164 (interactive)
4165 (setq org-table-formula-debug (not org-table-formula-debug))
4166 (message "Formula debugging has been turned %s"
4167 (if org-table-formula-debug "on" "off")))
4169 ;;; The orgtbl minor mode
4171 ;; Define a minor mode which can be used in other modes in order to
4172 ;; integrate the org-mode table editor.
4174 ;; This is really a hack, because the org-mode table editor uses several
4175 ;; keys which normally belong to the major mode, for example the TAB and
4176 ;; RET keys. Here is how it works: The minor mode defines all the keys
4177 ;; necessary to operate the table editor, but wraps the commands into a
4178 ;; function which tests if the cursor is currently inside a table. If that
4179 ;; is the case, the table editor command is executed. However, when any of
4180 ;; those keys is used outside a table, the function uses `key-binding' to
4181 ;; look up if the key has an associated command in another currently active
4182 ;; keymap (minor modes, major mode, global), and executes that command.
4183 ;; There might be problems if any of the keys used by the table editor is
4184 ;; otherwise used as a prefix key.
4186 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4187 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4188 ;; addresses this by checking explicitly for both bindings.
4190 ;; The optimized version (see variable `orgtbl-optimized') takes over
4191 ;; all keys which are bound to `self-insert-command' in the *global map*.
4192 ;; Some modes bind other commands to simple characters, for example
4193 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4194 ;; active, this binding is ignored inside tables and replaced with a
4195 ;; modified self-insert.
4198 (defvar orgtbl-mode-map (make-keymap)
4199 "Keymap for `orgtbl-mode'.")
4201 (defvar org-old-auto-fill-inhibit-regexp nil
4202 "Local variable used by `orgtbl-mode'.")
4204 (defconst orgtbl-line-start-regexp
4205 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4206 "Matches a line belonging to an orgtbl.")
4208 (defconst orgtbl-extra-font-lock-keywords
4209 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4210 0 (quote 'org-table) 'prepend))
4211 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4213 ;; Install it as a minor mode.
4214 (put 'orgtbl-mode :included t)
4215 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4217 ;;;###autoload
4218 (define-minor-mode orgtbl-mode
4219 "The `org-mode' table editor as a minor mode for use in other modes."
4220 :lighter " OrgTbl" :keymap orgtbl-mode-map
4221 (org-load-modules-maybe)
4222 (cond
4223 ((derived-mode-p 'org-mode)
4224 ;; Exit without error, in case some hook functions calls this
4225 ;; by accident in org-mode.
4226 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4227 (orgtbl-mode
4228 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4229 ;; Make sure we are first in minor-mode-map-alist
4230 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4231 ;; FIXME: maybe it should use emulation-mode-map-alists?
4232 (and c (setq minor-mode-map-alist
4233 (cons c (delq c minor-mode-map-alist)))))
4234 (setq-local org-table-may-need-update t)
4235 (org-add-hook 'before-change-functions 'org-before-change-function
4236 nil 'local)
4237 (setq-local org-old-auto-fill-inhibit-regexp
4238 auto-fill-inhibit-regexp)
4239 (setq-local auto-fill-inhibit-regexp
4240 (if auto-fill-inhibit-regexp
4241 (concat orgtbl-line-start-regexp "\\|"
4242 auto-fill-inhibit-regexp)
4243 orgtbl-line-start-regexp))
4244 (add-to-invisibility-spec '(org-cwidth))
4245 (when (fboundp 'font-lock-add-keywords)
4246 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4247 (org-restart-font-lock))
4248 (easy-menu-add orgtbl-mode-menu))
4250 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4251 (org-table-cleanup-narrow-column-properties)
4252 (org-remove-from-invisibility-spec '(org-cwidth))
4253 (remove-hook 'before-change-functions 'org-before-change-function t)
4254 (when (fboundp 'font-lock-remove-keywords)
4255 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4256 (org-restart-font-lock))
4257 (easy-menu-remove orgtbl-mode-menu)
4258 (force-mode-line-update 'all))))
4260 (defun org-table-cleanup-narrow-column-properties ()
4261 "Remove all properties related to narrow-column invisibility."
4262 (let ((s (point-min)))
4263 (while (setq s (text-property-any s (point-max)
4264 'display org-narrow-column-arrow))
4265 (remove-text-properties s (1+ s) '(display t)))
4266 (setq s (point-min))
4267 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4268 (remove-text-properties s (1+ s) '(org-cwidth t)))
4269 (setq s (point-min))
4270 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4271 (remove-text-properties s (1+ s) '(invisible t)))))
4273 (defun orgtbl-make-binding (fun n &rest keys)
4274 "Create a function for binding in the table minor mode.
4275 FUN is the command to call inside a table. N is used to create a unique
4276 command name. KEYS are keys that should be checked in for a command
4277 to execute outside of tables."
4278 (eval
4279 (list 'defun
4280 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4281 '(arg)
4282 (concat "In tables, run `" (symbol-name fun) "'.\n"
4283 "Outside of tables, run the binding of `"
4284 (mapconcat #'key-description keys "' or `")
4285 "'.")
4286 '(interactive "p")
4287 (list 'if
4288 '(org-at-table-p)
4289 (list 'call-interactively (list 'quote fun))
4290 (list 'let '(orgtbl-mode)
4291 (list 'call-interactively
4292 (append '(or)
4293 (mapcar (lambda (k)
4294 (list 'key-binding k))
4295 keys)
4296 '('orgtbl-error))))))))
4298 (defun orgtbl-error ()
4299 "Error when there is no default binding for a table key."
4300 (interactive)
4301 (user-error "This key has no function outside tables"))
4303 (defun orgtbl-setup ()
4304 "Setup orgtbl keymaps."
4305 (let ((nfunc 0)
4306 (bindings
4307 '(([(meta shift left)] org-table-delete-column)
4308 ([(meta left)] org-table-move-column-left)
4309 ([(meta right)] org-table-move-column-right)
4310 ([(meta shift right)] org-table-insert-column)
4311 ([(meta shift up)] org-table-kill-row)
4312 ([(meta shift down)] org-table-insert-row)
4313 ([(meta up)] org-table-move-row-up)
4314 ([(meta down)] org-table-move-row-down)
4315 ("\C-c\C-w" org-table-cut-region)
4316 ("\C-c\M-w" org-table-copy-region)
4317 ("\C-c\C-y" org-table-paste-rectangle)
4318 ("\C-c\C-w" org-table-wrap-region)
4319 ("\C-c-" org-table-insert-hline)
4320 ("\C-c}" org-table-toggle-coordinate-overlays)
4321 ("\C-c{" org-table-toggle-formula-debugger)
4322 ("\C-m" org-table-next-row)
4323 ([(shift return)] org-table-copy-down)
4324 ("\C-c?" org-table-field-info)
4325 ("\C-c " org-table-blank-field)
4326 ("\C-c+" org-table-sum)
4327 ("\C-c=" org-table-eval-formula)
4328 ("\C-c'" org-table-edit-formulas)
4329 ("\C-c`" org-table-edit-field)
4330 ("\C-c*" org-table-recalculate)
4331 ("\C-c^" org-table-sort-lines)
4332 ("\M-a" org-table-beginning-of-field)
4333 ("\M-e" org-table-end-of-field)
4334 ([(control ?#)] org-table-rotate-recalc-marks)))
4335 elt key fun cmd)
4336 (while (setq elt (pop bindings))
4337 (setq nfunc (1+ nfunc))
4338 (setq key (org-key (car elt))
4339 fun (nth 1 elt)
4340 cmd (orgtbl-make-binding fun nfunc key))
4341 (org-defkey orgtbl-mode-map key cmd))
4343 ;; Special treatment needed for TAB and RET
4344 (org-defkey orgtbl-mode-map [(return)]
4345 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4346 (org-defkey orgtbl-mode-map "\C-m"
4347 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4349 (org-defkey orgtbl-mode-map [(tab)]
4350 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4351 (org-defkey orgtbl-mode-map "\C-i"
4352 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4354 (org-defkey orgtbl-mode-map [(shift tab)]
4355 (orgtbl-make-binding 'org-table-previous-field 104
4356 [(shift tab)] [(tab)] "\C-i"))
4359 (unless (featurep 'xemacs)
4360 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4361 (orgtbl-make-binding 'org-table-previous-field 107
4362 [S-iso-lefttab] [backtab] [(shift tab)]
4363 [(tab)] "\C-i")))
4365 (org-defkey orgtbl-mode-map [backtab]
4366 (orgtbl-make-binding 'org-table-previous-field 108
4367 [backtab] [S-iso-lefttab] [(shift tab)]
4368 [(tab)] "\C-i"))
4370 (org-defkey orgtbl-mode-map "\M-\C-m"
4371 (orgtbl-make-binding 'org-table-wrap-region 105
4372 "\M-\C-m" [(meta return)]))
4373 (org-defkey orgtbl-mode-map [(meta return)]
4374 (orgtbl-make-binding 'org-table-wrap-region 106
4375 [(meta return)] "\M-\C-m"))
4377 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4378 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4380 (when orgtbl-optimized
4381 ;; If the user wants maximum table support, we need to hijack
4382 ;; some standard editing functions
4383 (org-remap orgtbl-mode-map
4384 'self-insert-command 'orgtbl-self-insert-command
4385 'delete-char 'org-delete-char
4386 'delete-backward-char 'org-delete-backward-char)
4387 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4388 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4389 '("OrgTbl"
4390 ["Create or convert" org-table-create-or-convert-from-region
4391 :active (not (org-at-table-p)) :keys "C-c |" ]
4392 "--"
4393 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4394 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4395 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4396 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4397 "--"
4398 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4399 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4400 ["Copy Field from Above"
4401 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4402 "--"
4403 ("Column"
4404 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4405 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4406 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4407 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4408 ("Row"
4409 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4410 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4411 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4412 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4413 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4414 "--"
4415 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4416 ("Rectangle"
4417 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4418 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4419 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4420 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4421 "--"
4422 ("Radio tables"
4423 ["Insert table template" orgtbl-insert-radio-table
4424 (assq major-mode orgtbl-radio-table-templates)]
4425 ["Comment/uncomment table" orgtbl-toggle-comment t])
4426 "--"
4427 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4428 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4429 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4430 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4431 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4432 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4433 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4434 ["Sum Column/Rectangle" org-table-sum
4435 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4436 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4437 ["Debug Formulas"
4438 org-table-toggle-formula-debugger :active (org-at-table-p)
4439 :keys "C-c {"
4440 :style toggle :selected org-table-formula-debug]
4441 ["Show Col/Row Numbers"
4442 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4443 :keys "C-c }"
4444 :style toggle :selected org-table-overlay-coordinates]
4445 "--"
4446 ("Plot"
4447 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4448 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4451 (defun orgtbl-ctrl-c-ctrl-c (arg)
4452 "If the cursor is inside a table, realign the table.
4453 If it is a table to be sent away to a receiver, do it.
4454 With prefix arg, also recompute table."
4455 (interactive "P")
4456 (let ((case-fold-search t) (pos (point)) action)
4457 (save-excursion
4458 (beginning-of-line 1)
4459 (setq action (cond
4460 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4461 ((looking-at "[ \t]*|") pos)
4462 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4463 (cond
4464 ((integerp action)
4465 (goto-char action)
4466 (org-table-maybe-eval-formula)
4467 (if arg
4468 (call-interactively 'org-table-recalculate)
4469 (org-table-maybe-recalculate-line))
4470 (call-interactively 'org-table-align)
4471 (when (orgtbl-send-table 'maybe)
4472 (run-hooks 'orgtbl-after-send-table-hook)))
4473 ((eq action 'recalc)
4474 (save-excursion
4475 (beginning-of-line 1)
4476 (skip-chars-backward " \r\n\t")
4477 (if (org-at-table-p)
4478 (org-call-with-arg 'org-table-recalculate t))))
4479 (t (let (orgtbl-mode)
4480 (call-interactively (key-binding "\C-c\C-c")))))))
4482 (defun orgtbl-create-or-convert-from-region (_arg)
4483 "Create table or convert region to table, if no conflicting binding.
4484 This installs the table binding `C-c |', but only if there is no
4485 conflicting binding to this key outside orgtbl-mode."
4486 (interactive "P")
4487 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4488 (if cmd
4489 (call-interactively cmd)
4490 (call-interactively 'org-table-create-or-convert-from-region))))
4492 (defun orgtbl-tab (arg)
4493 "Justification and field motion for `orgtbl-mode'."
4494 (interactive "P")
4495 (if arg (org-table-edit-field t)
4496 (org-table-justify-field-maybe)
4497 (org-table-next-field)))
4499 (defun orgtbl-ret ()
4500 "Justification and field motion for `orgtbl-mode'."
4501 (interactive)
4502 (if (bobp)
4503 (newline)
4504 (org-table-justify-field-maybe)
4505 (org-table-next-row)))
4507 (defun orgtbl-self-insert-command (N)
4508 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4509 If the cursor is in a table looking at whitespace, the whitespace is
4510 overwritten, and the table is not marked as requiring realignment."
4511 (interactive "p")
4512 (if (and (org-at-table-p)
4514 (and org-table-auto-blank-field
4515 (member last-command
4516 '(orgtbl-hijacker-command-100
4517 orgtbl-hijacker-command-101
4518 orgtbl-hijacker-command-102
4519 orgtbl-hijacker-command-103
4520 orgtbl-hijacker-command-104
4521 orgtbl-hijacker-command-105
4522 yas/expand))
4523 (org-table-blank-field))
4525 (eq N 1)
4526 (looking-at "[^|\n]* +|"))
4527 (let (org-table-may-need-update)
4528 (goto-char (1- (match-end 0)))
4529 (org-delete-backward-char 1)
4530 (goto-char (match-beginning 0))
4531 (self-insert-command N))
4532 (setq org-table-may-need-update t)
4533 (let* (orgtbl-mode
4535 (cmd (or (key-binding
4536 (or (and (listp function-key-map)
4537 (setq a (assoc last-input-event function-key-map))
4538 (cdr a))
4539 (vector last-input-event)))
4540 'self-insert-command)))
4541 (call-interactively cmd)
4542 (if (and org-self-insert-cluster-for-undo
4543 (eq cmd 'self-insert-command))
4544 (if (not (eq last-command 'orgtbl-self-insert-command))
4545 (setq org-self-insert-command-undo-counter 1)
4546 (if (>= org-self-insert-command-undo-counter 20)
4547 (setq org-self-insert-command-undo-counter 1)
4548 (and (> org-self-insert-command-undo-counter 0)
4549 buffer-undo-list
4550 (not (cadr buffer-undo-list)) ; remove nil entry
4551 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4552 (setq org-self-insert-command-undo-counter
4553 (1+ org-self-insert-command-undo-counter))))))))
4555 ;;;###autoload
4556 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4557 "Regular expression matching exponentials as produced by calc.")
4559 (defun orgtbl-gather-send-defs ()
4560 "Gather a plist of :name, :transform, :params for each destination before
4561 a radio table."
4562 (save-excursion
4563 (goto-char (org-table-begin))
4564 (let (rtn)
4565 (beginning-of-line 0)
4566 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4567 (let ((name (org-no-properties (match-string 1)))
4568 (transform (intern (match-string 2)))
4569 (params (if (match-end 3)
4570 (read (concat "(" (match-string 3) ")")))))
4571 (push (list :name name :transform transform :params params)
4572 rtn)
4573 (beginning-of-line 0)))
4574 rtn)))
4576 (defun orgtbl-send-replace-tbl (name txt)
4577 "Find and replace table NAME with TXT."
4578 (save-excursion
4579 (goto-char (point-min))
4580 (unless (re-search-forward
4581 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4582 (user-error "Don't know where to insert translated table"))
4583 (let ((beg (line-beginning-position 2)))
4584 (unless (re-search-forward
4585 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4586 (user-error "Cannot find end of insertion region"))
4587 (beginning-of-line)
4588 (delete-region beg (point)))
4589 (insert txt "\n")))
4591 ;;;###autoload
4592 (defun org-table-to-lisp (&optional txt)
4593 "Convert the table at point to a Lisp structure.
4594 The structure will be a list. Each item is either the symbol `hline'
4595 for a horizontal separator line, or a list of field values as strings.
4596 The table is taken from the parameter TXT, or from the buffer at point."
4597 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4598 (let ((txt (or txt
4599 (buffer-substring-no-properties (org-table-begin)
4600 (org-table-end)))))
4601 (mapcar (lambda (x)
4602 (if (string-match org-table-hline-regexp x) 'hline
4603 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4604 (org-split-string txt "[ \t]*\n[ \t]*"))))
4606 (defun orgtbl-send-table (&optional maybe)
4607 "Send a transformed version of table at point to the receiver position.
4608 With argument MAYBE, fail quietly if no transformation is defined
4609 for this table."
4610 (interactive)
4611 (catch 'exit
4612 (unless (org-at-table-p) (user-error "Not at a table"))
4613 ;; when non-interactive, we assume align has just happened.
4614 (when (org-called-interactively-p 'any) (org-table-align))
4615 (let ((dests (orgtbl-gather-send-defs))
4616 (table (org-table-to-lisp
4617 (buffer-substring-no-properties (org-table-begin)
4618 (org-table-end))))
4619 (ntbl 0))
4620 (unless dests
4621 (if maybe (throw 'exit nil)
4622 (user-error "Don't know how to transform this table")))
4623 (dolist (dest dests)
4624 (let ((name (plist-get dest :name))
4625 (transform (plist-get dest :transform))
4626 (params (plist-get dest :params)))
4627 (unless (fboundp transform)
4628 (user-error "No such transformation function %s" transform))
4629 (orgtbl-send-replace-tbl name (funcall transform table params)))
4630 (incf ntbl))
4631 (message "Table converted and installed at %d receiver location%s"
4632 ntbl (if (> ntbl 1) "s" ""))
4633 (and (> ntbl 0) ntbl))))
4635 (defun org-remove-by-index (list indices &optional i0)
4636 "Remove the elements in LIST with indices in INDICES.
4637 First element has index 0, or I0 if given."
4638 (if (not indices)
4639 list
4640 (if (integerp indices) (setq indices (list indices)))
4641 (setq i0 (1- (or i0 0)))
4642 (delq :rm (mapcar (lambda (x)
4643 (setq i0 (1+ i0))
4644 (if (memq i0 indices) :rm x))
4645 list))))
4647 (defun orgtbl-toggle-comment ()
4648 "Comment or uncomment the orgtbl at point."
4649 (interactive)
4650 (let* ((case-fold-search t)
4651 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4652 (re2 (concat "^" orgtbl-line-start-regexp))
4653 (commented (save-excursion (beginning-of-line 1)
4654 (cond ((looking-at re1) t)
4655 ((looking-at re2) nil)
4656 (t (user-error "Not at an org table")))))
4657 (re (if commented re1 re2))
4658 beg end)
4659 (save-excursion
4660 (beginning-of-line 1)
4661 (while (looking-at re) (beginning-of-line 0))
4662 (beginning-of-line 2)
4663 (setq beg (point))
4664 (while (looking-at re) (beginning-of-line 2))
4665 (setq end (point)))
4666 (comment-region beg end (if commented '(4) nil))))
4668 (defun orgtbl-insert-radio-table ()
4669 "Insert a radio table template appropriate for this major mode."
4670 (interactive)
4671 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4672 (txt (nth 1 e))
4673 name pos)
4674 (unless e (user-error "No radio table setup defined for %s" major-mode))
4675 (setq name (read-string "Table name: "))
4676 (while (string-match "%n" txt)
4677 (setq txt (replace-match name t t txt)))
4678 (or (bolp) (insert "\n"))
4679 (setq pos (point))
4680 (insert txt)
4681 (goto-char pos)))
4683 ;;;###autoload
4684 (defun orgtbl-to-generic (table params)
4685 "Convert the orgtbl-mode TABLE to some other format.
4687 This generic routine can be used for many standard cases.
4689 TABLE is a list, each entry either the symbol `hline' for
4690 a horizontal separator line, or a list of fields for that
4691 line. PARAMS is a property list of parameters that can
4692 influence the conversion.
4694 Valid parameters are:
4696 :backend, :raw
4698 Export back-end used as a basis to transcode elements of the
4699 table, when no specific parameter applies to it. It is also
4700 used to translate cells contents. You can prevent this by
4701 setting :raw property to a non-nil value.
4703 :splice
4705 When non-nil, only convert rows, not the table itself. This is
4706 equivalent to setting to the empty string both :tstart
4707 and :tend, which see.
4709 :skip
4711 When set to an integer N, skip the first N lines of the table.
4712 Horizontal separation lines do count for this parameter!
4714 :skipcols
4716 List of columns that should be skipped. If the table has
4717 a column with calculation marks, that column is automatically
4718 discarded beforehand.
4720 :hline
4722 String to be inserted on horizontal separation lines. May be
4723 nil to ignore these lines altogether.
4725 :sep
4727 Separator between two fields, as a string.
4729 Each in the following group may be either a string or a function
4730 of no arguments returning a string:
4732 :tstart, :tend
4734 Strings to start and end the table. Ignored when :splice is t.
4736 :lstart, :lend
4738 Strings to start and end a new table line.
4740 :llstart, :llend
4742 Strings to start and end the last table line. Default,
4743 respectively, to :lstart and :lend.
4745 Each in the following group may be a string or a function of one
4746 argument (either the cells in the current row, as a list of
4747 strings, or the current cell) returning a string:
4749 :lfmt
4751 Format string for an entire row, with enough %s to capture all
4752 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4754 :llfmt
4756 Format for the entire last line, defaults to :lfmt.
4758 :fmt
4760 A format to be used to wrap the field, should contain %s for
4761 the original field value. For example, to wrap everything in
4762 dollars, you could use :fmt \"$%s$\". This may also be
4763 a property list with column numbers and format strings, or
4764 functions, e.g.,
4766 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4768 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4770 Same as above, specific for the header lines in the table.
4771 All lines before the first hline are treated as header. If
4772 any of these is not present, the data line value is used.
4774 This may be either a string or a function of two arguments:
4776 :efmt
4778 Use this format to print numbers with exponential. The format
4779 should have %s twice for inserting mantissa and exponent, for
4780 example \"%s\\\\times10^{%s}\". This may also be a property
4781 list with column numbers and format strings or functions.
4782 :fmt will still be applied after :efmt."
4783 ;; Make sure `org-export-create-backend' is available.
4784 (require 'ox)
4785 (let* ((backend (plist-get params :backend))
4786 (custom-backend
4787 ;; Build a custom back-end according to PARAMS. Before
4788 ;; defining a translator, check if there is anything to do.
4789 ;; When there isn't, let BACKEND handle the element.
4790 (org-export-create-backend
4791 :parent (or backend 'org)
4792 :transcoders
4793 `((table . ,(org-table--to-generic-table params))
4794 (table-row . ,(org-table--to-generic-row params))
4795 (table-cell . ,(org-table--to-generic-cell params))
4796 ;; Macros are not going to be expanded. However, no
4797 ;; regular back-end has a transcoder for them. We
4798 ;; provide one so they are not ignored, but displayed
4799 ;; as-is instead.
4800 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4801 data info)
4802 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4803 ;; Initialize communication channel in INFO.
4804 (with-temp-buffer
4805 (let ((org-inhibit-startup t)) (org-mode))
4806 (let ((standard-output (current-buffer)))
4807 (dolist (e table)
4808 (cond ((eq e 'hline) (princ "|--\n"))
4809 ((consp e)
4810 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4811 (princ "\n")))))
4812 (setq data
4813 (org-element-map (org-element-parse-buffer) 'table
4814 #'identity nil t))
4815 (setq info (org-export-get-environment backend nil params)))
4816 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4817 (user-error "Unknown :backend value"))
4818 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4819 ;; Handle :skip parameter.
4820 (let ((skip (plist-get info :skip)))
4821 (when skip
4822 (unless (wholenump skip) (user-error "Wrong :skip value"))
4823 (let ((n 0))
4824 (org-element-map data 'table-row
4825 (lambda (row)
4826 (if (>= n skip) t
4827 (org-element-extract-element row)
4828 (incf n)
4829 nil))
4830 nil t))))
4831 ;; Handle :skipcols parameter.
4832 (let ((skipcols (plist-get info :skipcols)))
4833 (when skipcols
4834 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4835 (org-element-map data 'table
4836 (lambda (table)
4837 (let ((specialp (org-export-table-has-special-column-p table)))
4838 (dolist (row (org-element-contents table))
4839 (when (eq (org-element-property :type row) 'standard)
4840 (let ((c 1))
4841 (dolist (cell (nthcdr (if specialp 1 0)
4842 (org-element-contents row)))
4843 (when (memq c skipcols)
4844 (org-element-extract-element cell))
4845 (incf c))))))))))
4846 ;; Since we are going to export using a low-level mechanism,
4847 ;; ignore special column and special rows manually.
4848 (let ((special? (org-export-table-has-special-column-p data))
4849 ignore)
4850 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4851 (lambda (datum)
4852 (when (if (eq (org-element-type datum) 'table-row)
4853 (org-export-table-row-is-special-p datum nil)
4854 (org-export-first-sibling-p datum nil))
4855 (push datum ignore))))
4856 (setq info (plist-put info :ignore-list ignore)))
4857 ;; We use a low-level mechanism to export DATA so as to skip all
4858 ;; usual pre-processing and post-processing, i.e., hooks, filters,
4859 ;; Babel code evaluation, include keywords and macro expansion,
4860 ;; and filters.
4861 (let ((output (org-export-data-with-backend data custom-backend info)))
4862 ;; Remove final newline.
4863 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4865 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4866 (cond ((null value) nil)
4867 ((functionp value) `(funcall ',value ,@args))
4868 ((stringp value)
4869 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4870 (args `(format ,value ,@args))
4871 (t value)))
4872 ((and with-cons (consp value))
4873 `(let ((val (cadr (memq column ',value))))
4874 (cond ((null val) contents)
4875 ((stringp val) (format val ,@args))
4876 ((functionp val) (funcall val ,@args))
4877 (t (user-error "Wrong %s value" ,name)))))
4878 (t (user-error "Wrong %s value" name))))
4880 (defun org-table--to-generic-table (params)
4881 "Return custom table transcoder according to PARAMS.
4882 PARAMS is a plist. See `orgtbl-to-generic' for more
4883 information."
4884 (let ((backend (plist-get params :backend))
4885 (splice (plist-get params :splice))
4886 (tstart (plist-get params :tstart))
4887 (tend (plist-get params :tend)))
4888 `(lambda (table contents info)
4889 (concat
4890 ,(and tstart (not splice)
4891 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4892 ,(if (or (not backend) tstart tend splice) 'contents
4893 `(org-export-with-backend ',backend table contents info))
4894 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4896 (defun org-table--to-generic-row (params)
4897 "Return custom table row transcoder according to PARAMS.
4898 PARAMS is a plist. See `orgtbl-to-generic' for more
4899 information."
4900 (let* ((backend (plist-get params :backend))
4901 (lstart (plist-get params :lstart))
4902 (llstart (plist-get params :llstart))
4903 (hlstart (plist-get params :hlstart))
4904 (hllstart (plist-get params :hllstart))
4905 (lend (plist-get params :lend))
4906 (llend (plist-get params :llend))
4907 (hlend (plist-get params :hlend))
4908 (hllend (plist-get params :hllend))
4909 (lfmt (plist-get params :lfmt))
4910 (llfmt (plist-get params :llfmt))
4911 (hlfmt (plist-get params :hlfmt))
4912 (hllfmt (plist-get params :hllfmt)))
4913 `(lambda (row contents info)
4914 (if (eq (org-element-property :type row) 'rule)
4915 ,(cond
4916 ((plist-member params :hline)
4917 (org-table--generic-apply (plist-get params :hline) ":hline"))
4918 (backend `(org-export-with-backend ',backend row nil info)))
4919 (let ((headerp (org-export-table-row-in-header-p row info))
4920 (lastp (not (org-export-get-next-element row info)))
4921 (last-header-p (org-export-table-row-ends-header-p row info)))
4922 (when contents
4923 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4924 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4925 ;; `:lstart', `:lend' and their relatives.
4926 ,(let ((cells
4927 '(org-element-map row 'table-cell
4928 (lambda (cell)
4929 ;; Export all cells, without separators.
4931 ;; Use `org-export-data-with-backend'
4932 ;; instead of `org-export-data' to eschew
4933 ;; cached values, which
4934 ;; ignore :orgtbl-ignore-sep parameter.
4935 (org-export-data-with-backend
4936 cell
4937 (plist-get info :back-end)
4938 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4939 info)))
4940 `(cond
4941 ,(and hllfmt
4942 `(last-header-p ,(org-table--generic-apply
4943 hllfmt ":hllfmt" nil cells)))
4944 ,(and hlfmt
4945 `(headerp ,(org-table--generic-apply
4946 hlfmt ":hlfmt" nil cells)))
4947 ,(and llfmt
4948 `(lastp ,(org-table--generic-apply
4949 llfmt ":llfmt" nil cells)))
4951 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4952 `(concat
4953 (cond
4954 ,(and
4955 (or hllstart hllend)
4956 `(last-header-p
4957 (concat
4958 ,(org-table--generic-apply hllstart ":hllstart")
4959 contents
4960 ,(org-table--generic-apply hllend ":hllend"))))
4961 ,(and
4962 (or hlstart hlend)
4963 `(headerp
4964 (concat
4965 ,(org-table--generic-apply hlstart ":hlstart")
4966 contents
4967 ,(org-table--generic-apply hlend ":hlend"))))
4968 ,(and
4969 (or llstart llend)
4970 `(lastp
4971 (concat
4972 ,(org-table--generic-apply llstart ":llstart")
4973 contents
4974 ,(org-table--generic-apply llend ":llend"))))
4976 ,(cond
4977 ((or lstart lend)
4978 `(concat
4979 ,(org-table--generic-apply lstart ":lstart")
4980 contents
4981 ,(org-table--generic-apply lend ":lend")))
4982 (backend
4983 `(org-export-with-backend
4984 ',backend row contents info))
4985 (t 'contents)))))))))))))))
4987 (defun org-table--to-generic-cell (params)
4988 "Return custom table cell transcoder according to PARAMS.
4989 PARAMS is a plist. See `orgtbl-to-generic' for more
4990 information."
4991 (let* ((backend (plist-get params :backend))
4992 (efmt (plist-get params :efmt))
4993 (fmt (plist-get params :fmt))
4994 (hfmt (plist-get params :hfmt))
4995 (sep (plist-get params :sep))
4996 (hsep (plist-get params :hsep)))
4997 `(lambda (cell contents info)
4998 (let ((headerp (org-export-table-row-in-header-p
4999 (org-export-get-parent-element cell) info))
5000 (column (1+ (cdr (org-export-table-cell-address cell info)))))
5001 ;; Make sure that contents are exported as Org data when :raw
5002 ;; parameter is non-nil.
5003 ,(when (and backend (plist-get params :raw))
5004 `(setq contents
5005 ;; Since we don't know what are the pseudo object
5006 ;; types defined in backend, we cannot pass them to
5007 ;; `org-element-interpret-data'. As a consequence,
5008 ;; they will be treated as pseudo elements, and
5009 ;; will have newlines appended instead of spaces.
5010 ;; Therefore, we must make sure :post-blank value
5011 ;; is really turned into spaces.
5012 (replace-regexp-in-string
5013 "\n" " "
5014 (org-trim
5015 (org-element-interpret-data
5016 (org-element-contents cell))))))
5017 (when contents
5018 ;; Check if we can apply `:efmt' on CONTENTS.
5019 ,(when efmt
5020 `(when (string-match orgtbl-exp-regexp contents)
5021 (let ((mantissa (match-string 1 contents))
5022 (exponent (match-string 2 contents)))
5023 (setq contents ,(org-table--generic-apply
5024 efmt ":efmt" t 'mantissa 'exponent)))))
5025 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5026 (cond
5027 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5028 hfmt ":hfmt" t 'contents))))
5029 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5030 fmt ":fmt" t 'contents))))))
5031 ;; If a separator is provided, use it instead of BACKEND's.
5032 ;; Separators are ignored when LFMT (or equivalent) is
5033 ;; provided.
5034 ,(cond
5035 ((or hsep sep)
5036 `(if (or ,(and (not sep) '(not headerp))
5037 (plist-get info :orgtbl-ignore-sep)
5038 (not (org-export-get-next-element cell info)))
5039 ,(if (not backend) 'contents
5040 `(org-export-with-backend ',backend cell contents info))
5041 (concat contents
5042 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5043 (or hsep sep)))))
5044 (backend `(org-export-with-backend ',backend cell contents info))
5045 (t 'contents))))))
5047 ;;;###autoload
5048 (defun orgtbl-to-tsv (table params)
5049 "Convert the orgtbl-mode table to TAB separated material."
5050 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5052 ;;;###autoload
5053 (defun orgtbl-to-csv (table params)
5054 "Convert the orgtbl-mode table to CSV material.
5055 This does take care of the proper quoting of fields with comma or quotes."
5056 (orgtbl-to-generic table
5057 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5058 params)))
5060 ;;;###autoload
5061 (defun orgtbl-to-latex (table params)
5062 "Convert the orgtbl-mode TABLE to LaTeX.
5064 TABLE is a list, each entry either the symbol `hline' for
5065 a horizontal separator line, or a list of fields for that line.
5066 PARAMS is a property list of parameters that can influence the
5067 conversion. All parameters from `orgtbl-to-generic' are
5068 supported. It is also possible to use the following ones:
5070 :booktabs
5072 When non-nil, use formal \"booktabs\" style.
5074 :environment
5076 Specify environment to use, as a string. If you use
5077 \"longtable\", you may also want to specify :language property,
5078 as a string, to get proper continuation strings."
5079 (require 'ox-latex)
5080 (orgtbl-to-generic
5081 table
5082 (org-combine-plists
5083 ;; Provide sane default values.
5084 (list :backend 'latex
5085 :latex-default-table-mode 'table
5086 :latex-tables-centered nil
5087 :latex-tables-booktabs (plist-get params :booktabs)
5088 :latex-table-scientific-notation nil
5089 :latex-default-table-environment
5090 (or (plist-get params :environment) "tabular"))
5091 params)))
5093 ;;;###autoload
5094 (defun orgtbl-to-html (table params)
5095 "Convert the orgtbl-mode TABLE to HTML.
5097 TABLE is a list, each entry either the symbol `hline' for
5098 a horizontal separator line, or a list of fields for that line.
5099 PARAMS is a property list of parameters that can influence the
5100 conversion. All parameters from `orgtbl-to-generic' are
5101 supported. It is also possible to use the following one:
5103 :attributes
5105 Attributes and values, as a plist, which will be used in
5106 <table> tag."
5107 (require 'ox-html)
5108 (orgtbl-to-generic
5109 table
5110 (org-combine-plists
5111 ;; Provide sane default values.
5112 (list :backend 'html
5113 :html-table-data-tags '("<td%s>" . "</td>")
5114 :html-table-use-header-tags-for-first-column nil
5115 :html-table-align-individual-fields t
5116 :html-table-row-tags '("<tr>" . "</tr>")
5117 :html-table-attributes
5118 (if (plist-member params :attributes)
5119 (plist-get params :attributes)
5120 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5121 :frame "hsides")))
5122 params)))
5124 ;;;###autoload
5125 (defun orgtbl-to-texinfo (table params)
5126 "Convert the orgtbl-mode TABLE to Texinfo.
5128 TABLE is a list, each entry either the symbol `hline' for
5129 a horizontal separator line, or a list of fields for that line.
5130 PARAMS is a property list of parameters that can influence the
5131 conversion. All parameters from `orgtbl-to-generic' are
5132 supported. It is also possible to use the following one:
5134 :columns
5136 Column widths, as a string. When providing column fractions,
5137 \"@columnfractions\" command can be omitted."
5138 (require 'ox-texinfo)
5139 (let ((output
5140 (orgtbl-to-generic
5141 table
5142 (org-combine-plists
5143 (list :backend 'texinfo
5144 :texinfo-tables-verbatim nil
5145 :texinfo-table-scientific-notation nil)
5146 params)))
5147 (columns (let ((w (plist-get params :columns)))
5148 (cond ((not w) nil)
5149 ((org-string-match-p "{\\|@columnfractions " w) w)
5150 (t (concat "@columnfractions " w))))))
5151 (if (not columns) output
5152 (replace-regexp-in-string
5153 "@multitable \\(.*\\)" columns output t nil 1))))
5155 ;;;###autoload
5156 (defun orgtbl-to-orgtbl (table params)
5157 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5159 TABLE is a list, each entry either the symbol `hline' for
5160 a horizontal separator line, or a list of fields for that line.
5161 PARAMS is a property list of parameters that can influence the
5162 conversion. All parameters from `orgtbl-to-generic' are
5163 supported.
5165 Useful when slicing one table into many. The :hline, :sep,
5166 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5167 be set to provide ORGTBL directives for the generated table."
5168 (require 'ox-org)
5169 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5171 (defun orgtbl-to-table.el (table params)
5172 "Convert the orgtbl-mode TABLE into a table.el table.
5173 TABLE is a list, each entry either the symbol `hline' for
5174 a horizontal separator line, or a list of fields for that line.
5175 PARAMS is a property list of parameters that can influence the
5176 conversion. All parameters from `orgtbl-to-generic' are
5177 supported."
5178 (with-temp-buffer
5179 (insert (orgtbl-to-orgtbl table params))
5180 (org-table-align)
5181 (replace-regexp-in-string
5182 "-|" "-+"
5183 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5185 (defun orgtbl-to-unicode (table params)
5186 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5188 TABLE is a list, each entry either the symbol `hline' for
5189 a horizontal separator line, or a list of fields for that line.
5190 PARAMS is a property list of parameters that can influence the
5191 conversion. All parameters from `orgtbl-to-generic' are
5192 supported. It is also possible to use the following ones:
5194 :ascii-art
5196 When non-nil, use \"ascii-art-to-unicode\" package to translate
5197 the table. You can download it here:
5198 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5200 :narrow
5202 When non-nil, narrow columns width than provided width cookie,
5203 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5204 (require 'ox-ascii)
5205 (orgtbl-to-generic
5206 table
5207 (org-combine-plists
5208 (list :backend 'ascii
5209 :ascii-charset 'utf-8
5210 :ascii-table-widen-columns (not (plist-get params :narrow))
5211 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5212 params)))
5214 ;; Put the cursor in a column containing numerical values
5215 ;; of an Org-Mode table,
5216 ;; type C-c " a
5217 ;; A new column is added with a bar plot.
5218 ;; When the table is refreshed (C-u C-c *),
5219 ;; the plot is updated to reflect the new values.
5221 (defun orgtbl-ascii-draw (value min max &optional width characters)
5222 "Draw an ascii bar in a table.
5223 VALUE is a the value to plot, the width of the bar to draw. A
5224 value equal to MIN will be displayed as empty (zero width bar).
5225 A value equal to MAX will draw a bar filling all the WIDTH.
5226 WIDTH is the expected width in characters of the column.
5227 CHARACTERS is a string that will compose the bar, with shades of
5228 grey from pure white to pure black. It defaults to a 10
5229 characters string of regular ascii characters."
5230 (let* ((characters (or characters " .:;c!lhVHW"))
5231 (width (or width 12))
5232 (value (if (numberp value) value (string-to-number value)))
5233 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5234 (cond
5235 ((< value 0) "too small")
5236 ((> value width) "too large")
5238 (let ((len (1- (length characters))))
5239 (concat
5240 (make-string (floor value) (elt characters len))
5241 (string (elt characters
5242 (floor (* (- value (floor value)) len))))))))))
5244 ;;;###autoload
5245 (defun orgtbl-ascii-plot (&optional ask)
5246 "Draw an ascii bar plot in a column.
5247 With cursor in a column containing numerical values, this
5248 function will draw a plot in a new column.
5249 ASK, if given, is a numeric prefix to override the default 12
5250 characters width of the plot. ASK may also be the
5251 \\[universal-argument] prefix, which will prompt for the width."
5252 (interactive "P")
5253 (let ((col (org-table-current-column))
5254 (min 1e999) ; 1e999 will be converted to infinity
5255 (max -1e999) ; which is the desired result
5256 (table (org-table-to-lisp))
5257 (length
5258 (cond ((consp ask)
5259 (read-number "Length of column " 12))
5260 ((numberp ask) ask)
5261 (t 12))))
5262 ;; Skip any hline a the top of table.
5263 (while (eq (car table) 'hline) (setq table (cdr table)))
5264 ;; Skip table header if any.
5265 (dolist (x (or (cdr (memq 'hline table)) table))
5266 (when (consp x)
5267 (setq x (nth (1- col) x))
5268 (when (string-match
5269 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5271 (setq x (string-to-number x))
5272 (when (> min x) (setq min x))
5273 (when (< max x) (setq max x)))))
5274 (org-table-insert-column)
5275 (org-table-move-column-right)
5276 (org-table-store-formulas
5277 (cons
5278 (cons
5279 (number-to-string (1+ col))
5280 (format "'(%s $%s %s %s %s)"
5281 "orgtbl-ascii-draw" col min max length))
5282 (org-table-get-stored-formulas)))
5283 (org-table-recalculate t)))
5285 ;; Example of extension: unicode characters
5286 ;; Here are two examples of different styles.
5288 ;; Unicode block characters are used to give a smooth effect.
5289 ;; See http://en.wikipedia.org/wiki/Block_Elements
5290 ;; Use one of those drawing functions
5291 ;; - orgtbl-ascii-draw (the default ascii)
5292 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5293 ;; - orgtbl-uc-draw-cont (smooth unicode)
5295 ;; This is best viewed with the "DejaVu Sans Mono" font
5296 ;; (use M-x set-default-font).
5298 (defun orgtbl-uc-draw-grid (value min max &optional width)
5299 "Draw a bar in a table using block unicode characters.
5300 It is a variant of orgtbl-ascii-draw with Unicode block
5301 characters, for a smooth display. Bars appear as grids (to the
5302 extent the font allows)."
5303 ;; http://en.wikipedia.org/wiki/Block_Elements
5304 ;; best viewed with the "DejaVu Sans Mono" font.
5305 (orgtbl-ascii-draw value min max width
5306 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5308 (defun orgtbl-uc-draw-cont (value min max &optional width)
5309 "Draw a bar in a table using block unicode characters.
5310 It is a variant of orgtbl-ascii-draw with Unicode block
5311 characters, for a smooth display. Bars are solid (to the extent
5312 the font allows)."
5313 (orgtbl-ascii-draw value min max width
5314 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5316 (defun org-table-get-remote-range (name-or-id form)
5317 "Get a field value or a list of values in a range from table at ID.
5319 NAME-OR-ID may be the name of a table in the current file as set
5320 by a \"#+NAME:\" directive. The first table following this line
5321 will then be used. Alternatively, it may be an ID referring to
5322 any entry, also in a different file. In this case, the first
5323 table in that entry will be referenced.
5324 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5325 \"@I$2..@II$2\". All the references must be absolute, not relative.
5327 The return value is either a single string for a single field, or a
5328 list of the fields in the rectangle."
5329 (save-match-data
5330 (let ((case-fold-search t) (id-loc nil)
5331 ;; Protect a bunch of variables from being overwritten by
5332 ;; the context of the remote table.
5333 org-table-column-names org-table-column-name-regexp
5334 org-table-local-parameters org-table-named-field-locations
5335 org-table-current-line-types
5336 org-table-current-begin-pos org-table-dlines
5337 org-table-current-ncol
5338 org-table-hlines org-table-last-alignment
5339 org-table-last-column-widths org-table-last-alignment
5340 org-table-last-column-widths
5341 buffer loc)
5342 (setq form (org-table-convert-refs-to-rc form))
5343 (org-with-wide-buffer
5344 (goto-char (point-min))
5345 (if (re-search-forward
5346 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5347 (regexp-quote name-or-id) "[ \t]*$")
5348 nil t)
5349 (setq buffer (current-buffer) loc (match-beginning 0))
5350 (setq id-loc (org-id-find name-or-id 'marker))
5351 (unless (and id-loc (markerp id-loc))
5352 (user-error "Can't find remote table \"%s\"" name-or-id))
5353 (setq buffer (marker-buffer id-loc)
5354 loc (marker-position id-loc))
5355 (move-marker id-loc nil))
5356 (with-current-buffer buffer
5357 (org-with-wide-buffer
5358 (goto-char loc)
5359 (forward-char 1)
5360 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5361 (not (match-beginning 1)))
5362 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5363 (org-table-analyze)
5364 (setq form (org-table-formula-substitute-names
5365 (org-table-formula-handle-first/last-rc form)))
5366 (if (and (string-match org-table-range-regexp form)
5367 (> (length (match-string 0 form)) 1))
5368 (org-table-get-range
5369 (match-string 0 form) org-table-current-begin-pos 1)
5370 form)))))))
5372 (defun org-table-remote-reference-indirection (form)
5373 "Return formula with table remote references substituted by indirection.
5374 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5375 This indirection works only with the format @ROW$COLUMN. The
5376 format \"B3\" is not supported because it can not be
5377 distinguished from a plain table name or ID."
5378 (let ((start 0))
5379 (while (string-match (concat
5380 ;; Same as in `org-table-eval-formula'.
5381 "\\<remote([ \t]*\\("
5382 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5383 "[@$][^ \t,]+"
5384 ;; Same as in `org-table-eval-formula'.
5385 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5386 form
5387 start)
5388 ;; The position of the character as far as possible to the right
5389 ;; that will not be replaced and particularly not be shifted by
5390 ;; `replace-match'.
5391 (setq start (match-beginning 1))
5392 ;; Substitute the remote reference with the value found in the
5393 ;; field.
5394 (setq form
5395 (replace-match
5396 (save-match-data
5397 (org-table-get-range (org-table-formula-handle-first/last-rc
5398 (match-string 1 form))))
5399 t t form 1))))
5400 form)
5402 (defmacro org-define-lookup-function (mode)
5403 (let ((mode-str (symbol-name mode))
5404 (first-p (equal mode 'first))
5405 (all-p (equal mode 'all)))
5406 (let ((plural-str (if all-p "s" "")))
5407 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5408 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5409 If R-LIST is nil, return matching element%s of S-LIST.
5410 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5411 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5412 This function is generated by a call to the macro `org-define-lookup-function'."
5413 mode-str plural-str plural-str plural-str)
5414 (let ,(let ((lvars '((p (or predicate 'equal))
5415 (sl s-list)
5416 (rl (or r-list s-list))
5417 (ret nil))))
5418 (if first-p (cons '(match-p nil) lvars) lvars))
5419 (while ,(if first-p '(and (not match-p) sl) 'sl)
5420 (when (funcall p val (car sl))
5421 ,(when first-p '(setq match-p t))
5422 (let ((rval (car rl)))
5423 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5424 (setq sl (cdr sl) rl (cdr rl)))
5425 ret)))))
5427 (org-define-lookup-function first)
5428 (org-define-lookup-function last)
5429 (org-define-lookup-function all)
5431 (provide 'org-table)
5433 ;; Local variables:
5434 ;; generated-autoload-file: "org-loaddefs.el"
5435 ;; End:
5437 ;;; org-table.el ends here