ox-publish: Fix publishing bug
[org-mode.git] / lisp / org-table.el
blob097a191d2be90376ba89142fc4072ccb834f8dda
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 (forward-line -1)
2534 (let* ((last-dline (car dlines))
2535 (fields (org-split-string
2536 (buffer-substring (line-beginning-position)
2537 (line-end-position))
2538 "[ \t]*|[ \t]*"))
2539 (nfields (length fields))
2540 al al2)
2541 (setq org-table-current-ncol nfields)
2542 (dotimes (i nfields)
2543 (let ((column (1+ i)))
2544 (push (list (format "LR%d" column) last-dline column) al)
2545 (push (cons (format "LR%d" column) (nth i fields)) al2)))
2546 (setq org-table-named-field-locations
2547 (append org-table-named-field-locations al))
2548 (setq org-table-local-parameters
2549 (append org-table-local-parameters al2)))))))
2551 (defun org-table-goto-field (ref &optional create-column-p)
2552 "Move point to a specific field in the current table.
2554 REF is either the name of a field its absolute reference, as
2555 a string. No column is created unless CREATE-COLUMN-P is
2556 non-nil. If it is a function, it is called with the column
2557 number as its argument as is used as a predicate to know if the
2558 column can be created.
2560 This function assumes the table is already analyzed (i.e., using
2561 `org-table-analyze')."
2562 (let* ((coordinates
2563 (cond
2564 ((cdr (assoc ref org-table-named-field-locations)))
2565 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
2566 (list (condition-case nil
2567 (aref org-table-dlines
2568 (string-to-number (match-string 1 ref)))
2569 (error (user-error "Invalid row number in %s" ref)))
2570 (string-to-number (match-string 2 ref))))
2571 (t (user-error "Unknown field: %s" ref))))
2572 (line (car coordinates))
2573 (column (nth 1 coordinates))
2574 (create-new-column (if (functionp create-column-p)
2575 (funcall create-column-p column)
2576 create-column-p)))
2577 (when coordinates
2578 (goto-char org-table-current-begin-pos)
2579 (forward-line line)
2580 (org-table-goto-column column nil create-new-column))))
2582 ;;;###autoload
2583 (defun org-table-maybe-recalculate-line ()
2584 "Recompute the current line if marked for it, and if we haven't just done it."
2585 (interactive)
2586 (and org-table-allow-automatic-line-recalculation
2587 (not (and (memq last-command org-recalc-commands)
2588 (eq org-last-recalc-line (line-beginning-position))))
2589 (save-excursion (beginning-of-line 1)
2590 (looking-at org-table-auto-recalculate-regexp))
2591 (org-table-recalculate) t))
2593 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2594 (defsubst org-set-calc-mode (var &optional value)
2595 (if (stringp var)
2596 (setq var (assoc var '(("D" calc-angle-mode deg)
2597 ("R" calc-angle-mode rad)
2598 ("F" calc-prefer-frac t)
2599 ("S" calc-symbolic-mode t)))
2600 value (nth 2 var) var (nth 1 var)))
2601 (if (memq var org-tbl-calc-modes)
2602 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2603 (cons var (cons value org-tbl-calc-modes)))
2604 org-tbl-calc-modes)
2606 ;;;###autoload
2607 (defun org-table-eval-formula (&optional arg equation
2608 suppress-align suppress-const
2609 suppress-store suppress-analysis)
2610 "Replace the table field value at the cursor by the result of a calculation.
2612 This function makes use of Dave Gillespie's Calc package, in my view the
2613 most exciting program ever written for GNU Emacs. So you need to have Calc
2614 installed in order to use this function.
2616 In a table, this command replaces the value in the current field with the
2617 result of a formula. It also installs the formula as the \"current\" column
2618 formula, by storing it in a special line below the table. When called
2619 with a `C-u' prefix, the current field must be a named field, and the
2620 formula is installed as valid in only this specific field.
2622 When called with two `C-u' prefixes, insert the active equation
2623 for the field back into the current field, so that it can be
2624 edited there. This is useful in order to use \\[org-table-show-reference]
2625 to check the referenced fields.
2627 When called, the command first prompts for a formula, which is read in
2628 the minibuffer. Previously entered formulas are available through the
2629 history list, and the last used formula is offered as a default.
2630 These stored formulas are adapted correctly when moving, inserting, or
2631 deleting columns with the corresponding commands.
2633 The formula can be any algebraic expression understood by the Calc package.
2634 For details, see the Org-mode manual.
2636 This function can also be called from Lisp programs and offers
2637 additional arguments: EQUATION can be the formula to apply. If this
2638 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2639 used to speed-up recursive calls by by-passing unnecessary aligns.
2640 SUPPRESS-CONST suppresses the interpretation of constants in the
2641 formula, assuming that this has been done already outside the function.
2642 SUPPRESS-STORE means the formula should not be stored, either because
2643 it is already stored, or because it is a modified equation that should
2644 not overwrite the stored one."
2645 (interactive "P")
2646 (org-table-check-inside-data-field)
2647 (or suppress-analysis (org-table-analyze))
2648 (if (equal arg '(16))
2649 (let ((eq (org-table-current-field-formula)))
2650 (or eq (user-error "No equation active for current field"))
2651 (org-table-get-field nil eq)
2652 (org-table-align)
2653 (setq org-table-may-need-update t))
2654 (let* (fields
2655 (ndown (if (integerp arg) arg 1))
2656 (org-table-automatic-realign nil)
2657 (case-fold-search nil)
2658 (down (> ndown 1))
2659 (formula (if (and equation suppress-store)
2660 equation
2661 (org-table-get-formula equation (equal arg '(4)))))
2662 (n0 (org-table-current-column))
2663 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2664 (numbers nil) ; was a variable, now fixed default
2665 (keep-empty nil)
2666 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2667 duration duration-output-format)
2668 ;; Parse the format string. Since we have a lot of modes, this is
2669 ;; a lot of work. However, I think calc still uses most of the time.
2670 (if (string-match ";" formula)
2671 (let ((tmp (org-split-string formula ";")))
2672 (setq formula (car tmp)
2673 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2674 (nth 1 tmp)))
2675 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2676 (setq c (string-to-char (match-string 1 fmt))
2677 n (string-to-number (match-string 2 fmt)))
2678 (if (= c ?p)
2679 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2680 (setq org-tbl-calc-modes
2681 (org-set-calc-mode
2682 'calc-float-format
2683 (list (cdr (assoc c '((?n . float) (?f . fix)
2684 (?s . sci) (?e . eng))))
2685 n))))
2686 (setq fmt (replace-match "" t t fmt)))
2687 (if (string-match "T" fmt)
2688 (setq duration t numbers t
2689 duration-output-format nil
2690 fmt (replace-match "" t t fmt)))
2691 (if (string-match "t" fmt)
2692 (setq duration t
2693 duration-output-format org-table-duration-custom-format
2694 numbers t
2695 fmt (replace-match "" t t fmt)))
2696 (if (string-match "N" fmt)
2697 (setq numbers t
2698 fmt (replace-match "" t t fmt)))
2699 (if (string-match "L" fmt)
2700 (setq literal t
2701 fmt (replace-match "" t t fmt)))
2702 (if (string-match "E" fmt)
2703 (setq keep-empty t
2704 fmt (replace-match "" t t fmt)))
2705 (while (string-match "[DRFS]" fmt)
2706 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2707 (setq fmt (replace-match "" t t fmt)))
2708 (unless (string-match "\\S-" fmt)
2709 (setq fmt nil))))
2710 (if (and (not suppress-const) org-table-formula-use-constants)
2711 (setq formula (org-table-formula-substitute-names formula)))
2712 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2713 (while (> ndown 0)
2714 (setq fields (org-split-string
2715 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2716 " *| *"))
2717 ;; replace fields with duration values if relevant
2718 (if duration
2719 (setq fields
2720 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2721 fields)))
2722 (if (eq numbers t)
2723 (setq fields (mapcar
2724 (lambda (x)
2725 (if (string-match "\\S-" x)
2726 (number-to-string (string-to-number x))
2728 fields)))
2729 (setq ndown (1- ndown))
2730 (setq form (copy-sequence formula)
2731 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2732 (if (and lispp literal) (setq lispp 'literal))
2734 ;; Insert row and column number of formula result field
2735 (while (string-match "[@$]#" form)
2736 (setq form
2737 (replace-match
2738 (format "%d"
2739 (save-match-data
2740 (if (equal (substring form (match-beginning 0)
2741 (1+ (match-beginning 0)))
2742 "@")
2743 (org-table-current-dline)
2744 (org-table-current-column))))
2745 t t form)))
2747 ;; Check for old vertical references
2748 (org-table--error-on-old-row-references form)
2749 ;; Insert remote references
2750 (setq form (org-table-remote-reference-indirection form))
2751 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2752 (setq form
2753 (replace-match
2754 (save-match-data
2755 (org-table-make-reference
2756 (let ((rmtrng (org-table-get-remote-range
2757 (match-string 1 form) (match-string 2 form))))
2758 (if duration
2759 (if (listp rmtrng)
2760 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2761 (org-table-time-string-to-seconds rmtrng))
2762 rmtrng))
2763 keep-empty numbers lispp))
2764 t t form)))
2765 ;; Insert complex ranges
2766 (while (and (string-match org-table-range-regexp form)
2767 (> (length (match-string 0 form)) 1))
2768 (setq formrg
2769 (save-match-data
2770 (org-table-get-range
2771 (match-string 0 form) org-table-current-begin-pos n0)))
2772 (setq formrpl
2773 (save-match-data
2774 (org-table-make-reference
2775 ;; possibly handle durations
2776 (if duration
2777 (if (listp formrg)
2778 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2779 (org-table-time-string-to-seconds formrg))
2780 formrg)
2781 keep-empty numbers lispp)))
2782 (if (not (save-match-data
2783 (string-match (regexp-quote form) formrpl)))
2784 (setq form (replace-match formrpl t t form))
2785 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2786 ;; Insert simple ranges, i.e. included in the current row.
2787 (while (string-match
2788 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2789 form)
2790 (setq form
2791 (replace-match
2792 (save-match-data
2793 (org-table-make-reference
2794 (cl-subseq fields
2795 (+ (if (match-end 2) n0 0)
2796 (string-to-number (match-string 1 form))
2798 (+ (if (match-end 4) n0 0)
2799 (string-to-number (match-string 3 form))))
2800 keep-empty numbers lispp))
2801 t t form)))
2802 (setq form0 form)
2803 ;; Insert the references to fields in same row
2804 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2805 (setq n (+ (string-to-number (match-string 1 form))
2806 (if (match-end 2) n0 0))
2807 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2808 formrpl (save-match-data
2809 (org-table-make-reference
2810 x keep-empty numbers lispp)))
2811 (when (or (not x)
2812 (save-match-data
2813 (string-match (regexp-quote formula) formrpl)))
2814 (user-error "Invalid field specifier \"%s\""
2815 (match-string 0 form)))
2816 (setq form (replace-match formrpl t t form)))
2818 (if lispp
2819 (setq ev (condition-case nil
2820 (eval (eval (read form)))
2821 (error "#ERROR"))
2822 ev (if (numberp ev) (number-to-string ev) ev)
2823 ev (if duration (org-table-time-seconds-to-string
2824 (string-to-number ev)
2825 duration-output-format) ev))
2826 (or (fboundp 'calc-eval)
2827 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2828 ;; Use <...> time-stamps so that Calc can handle them
2829 (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
2830 (setq form (replace-match "<\\1>" nil nil form)))
2831 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2832 (when (string-match org-ts-regexp2 form)
2833 (let* ((ts (match-string 0 form))
2834 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2835 (system-time-locale "C")
2836 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2837 (cdr org-time-stamp-formats))
2838 (car org-time-stamp-formats))))
2839 (setq form (replace-match (format-time-string tf tsp) t t form))))
2841 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2842 form
2843 (calc-eval (cons form org-tbl-calc-modes)
2844 (when (and (not keep-empty) numbers) 'num)))
2845 ev (if duration (org-table-time-seconds-to-string
2846 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2847 (string-to-number (org-table-time-string-to-seconds ev))
2848 (string-to-number ev))
2849 duration-output-format)
2850 ev)))
2852 (when org-table-formula-debug
2853 (with-output-to-temp-buffer "*Substitution History*"
2854 (princ (format "Substitution history of formula
2855 Orig: %s
2856 $xyz-> %s
2857 @r$c-> %s
2858 $1-> %s\n" orig formula form0 form))
2859 (if (consp ev)
2860 (princ (format " %s^\nError: %s"
2861 (make-string (car ev) ?\-) (nth 1 ev)))
2862 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2863 ev (or fmt "NONE")
2864 (if fmt (format fmt (string-to-number ev)) ev)))))
2865 (setq bw (get-buffer-window "*Substitution History*"))
2866 (org-fit-window-to-buffer bw)
2867 (unless (and (org-called-interactively-p 'any) (not ndown))
2868 (unless (let (inhibit-redisplay)
2869 (y-or-n-p "Debugging Formula. Continue to next? "))
2870 (org-table-align)
2871 (user-error "Abort"))
2872 (delete-window bw)
2873 (message "")))
2874 (when (consp ev) (setq fmt nil ev "#ERROR"))
2875 (org-table-justify-field-maybe
2876 (format org-table-formula-field-format
2877 (if fmt (format fmt (string-to-number ev)) ev)))
2878 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2879 (call-interactively 'org-return)
2880 (setq ndown 0)))
2881 (and down (org-table-maybe-recalculate-line))
2882 (or suppress-align (and org-table-may-need-update
2883 (org-table-align))))))
2885 (defun org-table-put-field-property (prop value)
2886 (save-excursion
2887 (put-text-property (progn (skip-chars-backward "^|") (point))
2888 (progn (skip-chars-forward "^|") (point))
2889 prop value)))
2891 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2892 "Get a calc vector from a column, according to descriptor DESC.
2894 Optional arguments TBEG and COL can give the beginning of the table and
2895 the current column, to avoid unnecessary parsing.
2897 HIGHLIGHT means just highlight the range.
2899 When CORNERS-ONLY is set, only return the corners of the range as
2900 a list (line1 column1 line2 column2) where line1 and line2 are
2901 line numbers relative to beginning of table, or TBEG, and column1
2902 and column2 are table column numbers."
2903 (let* ((desc (if (eq (string-to-char desc) ?@) desc (concat "@" desc)))
2904 (col (or col (org-table-current-column)))
2905 (tbeg (or tbeg (org-table-begin)))
2906 (thisline (count-lines tbeg (line-beginning-position))))
2907 (unless (string-match org-table-range-regexp desc)
2908 (user-error "Invalid table range specifier `%s'" desc))
2909 (let ((rangep (match-end 3))
2910 (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
2911 (or (save-match-data
2912 (and (org-string-nw-p r)
2913 (org-table--descriptor-line r thisline)))
2914 thisline)))
2915 (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
2916 (or (save-match-data
2917 (and (org-string-nw-p r)
2918 (org-table--descriptor-line r thisline)))
2919 thisline)))
2920 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
2921 (if (or (not c) (= (string-to-number c) 0)) col
2922 (+ (string-to-number c)
2923 (if (memq (string-to-char c) '(?- ?+)) col 0)))))
2924 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
2925 (if (or (not c) (= (string-to-number c) 0)) col
2926 (+ (string-to-number c)
2927 (if (memq (string-to-char c) '(?- ?+)) col 0))))))
2928 (save-excursion
2929 (if (and (not corners-only)
2930 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2931 ;; Just one field.
2932 (progn
2933 (forward-line (- r1 thisline))
2934 (while (not (looking-at org-table-dataline-regexp))
2935 (forward-line))
2936 (prog1 (org-trim (org-table-get-field c1))
2937 (when highlight (org-table-highlight-rectangle))))
2938 ;; A range, return a vector. First sort the numbers to get
2939 ;; a regular rectangle.
2940 (let ((first-row (min r1 r2))
2941 (last-row (max r1 r2))
2942 (first-column (min c1 c2))
2943 (last-column (max c1 c2)))
2944 (if corners-only (list first-row first-column last-row last-column)
2945 ;; Copy the range values into a list.
2946 (forward-line (- first-row thisline))
2947 (while (not (looking-at org-table-dataline-regexp))
2948 (forward-line)
2949 (incf first-row))
2950 (org-table-goto-column first-column)
2951 (let ((beg (point)))
2952 (forward-line (- last-row first-row))
2953 (while (not (looking-at org-table-dataline-regexp))
2954 (forward-line -1))
2955 (org-table-goto-column last-column)
2956 (let ((end (point)))
2957 (when highlight
2958 (org-table-highlight-rectangle
2959 beg (progn (skip-chars-forward "^|\n") (point))))
2960 ;; Return string representation of calc vector.
2961 (mapcar #'org-trim
2962 (apply #'append
2963 (org-table-copy-region beg end))))))))))))
2965 (defun org-table--descriptor-line (desc cline)
2966 "Return relative line number corresponding to descriptor DESC.
2967 The cursor is currently in relative line number CLINE."
2968 (if (string-match "\\`[0-9]+\\'" desc)
2969 (aref org-table-dlines (string-to-number desc))
2970 (when (or (not (string-match
2971 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
2972 ;; 1 2 3 4 5 6
2973 desc))
2974 (and (not (match-end 3)) (not (match-end 6)))
2975 (and (match-end 3) (match-end 6) (not (match-end 5))))
2976 (user-error "Invalid row descriptor `%s'" desc))
2977 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
2978 (hdir (match-string 2 desc))
2979 (odir (match-string 5 desc))
2980 (on (and (match-end 6) (string-to-number (match-string 6 desc))))
2981 (rel (and (match-end 6)
2982 (or (and (match-end 1) (not (match-end 3)))
2983 (match-end 5)))))
2984 (when (and hn (not hdir))
2985 (setq cline 0)
2986 (setq hdir "+")
2987 (when (eq (aref org-table-current-line-types 0) 'hline) (decf hn)))
2988 (when (and (not hn) on (not odir)) (user-error "Should never happen"))
2989 (when hn
2990 (setq cline
2991 (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
2992 (when on
2993 (setq cline
2994 (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
2995 cline)))
2997 (defun org-table--row-type (type n i backwards relative desc)
2998 "Return relative line of Nth row with type TYPE.
2999 Search starts from relative line I. When BACKWARDS in non-nil,
3000 look before I. When RELATIVE is non-nil, the reference is
3001 relative. DESC is the original descriptor that started the
3002 search, as a string."
3003 (let ((l (length org-table-current-line-types)))
3004 (catch :exit
3005 (dotimes (_ n)
3006 (while (and (incf i (if backwards -1 1))
3007 (>= i 0)
3008 (< i l)
3009 (not (eq (aref org-table-current-line-types i) type))
3010 ;; We are going to cross a hline. Check if this is
3011 ;; an authorized move.
3012 (cond
3013 ((not relative))
3014 ((not (eq (aref org-table-current-line-types i) 'hline)))
3015 ((eq org-table-relative-ref-may-cross-hline t))
3016 ((eq org-table-relative-ref-may-cross-hline 'error)
3017 (user-error "Row descriptor %s crosses hline" desc))
3018 (t (decf i (if backwards -1 1)) ; Step back.
3019 (throw :exit nil)))))))
3020 (cond ((or (< i 0) (>= i l))
3021 (user-error "Row descriptor %s leads outside table" desc))
3022 ;; The last hline doesn't exist. Instead, point to last row
3023 ;; in table.
3024 ((= i (1- l)) (1- i))
3025 (t i))))
3027 (defun org-table--error-on-old-row-references (s)
3028 (when (string-match "&[-+0-9I]" s)
3029 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3031 (defun org-table-make-reference (elements keep-empty numbers lispp)
3032 "Convert list ELEMENTS to something appropriate to insert into formula.
3033 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3034 NUMBERS indicates that everything should be converted to numbers.
3035 LISPP non-nil means to return something appropriate for a Lisp
3036 list, `literal' is for the format specifier L."
3037 ;; Calc nan (not a number) is used for the conversion of the empty
3038 ;; field to a reference for several reasons: (i) It is accepted in a
3039 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3040 ;; (ii) In a single field (not in range) it can be distinguished
3041 ;; from "(nan)" which is the reference made from a single field
3042 ;; containing "nan".
3043 (if (stringp elements)
3044 ;; field reference
3045 (if lispp
3046 (if (eq lispp 'literal)
3047 elements
3048 (if (and (eq elements "") (not keep-empty))
3050 (prin1-to-string
3051 (if numbers (string-to-number elements) elements))))
3052 (if (string-match "\\S-" elements)
3053 (progn
3054 (when numbers (setq elements (number-to-string
3055 (string-to-number elements))))
3056 (concat "(" elements ")"))
3057 (if (or (not keep-empty) numbers) "(0)" "nan")))
3058 ;; range reference
3059 (unless keep-empty
3060 (setq elements
3061 (delq nil
3062 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3063 elements))))
3064 (setq elements (or elements '())) ; if delq returns nil then we need '()
3065 (if lispp
3066 (mapconcat
3067 (lambda (x)
3068 (if (eq lispp 'literal)
3070 (prin1-to-string (if numbers (string-to-number x) x))))
3071 elements " ")
3072 (concat "[" (mapconcat
3073 (lambda (x)
3074 (if (string-match "\\S-" x)
3075 (if numbers
3076 (number-to-string (string-to-number x))
3078 (if (or (not keep-empty) numbers) "0" "nan")))
3079 elements
3080 ",") "]"))))
3082 (defun org-table-message-once-per-second (t1 &rest args)
3083 "If there has been more than one second since T1, display message.
3084 ARGS are passed as arguments to the `message' function. Returns
3085 current time if a message is printed, otherwise returns T1. If
3086 T1 is nil, always messages."
3087 (let ((curtime (current-time)))
3088 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3089 (progn (apply 'message args)
3090 curtime)
3091 t1)))
3093 ;;;###autoload
3094 (defun org-table-recalculate (&optional all noalign)
3095 "Recalculate the current table line by applying all stored formulas.
3096 With prefix arg ALL, do this for all lines in the table.
3097 With the prefix argument ALL is `(16)' \
3098 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3099 it is the symbol `iterate', recompute the table until it no longer changes.
3100 If NOALIGN is not nil, do not re-align the table after the computations
3101 are done. This is typically used internally to save time, if it is
3102 known that the table will be realigned a little later anyway."
3103 (interactive "P")
3104 (unless (memq this-command org-recalc-commands)
3105 (push this-command org-recalc-commands))
3106 (unless (org-at-table-p) (user-error "Not at a table"))
3107 (if (or (eq all 'iterate) (equal all '(16)))
3108 (org-table-iterate)
3109 (org-table-analyze)
3110 (let* ((eqlist (sort (org-table-get-stored-formulas)
3111 (lambda (a b) (string< (car a) (car b)))))
3112 (eqlist1 (copy-sequence eqlist))
3113 (inhibit-redisplay (not debug-on-error))
3114 (line-re org-table-dataline-regexp)
3115 (log-first-time (current-time))
3116 (log-last-time log-first-time)
3117 (cnt 0)
3118 beg end eqlnum eqlname)
3119 ;; Insert constants in all formulas
3120 (when eqlist
3121 (org-table-save-field
3122 (setq eqlist
3123 (mapcar
3124 (lambda (x)
3125 (when (string-match "\\`@-?I+" (car x))
3126 (user-error "Can't assign to hline relative reference"))
3127 (when (string-match "\\`$[<>]" (car x))
3128 (let ((old-lhs (car x)))
3129 (setq x
3130 (cons
3131 (substring
3132 (org-table-formula-handle-first/last-rc old-lhs)
3134 (cdr x)))
3135 (when (assoc (car x) eqlist1)
3136 (user-error "\"%s=\" formula tries to overwrite \
3137 existing formula for column %s"
3138 old-lhs
3139 (car x)))))
3140 (cons (org-table-formula-handle-first/last-rc (car x))
3141 (org-table-formula-substitute-names
3142 (org-table-formula-handle-first/last-rc (cdr x)))))
3143 eqlist))
3144 ;; Split the equation list.
3145 (dolist (eq eqlist)
3146 (if (<= (string-to-char (car eq)) ?9)
3147 (push eq eqlnum)
3148 (push eq eqlname)))
3149 (setq eqlnum (nreverse eqlnum))
3150 ;; Expand ranges in lhs of formulas
3151 (setq eqlname (org-table-expand-lhs-ranges (nreverse eqlname)))
3152 ;; Get the correct line range to process
3153 (if all
3154 (progn
3155 (setq end (copy-marker (org-table-end)))
3156 (goto-char (setq beg org-table-current-begin-pos))
3157 (cond
3158 ((re-search-forward org-table-calculate-mark-regexp end t)
3159 ;; This is a table with marked lines, compute selected
3160 ;; lines.
3161 (setq line-re org-table-recalculate-regexp))
3162 ;; Move forward to the first non-header line.
3163 ((and (re-search-forward org-table-dataline-regexp end t)
3164 (re-search-forward org-table-hline-regexp end t)
3165 (re-search-forward org-table-dataline-regexp end t))
3166 (setq beg (match-beginning 0)))
3167 ;; Just leave BEG where it is.
3168 (t nil)))
3169 (setq beg (line-beginning-position)
3170 end (copy-marker (line-beginning-position 2))))
3171 (goto-char beg)
3172 ;; Mark named fields untouchable. Also check if several
3173 ;; field/range formulas try to set the same field.
3174 (remove-text-properties beg end '(org-untouchable t))
3175 (let ((current-line (count-lines org-table-current-begin-pos
3176 (line-beginning-position)))
3177 seen-fields)
3178 (dolist (eq eqlname)
3179 (let* ((name (car eq))
3180 (location (assoc name org-table-named-field-locations))
3181 (eq-line (or (nth 1 location)
3182 (and (string-match "\\`@\\([0-9]+\\)" name)
3183 (aref org-table-dlines
3184 (string-to-number
3185 (match-string 1 name))))))
3186 (reference
3187 (if location
3188 ;; Turn field coordinates associated to NAME
3189 ;; into an absolute reference.
3190 (format "@%d$%d"
3191 (org-table-line-to-dline eq-line)
3192 (nth 2 location))
3193 name)))
3194 (when (member reference seen-fields)
3195 (user-error "Several field/range formulas try to set %s"
3196 reference))
3197 (push reference seen-fields)
3198 (when (or all (eq eq-line current-line))
3199 (org-table-goto-field name)
3200 (org-table-put-field-property :org-untouchable t)))))
3201 ;; Evaluate the column formulas, but skip fields covered by
3202 ;; field formulas.
3203 (goto-char beg)
3204 (while (re-search-forward line-re end t)
3205 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3206 ;; Unprotected line, recalculate.
3207 (incf cnt)
3208 (when all
3209 (setq log-last-time
3210 (org-table-message-once-per-second
3211 log-last-time
3212 "Re-applying formulas to full table...(line %d)" cnt)))
3213 (if (markerp org-last-recalc-line)
3214 (move-marker org-last-recalc-line (line-beginning-position))
3215 (setq org-last-recalc-line
3216 (copy-marker (line-beginning-position))))
3217 (dolist (entry eqlnum)
3218 (goto-char org-last-recalc-line)
3219 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3220 (unless (get-text-property (point) :org-untouchable)
3221 (org-table-eval-formula
3222 nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
3223 ;; Evaluate the field formulas.
3224 (dolist (eq eqlname)
3225 (let ((reference (car eq))
3226 (formula (cdr eq)))
3227 (setq log-last-time
3228 (org-table-message-once-per-second
3229 (and all log-last-time)
3230 "Re-applying formula to field: %s" (car eq)))
3231 (org-table-goto-field
3232 reference
3233 ;; Possibly create a new column, as long as
3234 ;; `org-table-formula-create-columns' allows it.
3235 (let ((column-count (progn (end-of-line)
3236 (1- (org-table-current-column)))))
3237 `(lambda (column)
3238 (when (> column 1000)
3239 (user-error "Formula column target too large"))
3240 (and (> column ,column-count)
3241 (or (eq org-table-formula-create-columns t)
3242 (and (eq org-table-formula-create-columns 'warn)
3243 (progn
3244 (org-display-warning
3245 "Out-of-bounds formula added columns")
3247 (and (eq org-table-formula-create-columns 'prompt)
3248 (yes-or-no-p
3249 "Out-of-bounds formula. Add columns? ")))))))
3250 (org-table-eval-formula nil formula t t t t))))
3251 ;; Clean up markers and internal text property.
3252 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3253 (set-marker end nil)
3254 (unless noalign
3255 (when org-table-may-need-update (org-table-align))
3256 (when all
3257 (org-table-message-once-per-second
3258 log-first-time "Re-applying formulas to %d lines... done" cnt)))
3259 (org-table-message-once-per-second
3260 (and all log-first-time) "Re-applying formulas... done")))))
3262 ;;;###autoload
3263 (defun org-table-iterate (&optional arg)
3264 "Recalculate the table until it does not change anymore.
3265 The maximum number of iterations is 10, but you can choose a different value
3266 with the prefix ARG."
3267 (interactive "P")
3268 (let ((imax (if arg (prefix-numeric-value arg) 10))
3269 (i 0)
3270 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3271 thistbl)
3272 (catch 'exit
3273 (while (< i imax)
3274 (setq i (1+ i))
3275 (org-table-recalculate 'all)
3276 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3277 (if (not (string= lasttbl thistbl))
3278 (setq lasttbl thistbl)
3279 (if (> i 1)
3280 (message "Convergence after %d iterations" i)
3281 (message "Table was already stable"))
3282 (throw 'exit t)))
3283 (user-error "No convergence after %d iterations" i))))
3285 ;;;###autoload
3286 (defun org-table-recalculate-buffer-tables ()
3287 "Recalculate all tables in the current buffer."
3288 (interactive)
3289 (save-excursion
3290 (save-restriction
3291 (widen)
3292 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3294 ;;;###autoload
3295 (defun org-table-iterate-buffer-tables ()
3296 "Iterate all tables in the buffer, to converge inter-table dependencies."
3297 (interactive)
3298 (let* ((imax 10)
3299 (i imax)
3300 (checksum (md5 (buffer-string)))
3302 (save-excursion
3303 (save-restriction
3304 (widen)
3305 (catch 'exit
3306 (while (> i 0)
3307 (setq i (1- i))
3308 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3309 (if (equal checksum (setq c1 (md5 (buffer-string))))
3310 (progn
3311 (message "Convergence after %d iterations" (- imax i))
3312 (throw 'exit t))
3313 (setq checksum c1)))
3314 (user-error "No convergence after %d iterations" imax))))))
3316 (defun org-table-calc-current-TBLFM (&optional arg)
3317 "Apply the #+TBLFM in the line at point to the table."
3318 (interactive "P")
3319 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3320 (let ((formula (buffer-substring
3321 (line-beginning-position)
3322 (line-end-position))))
3323 (save-excursion
3324 ;; Insert a temporary formula at right after the table
3325 (goto-char (org-table-TBLFM-begin))
3326 (let ((s (point-marker)))
3327 (insert formula "\n")
3328 (let ((e (point-marker)))
3329 ;; Recalculate the table.
3330 (beginning-of-line 0) ; move to the inserted line
3331 (skip-chars-backward " \r\n\t")
3332 (unwind-protect
3333 (org-call-with-arg #'org-table-recalculate (or arg t))
3334 ;; Delete the formula inserted temporarily.
3335 (delete-region s e)
3336 (set-marker s nil)
3337 (set-marker e nil)))))))
3339 (defun org-table-TBLFM-begin ()
3340 "Find the beginning of the TBLFM lines and return its position.
3341 Return nil when the beginning of TBLFM line was not found."
3342 (save-excursion
3343 (when (progn (forward-line 1)
3344 (re-search-backward org-table-TBLFM-begin-regexp nil t))
3345 (line-beginning-position 2))))
3347 (defun org-table-expand-lhs-ranges (equations)
3348 "Expand list of formulas.
3349 If some of the RHS in the formulas are ranges or a row reference, expand
3350 them to individual field equations for each field."
3351 (let (res)
3352 (dolist (e equations (nreverse res))
3353 (let ((lhs (car e))
3354 (rhs (cdr e)))
3355 (cond
3356 ((string-match "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
3357 ;; This just refers to one fixed field.
3358 (push e res))
3359 ((string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
3360 ;; This just refers to one fixed named field.
3361 (push e res))
3362 ((string-match "\\`@[0-9]+\\'" lhs)
3363 (dotimes (ic org-table-current-ncol)
3364 (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
3365 rhs)
3366 res)))
3368 (let* ((range (org-table-get-range
3369 lhs org-table-current-begin-pos 1 nil 'corners))
3370 (r1 (org-table-line-to-dline (nth 0 range)))
3371 (c1 (nth 1 range))
3372 (r2 (org-table-line-to-dline (nth 2 range) 'above))
3373 (c2 (nth 3 range)))
3374 (loop for ir from r1 to r2 do
3375 (loop for ic from c1 to c2 do
3376 (push
3377 (cons (propertize (format "@%d$%d" ir ic) :orig-eqn e)
3378 rhs)
3379 res))))))))))
3381 (defun org-table-formula-handle-first/last-rc (s)
3382 "Replace @<, @>, $<, $> with first/last row/column of the table.
3383 So @< and $< will always be replaced with @1 and $1, respectively.
3384 The advantage of these special markers are that structure editing of
3385 the table will not change them, while @1 and $1 will be modified
3386 when a line/row is swapped out of that privileged position. So for
3387 formulas that use a range of rows or columns, it may often be better
3388 to anchor the formula with \"I\" row markers, or to offset from the
3389 borders of the table using the @< @> $< $> makers."
3390 (let (n nmax len char (start 0))
3391 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3392 s start)
3393 (if (match-end 3)
3394 (setq start (match-end 3))
3395 (setq nmax (if (equal (match-string 1 s) "@")
3396 (1- (length org-table-dlines))
3397 org-table-current-ncol)
3398 len (- (match-end 2) (match-beginning 2))
3399 char (string-to-char (match-string 2 s))
3400 n (if (= char ?<)
3402 (- nmax len -1)))
3403 (if (or (< n 1) (> n nmax))
3404 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3405 (match-string 0 s) s))
3406 (setq start (match-beginning 0))
3407 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3410 (defun org-table-formula-substitute-names (f)
3411 "Replace $const with values in string F."
3412 (let ((start 0)
3413 (pp (/= (string-to-char f) ?'))
3414 (duration (org-string-match-p ";.*[Tt].*\\'" f))
3415 (new (replace-regexp-in-string ; Check for column names.
3416 org-table-column-name-regexp
3417 (lambda (m)
3418 (concat "$" (cdr (assoc (match-string 1 m)
3419 org-table-column-names))))
3420 f t t)))
3421 ;; Parameters and constants.
3422 (while (setq start
3423 (string-match
3424 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3425 new start))
3426 (if (match-end 2) (setq start (match-end 2))
3427 (incf start)
3428 ;; When a duration is expected, convert value on the fly.
3429 (let ((value
3430 (save-match-data
3431 (let ((v (org-table-get-constant (match-string 1 new))))
3432 (if (and (org-string-nw-p v) duration)
3433 (org-table-time-string-to-seconds v)
3434 v)))))
3435 (when value
3436 (setq new (replace-match
3437 (concat (and pp "(") value (and pp ")")) t t new))))))
3438 (if org-table-formula-debug (org-propertize new :orig-formula f)) new))
3440 (defun org-table-get-constant (const)
3441 "Find the value for a parameter or constant in a formula.
3442 Parameters get priority."
3443 (or (cdr (assoc const org-table-local-parameters))
3444 (cdr (assoc const org-table-formula-constants-local))
3445 (cdr (assoc const org-table-formula-constants))
3446 (and (fboundp 'constants-get) (constants-get const))
3447 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3448 (org-entry-get nil (substring const 5) 'inherit))
3449 "#UNDEFINED_NAME"))
3451 (defvar org-table-fedit-map
3452 (let ((map (make-sparse-keymap)))
3453 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3454 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3455 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3456 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3457 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3458 (org-defkey map "\C-c?" 'org-table-show-reference)
3459 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3460 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3461 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3462 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3463 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3464 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3465 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3466 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3467 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3468 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3469 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3470 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3471 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3472 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3473 map))
3475 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3476 '("Edit-Formulas"
3477 ["Finish and Install" org-table-fedit-finish t]
3478 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3479 ["Abort" org-table-fedit-abort t]
3480 "--"
3481 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3482 ["Complete Lisp Symbol" lisp-complete-symbol t]
3483 "--"
3484 "Shift Reference at Point"
3485 ["Up" org-table-fedit-ref-up t]
3486 ["Down" org-table-fedit-ref-down t]
3487 ["Left" org-table-fedit-ref-left t]
3488 ["Right" org-table-fedit-ref-right t]
3490 "Change Test Row for Column Formulas"
3491 ["Up" org-table-fedit-line-up t]
3492 ["Down" org-table-fedit-line-down t]
3493 "--"
3494 ["Scroll Table Window" org-table-fedit-scroll t]
3495 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3496 ["Show Table Grid" org-table-fedit-toggle-coordinates
3497 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3498 org-table-overlay-coordinates)]
3499 "--"
3500 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3501 :style toggle :selected org-table-buffer-is-an]))
3503 (defvar org-pos)
3505 ;;;###autoload
3506 (defun org-table-edit-formulas ()
3507 "Edit the formulas of the current table in a separate buffer."
3508 (interactive)
3509 (when (save-excursion (beginning-of-line)
3510 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3511 (beginning-of-line 0))
3512 (unless (org-at-table-p) (user-error "Not at a table"))
3513 (org-table-analyze)
3514 (let ((key (org-table-current-field-formula 'key 'noerror))
3515 (eql (sort (org-table-get-stored-formulas 'noerror)
3516 #'org-table-formula-less-p))
3517 (pos (point-marker))
3518 (startline 1)
3519 (wc (current-window-configuration))
3520 (sel-win (selected-window))
3521 (titles '((column . "# Column Formulas\n")
3522 (field . "# Field and Range Formulas\n")
3523 (named . "# Named Field Formulas\n"))))
3524 (org-switch-to-buffer-other-window "*Edit Formulas*")
3525 (erase-buffer)
3526 ;; Keep global-font-lock-mode from turning on font-lock-mode
3527 (let ((font-lock-global-modes '(not fundamental-mode)))
3528 (fundamental-mode))
3529 (setq-local font-lock-global-modes (list 'not major-mode))
3530 (setq-local org-pos pos)
3531 (setq-local org-window-configuration wc)
3532 (setq-local org-selected-window sel-win)
3533 (use-local-map org-table-fedit-map)
3534 (org-add-hook 'post-command-hook #'org-table-fedit-post-command t t)
3535 (easy-menu-add org-table-fedit-menu)
3536 (setq startline (org-current-line))
3537 (dolist (entry eql)
3538 (let* ((type (cond
3539 ((string-match "\\`$[<>]" (car entry)) 'column)
3540 ((equal (string-to-char (car entry)) ?@) 'field)
3541 ((string-match "\\'[0-9]" (car entry)) 'column)
3542 (t 'named)))
3543 (title (assq type titles)))
3544 (when title
3545 (unless (bobp) (insert "\n"))
3546 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3547 (setq titles (remove title titles)))
3548 (when (equal key (car entry)) (setq startline (org-current-line)))
3549 (let ((s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3550 (car entry) " = " (cdr entry) "\n")))
3551 (remove-text-properties 0 (length s) '(face nil) s)
3552 (insert s))))
3553 (when (eq org-table-use-standard-references t)
3554 (org-table-fedit-toggle-ref-type))
3555 (org-goto-line startline)
3556 (message
3557 (substitute-command-keys "\\<org-mode-map>\
3558 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3559 See menu for more commands."))))
3561 (defun org-table-fedit-post-command ()
3562 (when (not (memq this-command '(lisp-complete-symbol)))
3563 (let ((win (selected-window)))
3564 (save-excursion
3565 (ignore-errors (org-table-show-reference))
3566 (select-window win)))))
3568 (defun org-table-formula-to-user (s)
3569 "Convert a formula from internal to user representation."
3570 (if (eq org-table-use-standard-references t)
3571 (org-table-convert-refs-to-an s)
3574 (defun org-table-formula-from-user (s)
3575 "Convert a formula from user to internal representation."
3576 (if org-table-use-standard-references
3577 (org-table-convert-refs-to-rc s)
3580 (defun org-table-convert-refs-to-rc (s)
3581 "Convert spreadsheet references from A7 to @7$28.
3582 Works for single references, but also for entire formulas and even the
3583 full TBLFM line."
3584 (let ((start 0))
3585 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3586 (cond
3587 ((match-end 3)
3588 ;; format match, just advance
3589 (setq start (match-end 0)))
3590 ((and (> (match-beginning 0) 0)
3591 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3592 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3593 ;; 3.e5 or something like this.
3594 (setq start (match-end 0)))
3595 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3596 ;; (member (match-string 1 s)
3597 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3599 ;; function name, just advance
3600 (setq start (match-end 0)))
3602 (setq start (match-beginning 0)
3603 s (replace-match
3604 (if (equal (match-string 2 s) "&")
3605 (format "$%d" (org-letters-to-number (match-string 1 s)))
3606 (format "@%d$%d"
3607 (string-to-number (match-string 2 s))
3608 (org-letters-to-number (match-string 1 s))))
3609 t t s)))))
3612 (defun org-table-convert-refs-to-an (s)
3613 "Convert spreadsheet references from to @7$28 to AB7.
3614 Works for single references, but also for entire formulas and even the
3615 full TBLFM line."
3616 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3617 (setq s (replace-match
3618 (format "%s%d"
3619 (org-number-to-letters
3620 (string-to-number (match-string 2 s)))
3621 (string-to-number (match-string 1 s)))
3622 t t s)))
3623 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3624 (setq s (replace-match (concat "\\1"
3625 (org-number-to-letters
3626 (string-to-number (match-string 2 s))) "&")
3627 t nil s)))
3630 (defun org-letters-to-number (s)
3631 "Convert a base 26 number represented by letters into an integer.
3632 For example: AB -> 28."
3633 (let ((n 0))
3634 (setq s (upcase s))
3635 (while (> (length s) 0)
3636 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3637 s (substring s 1)))
3640 (defun org-number-to-letters (n)
3641 "Convert an integer into a base 26 number represented by letters.
3642 For example: 28 -> AB."
3643 (let ((s ""))
3644 (while (> n 0)
3645 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3646 n (/ (1- n) 26)))
3649 (defun org-table-time-string-to-seconds (s)
3650 "Convert a time string into numerical duration in seconds.
3651 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3652 If S is a string representing a number, keep this number."
3653 (if (equal s "")
3655 (let (hour minus min sec res)
3656 (cond
3657 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3658 (setq minus (< 0 (length (match-string 1 s)))
3659 hour (string-to-number (match-string 2 s))
3660 min (string-to-number (match-string 3 s))
3661 sec (string-to-number (match-string 4 s)))
3662 (if minus
3663 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3664 (setq res (+ (* hour 3600) (* min 60) sec))))
3665 ((and (not (string-match org-ts-regexp-both s))
3666 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3667 (setq minus (< 0 (length (match-string 1 s)))
3668 hour (string-to-number (match-string 2 s))
3669 min (string-to-number (match-string 3 s)))
3670 (if minus
3671 (setq res (- (+ (* hour 3600) (* min 60))))
3672 (setq res (+ (* hour 3600) (* min 60)))))
3673 (t (setq res (string-to-number s))))
3674 (number-to-string res))))
3676 (defun org-table-time-seconds-to-string (secs &optional output-format)
3677 "Convert a number of seconds to a time string.
3678 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3679 minutes or seconds."
3680 (let* ((secs0 (abs secs))
3681 (res
3682 (cond ((eq output-format 'days)
3683 (format "%.3f" (/ (float secs0) 86400)))
3684 ((eq output-format 'hours)
3685 (format "%.2f" (/ (float secs0) 3600)))
3686 ((eq output-format 'minutes)
3687 (format "%.1f" (/ (float secs0) 60)))
3688 ((eq output-format 'seconds)
3689 (format "%d" secs0))
3690 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3691 (if (< secs 0) (concat "-" res) res)))
3693 (defun org-table-fedit-convert-buffer (function)
3694 "Convert all references in this buffer, using FUNCTION."
3695 (let ((origin (copy-marker (line-beginning-position))))
3696 (goto-char (point-min))
3697 (while (not (eobp))
3698 (insert (funcall function (buffer-substring (point) (line-end-position))))
3699 (delete-region (point) (line-end-position))
3700 (forward-line))
3701 (goto-char origin)
3702 (set-marker origin nil)))
3704 (defun org-table-fedit-toggle-ref-type ()
3705 "Convert all references in the buffer from B3 to @3$2 and back."
3706 (interactive)
3707 (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
3708 (org-table-fedit-convert-buffer
3709 (if org-table-buffer-is-an
3710 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3711 (message "Reference type switched to %s"
3712 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3714 (defun org-table-fedit-ref-up ()
3715 "Shift the reference at point one row/hline up."
3716 (interactive)
3717 (org-table-fedit-shift-reference 'up))
3718 (defun org-table-fedit-ref-down ()
3719 "Shift the reference at point one row/hline down."
3720 (interactive)
3721 (org-table-fedit-shift-reference 'down))
3722 (defun org-table-fedit-ref-left ()
3723 "Shift the reference at point one field to the left."
3724 (interactive)
3725 (org-table-fedit-shift-reference 'left))
3726 (defun org-table-fedit-ref-right ()
3727 "Shift the reference at point one field to the right."
3728 (interactive)
3729 (org-table-fedit-shift-reference 'right))
3731 (defun org-table-fedit-shift-reference (dir)
3732 (cond
3733 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3734 (if (memq dir '(left right))
3735 (org-rematch-and-replace 1 (eq dir 'left))
3736 (user-error "Cannot shift reference in this direction")))
3737 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3738 ;; A B3-like reference
3739 (if (memq dir '(up down))
3740 (org-rematch-and-replace 2 (eq dir 'up))
3741 (org-rematch-and-replace 1 (eq dir 'left))))
3742 ((org-in-regexp
3743 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3744 ;; An internal reference
3745 (if (memq dir '(up down))
3746 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3747 (org-rematch-and-replace 5 (eq dir 'left))))))
3749 (defun org-rematch-and-replace (n &optional decr hline)
3750 "Re-match the group N, and replace it with the shifted reference."
3751 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3752 (goto-char (match-beginning n))
3753 (and (looking-at (regexp-quote (match-string n)))
3754 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3755 t t)))
3757 (defun org-table-shift-refpart (ref &optional decr hline)
3758 "Shift a reference part REF.
3759 If DECR is set, decrease the references row/column, else increase.
3760 If HLINE is set, this may be a hline reference, it certainly is not
3761 a translation reference."
3762 (save-match-data
3763 (let* ((sign (string-match "^[-+]" ref)) n)
3765 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3766 (cond
3767 ((and hline (string-match "^I+" ref))
3768 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3769 (setq n (+ n (if decr -1 1)))
3770 (if (= n 0) (setq n (+ n (if decr -1 1))))
3771 (if sign
3772 (setq sign (if (< n 0) "-" "+") n (abs n))
3773 (setq n (max 1 n)))
3774 (concat sign (make-string n ?I)))
3776 ((string-match "^[0-9]+" ref)
3777 (setq n (string-to-number (concat sign ref)))
3778 (setq n (+ n (if decr -1 1)))
3779 (if sign
3780 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3781 (number-to-string (max 1 n))))
3783 ((string-match "^[a-zA-Z]+" ref)
3784 (org-number-to-letters
3785 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3787 (t (user-error "Cannot shift reference"))))))
3789 (defun org-table-fedit-toggle-coordinates ()
3790 "Toggle the display of coordinates in the referenced table."
3791 (interactive)
3792 (let ((pos (marker-position org-pos)))
3793 (with-current-buffer (marker-buffer org-pos)
3794 (save-excursion
3795 (goto-char pos)
3796 (org-table-toggle-coordinate-overlays)))))
3798 (defun org-table-fedit-finish (&optional arg)
3799 "Parse the buffer for formula definitions and install them.
3800 With prefix ARG, apply the new formulas to the table."
3801 (interactive "P")
3802 (org-table-remove-rectangle-highlight)
3803 (if org-table-use-standard-references
3804 (progn
3805 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3806 (setq org-table-buffer-is-an nil)))
3807 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3808 (goto-char (point-min))
3809 (while (re-search-forward
3810 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3811 nil t)
3812 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3813 form (match-string 3))
3814 (setq form (org-trim form))
3815 (when (not (equal form ""))
3816 (while (string-match "[ \t]*\n[ \t]*" form)
3817 (setq form (replace-match " " t t form)))
3818 (when (assoc var eql)
3819 (user-error "Double formulas for %s" var))
3820 (push (cons var form) eql)))
3821 (setq org-pos nil)
3822 (set-window-configuration org-window-configuration)
3823 (select-window sel-win)
3824 (goto-char pos)
3825 (unless (org-at-table-p)
3826 (user-error "Lost table position - cannot install formulas"))
3827 (org-table-store-formulas eql)
3828 (move-marker pos nil)
3829 (kill-buffer "*Edit Formulas*")
3830 (if arg
3831 (org-table-recalculate 'all)
3832 (message "New formulas installed - press C-u C-c C-c to apply."))))
3834 (defun org-table-fedit-abort ()
3835 "Abort editing formulas, without installing the changes."
3836 (interactive)
3837 (org-table-remove-rectangle-highlight)
3838 (let ((pos org-pos) (sel-win org-selected-window))
3839 (set-window-configuration org-window-configuration)
3840 (select-window sel-win)
3841 (goto-char pos)
3842 (move-marker pos nil)
3843 (message "Formula editing aborted without installing changes")))
3845 (defun org-table-fedit-lisp-indent ()
3846 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3847 (interactive)
3848 (let ((pos (point)) beg end ind)
3849 (beginning-of-line 1)
3850 (cond
3851 ((looking-at "[ \t]")
3852 (goto-char pos)
3853 (call-interactively 'lisp-indent-line))
3854 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3855 ((not (fboundp 'pp-buffer))
3856 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3857 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3858 (goto-char (- (match-end 0) 2))
3859 (setq beg (point))
3860 (setq ind (make-string (current-column) ?\ ))
3861 (condition-case nil (forward-sexp 1)
3862 (error
3863 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3864 (setq end (point))
3865 (save-restriction
3866 (narrow-to-region beg end)
3867 (if (eq last-command this-command)
3868 (progn
3869 (goto-char (point-min))
3870 (setq this-command nil)
3871 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3872 (replace-match " ")))
3873 (pp-buffer)
3874 (untabify (point-min) (point-max))
3875 (goto-char (1+ (point-min)))
3876 (while (re-search-forward "^." nil t)
3877 (beginning-of-line 1)
3878 (insert ind))
3879 (goto-char (point-max))
3880 (org-delete-backward-char 1)))
3881 (goto-char beg))
3882 (t nil))))
3884 (defvar org-show-positions nil)
3886 (defun org-table-show-reference (&optional local)
3887 "Show the location/value of the $ expression at point."
3888 (interactive)
3889 (org-table-remove-rectangle-highlight)
3890 (when local (org-table-analyze))
3891 (catch 'exit
3892 (let ((pos (if local (point) org-pos))
3893 (table-start (if local org-table-current-begin-pos (org-table-begin)))
3894 (face2 'highlight)
3895 (org-inhibit-highlight-removal t)
3896 (win (selected-window))
3897 (org-show-positions nil)
3898 var name e what match dest)
3899 (setq what (cond
3900 ((org-in-regexp "^@[0-9]+[ \t=]")
3901 (setq match (concat (substring (match-string 0) 0 -1)
3902 "$1.."
3903 (substring (match-string 0) 0 -1)
3904 "$100"))
3905 'range)
3906 ((or (org-in-regexp org-table-range-regexp2)
3907 (org-in-regexp org-table-translate-regexp)
3908 (org-in-regexp org-table-range-regexp))
3909 (setq match
3910 (save-match-data
3911 (org-table-convert-refs-to-rc (match-string 0))))
3912 'range)
3913 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3914 ((org-in-regexp "\\$[0-9]+") 'column)
3915 ((not local) nil)
3916 (t (user-error "No reference at point")))
3917 match (and what (or match (match-string 0))))
3918 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3919 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3920 'secondary-selection))
3921 (org-add-hook 'before-change-functions
3922 #'org-table-remove-rectangle-highlight)
3923 (when (eq what 'name) (setq var (substring match 1)))
3924 (when (eq what 'range)
3925 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
3926 (setq match (org-table-formula-substitute-names match)))
3927 (unless local
3928 (save-excursion
3929 (end-of-line)
3930 (re-search-backward "^\\S-" nil t)
3931 (beginning-of-line)
3932 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3933 \\([0-9]+\\|&\\)\\) *=")
3934 (setq dest
3935 (save-match-data
3936 (org-table-convert-refs-to-rc (match-string 1))))
3937 (org-table-add-rectangle-overlay
3938 (match-beginning 1) (match-end 1) face2))))
3939 (if (and (markerp pos) (marker-buffer pos))
3940 (if (get-buffer-window (marker-buffer pos))
3941 (select-window (get-buffer-window (marker-buffer pos)))
3942 (org-switch-to-buffer-other-window (get-buffer-window
3943 (marker-buffer pos)))))
3944 (goto-char pos)
3945 (org-table-force-dataline)
3946 (when dest
3947 (setq name (substring dest 1))
3948 (cond
3949 ((org-string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3950 (org-table-goto-field dest))
3951 ((org-string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
3952 dest)
3953 (org-table-goto-field dest))
3954 (t (org-table-goto-column (string-to-number name))))
3955 (move-marker pos (point))
3956 (org-table-highlight-rectangle nil nil face2))
3957 (cond
3958 ((equal dest match))
3959 ((not match))
3960 ((eq what 'range)
3961 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
3962 ((setq e (assoc var org-table-named-field-locations))
3963 (org-table-goto-field var)
3964 (org-table-highlight-rectangle)
3965 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3966 ((setq e (assoc var org-table-column-names))
3967 (org-table-goto-column (string-to-number (cdr e)))
3968 (org-table-highlight-rectangle)
3969 (goto-char table-start)
3970 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3971 (org-table-end) t)
3972 (progn
3973 (goto-char (match-beginning 1))
3974 (org-table-highlight-rectangle)
3975 (message "Named column (column %s)" (cdr e)))
3976 (user-error "Column name not found")))
3977 ((eq what 'column)
3978 ;; Column number.
3979 (org-table-goto-column (string-to-number (substring match 1)))
3980 (org-table-highlight-rectangle)
3981 (message "Column %s" (substring match 1)))
3982 ((setq e (assoc var org-table-local-parameters))
3983 (goto-char table-start)
3984 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3985 (progn
3986 (goto-char (match-beginning 1))
3987 (org-table-highlight-rectangle)
3988 (message "Local parameter."))
3989 (user-error "Parameter not found")))
3990 ((not var) (user-error "No reference at point"))
3991 ((setq e (assoc var org-table-formula-constants-local))
3992 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3993 var (cdr e)))
3994 ((setq e (assoc var org-table-formula-constants))
3995 (message "Constant: $%s=%s in `org-table-formula-constants'."
3996 var (cdr e)))
3997 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3998 (message "Constant: $%s=%s, from `constants.el'%s."
3999 var e (format " (%s units)" constants-unit-system)))
4000 (t (user-error "Undefined name $%s" var)))
4001 (goto-char pos)
4002 (when (and org-show-positions
4003 (not (memq this-command '(org-table-fedit-scroll
4004 org-table-fedit-scroll-down))))
4005 (push pos org-show-positions)
4006 (push table-start org-show-positions)
4007 (let ((min (apply 'min org-show-positions))
4008 (max (apply 'max org-show-positions)))
4009 (set-window-start (selected-window) min)
4010 (goto-char max)
4011 (or (pos-visible-in-window-p max)
4012 (set-window-start (selected-window) max))))
4013 (select-window win))))
4015 (defun org-table-force-dataline ()
4016 "Make sure the cursor is in a dataline in a table."
4017 (unless (save-excursion
4018 (beginning-of-line 1)
4019 (looking-at org-table-dataline-regexp))
4020 (let* ((re org-table-dataline-regexp)
4021 (p1 (save-excursion (re-search-forward re nil 'move)))
4022 (p2 (save-excursion (re-search-backward re nil 'move))))
4023 (cond ((and p1 p2)
4024 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4025 p1 p2)))
4026 ((or p1 p2) (goto-char (or p1 p2)))
4027 (t (user-error "No table dataline around here"))))))
4029 (defun org-table-fedit-line-up ()
4030 "Move cursor one line up in the window showing the table."
4031 (interactive)
4032 (org-table-fedit-move 'previous-line))
4034 (defun org-table-fedit-line-down ()
4035 "Move cursor one line down in the window showing the table."
4036 (interactive)
4037 (org-table-fedit-move 'next-line))
4039 (defun org-table-fedit-move (command)
4040 "Move the cursor in the window showing the table.
4041 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4042 (let ((org-table-allow-automatic-line-recalculation nil)
4043 (pos org-pos) (win (selected-window)) p)
4044 (select-window (get-buffer-window (marker-buffer org-pos)))
4045 (setq p (point))
4046 (call-interactively command)
4047 (while (and (org-at-table-p)
4048 (org-at-table-hline-p))
4049 (call-interactively command))
4050 (or (org-at-table-p) (goto-char p))
4051 (move-marker pos (point))
4052 (select-window win)))
4054 (defun org-table-fedit-scroll (N)
4055 (interactive "p")
4056 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4057 (scroll-other-window N)))
4059 (defun org-table-fedit-scroll-down (N)
4060 (interactive "p")
4061 (org-table-fedit-scroll (- N)))
4063 (defvar org-table-rectangle-overlays nil)
4065 (defun org-table-add-rectangle-overlay (beg end &optional face)
4066 "Add a new overlay."
4067 (let ((ov (make-overlay beg end)))
4068 (overlay-put ov 'face (or face 'secondary-selection))
4069 (push ov org-table-rectangle-overlays)))
4071 (defun org-table-highlight-rectangle (&optional beg end face)
4072 "Highlight rectangular region in a table.
4073 When buffer positions BEG and END are provided, use them to
4074 delimit the region to highlight. Otherwise, refer to point. Use
4075 FACE, when non-nil, for the highlight."
4076 (let* ((beg (or beg (point)))
4077 (end (or end (point)))
4078 (b (min beg end))
4079 (e (max beg end))
4080 (start-coordinates
4081 (save-excursion
4082 (goto-char b)
4083 (cons (line-beginning-position) (org-table-current-column))))
4084 (end-coordinates
4085 (save-excursion
4086 (goto-char e)
4087 (cons (line-beginning-position) (org-table-current-column)))))
4088 (when (boundp 'org-show-positions)
4089 (setq org-show-positions (cons b (cons e org-show-positions))))
4090 (goto-char (car start-coordinates))
4091 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4092 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4093 (last-row (car end-coordinates)))
4094 (while (<= (point) last-row)
4095 (when (looking-at org-table-dataline-regexp)
4096 (org-table-goto-column column-start)
4097 (skip-chars-backward "^|\n")
4098 (let ((p (point)))
4099 (org-table-goto-column column-end)
4100 (skip-chars-forward "^|\n")
4101 (org-table-add-rectangle-overlay p (point) face)))
4102 (forward-line)))
4103 (goto-char (car start-coordinates)))
4104 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4106 (defun org-table-remove-rectangle-highlight (&rest _ignore)
4107 "Remove the rectangle overlays."
4108 (unless org-inhibit-highlight-removal
4109 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4110 (mapc 'delete-overlay org-table-rectangle-overlays)
4111 (setq org-table-rectangle-overlays nil)))
4113 (defvar-local org-table-coordinate-overlays nil
4114 "Collects the coordinate grid overlays, so that they can be removed.")
4116 (defun org-table-overlay-coordinates ()
4117 "Add overlays to the table at point, to show row/column coordinates."
4118 (interactive)
4119 (mapc 'delete-overlay org-table-coordinate-overlays)
4120 (setq org-table-coordinate-overlays nil)
4121 (save-excursion
4122 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4123 (goto-char (org-table-begin))
4124 (while (org-at-table-p)
4125 (setq eol (point-at-eol))
4126 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4127 (push ov org-table-coordinate-overlays)
4128 (setq hline (looking-at org-table-hline-regexp))
4129 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4130 (format "%4d" (setq id (1+ id)))))
4131 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4132 (when hline
4133 (setq ic 0)
4134 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4135 (setq beg (1+ (match-beginning 0))
4136 ic (1+ ic)
4137 s1 (concat "$" (int-to-string ic))
4138 s2 (org-number-to-letters ic)
4139 str (if (eq org-table-use-standard-references t) s2 s1))
4140 (setq ov (make-overlay beg (+ beg (length str))))
4141 (push ov org-table-coordinate-overlays)
4142 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4143 (beginning-of-line 2)))))
4145 ;;;###autoload
4146 (defun org-table-toggle-coordinate-overlays ()
4147 "Toggle the display of Row/Column numbers in tables."
4148 (interactive)
4149 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4150 (message "Tables Row/Column numbers display turned %s"
4151 (if org-table-overlay-coordinates "on" "off"))
4152 (if (and (org-at-table-p) org-table-overlay-coordinates)
4153 (org-table-align))
4154 (unless org-table-overlay-coordinates
4155 (mapc 'delete-overlay org-table-coordinate-overlays)
4156 (setq org-table-coordinate-overlays nil)))
4158 ;;;###autoload
4159 (defun org-table-toggle-formula-debugger ()
4160 "Toggle the formula debugger in tables."
4161 (interactive)
4162 (setq org-table-formula-debug (not org-table-formula-debug))
4163 (message "Formula debugging has been turned %s"
4164 (if org-table-formula-debug "on" "off")))
4166 ;;; The orgtbl minor mode
4168 ;; Define a minor mode which can be used in other modes in order to
4169 ;; integrate the org-mode table editor.
4171 ;; This is really a hack, because the org-mode table editor uses several
4172 ;; keys which normally belong to the major mode, for example the TAB and
4173 ;; RET keys. Here is how it works: The minor mode defines all the keys
4174 ;; necessary to operate the table editor, but wraps the commands into a
4175 ;; function which tests if the cursor is currently inside a table. If that
4176 ;; is the case, the table editor command is executed. However, when any of
4177 ;; those keys is used outside a table, the function uses `key-binding' to
4178 ;; look up if the key has an associated command in another currently active
4179 ;; keymap (minor modes, major mode, global), and executes that command.
4180 ;; There might be problems if any of the keys used by the table editor is
4181 ;; otherwise used as a prefix key.
4183 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4184 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4185 ;; addresses this by checking explicitly for both bindings.
4187 ;; The optimized version (see variable `orgtbl-optimized') takes over
4188 ;; all keys which are bound to `self-insert-command' in the *global map*.
4189 ;; Some modes bind other commands to simple characters, for example
4190 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4191 ;; active, this binding is ignored inside tables and replaced with a
4192 ;; modified self-insert.
4195 (defvar orgtbl-mode-map (make-keymap)
4196 "Keymap for `orgtbl-mode'.")
4198 (defvar org-old-auto-fill-inhibit-regexp nil
4199 "Local variable used by `orgtbl-mode'.")
4201 (defconst orgtbl-line-start-regexp
4202 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4203 "Matches a line belonging to an orgtbl.")
4205 (defconst orgtbl-extra-font-lock-keywords
4206 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4207 0 (quote 'org-table) 'prepend))
4208 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4210 ;; Install it as a minor mode.
4211 (put 'orgtbl-mode :included t)
4212 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4214 ;;;###autoload
4215 (define-minor-mode orgtbl-mode
4216 "The `org-mode' table editor as a minor mode for use in other modes."
4217 :lighter " OrgTbl" :keymap orgtbl-mode-map
4218 (org-load-modules-maybe)
4219 (cond
4220 ((derived-mode-p 'org-mode)
4221 ;; Exit without error, in case some hook functions calls this
4222 ;; by accident in org-mode.
4223 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4224 (orgtbl-mode
4225 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4226 ;; Make sure we are first in minor-mode-map-alist
4227 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4228 ;; FIXME: maybe it should use emulation-mode-map-alists?
4229 (and c (setq minor-mode-map-alist
4230 (cons c (delq c minor-mode-map-alist)))))
4231 (setq-local org-table-may-need-update t)
4232 (org-add-hook 'before-change-functions 'org-before-change-function
4233 nil 'local)
4234 (setq-local org-old-auto-fill-inhibit-regexp
4235 auto-fill-inhibit-regexp)
4236 (setq-local auto-fill-inhibit-regexp
4237 (if auto-fill-inhibit-regexp
4238 (concat orgtbl-line-start-regexp "\\|"
4239 auto-fill-inhibit-regexp)
4240 orgtbl-line-start-regexp))
4241 (add-to-invisibility-spec '(org-cwidth))
4242 (when (fboundp 'font-lock-add-keywords)
4243 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4244 (org-restart-font-lock))
4245 (easy-menu-add orgtbl-mode-menu))
4247 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4248 (org-table-cleanup-narrow-column-properties)
4249 (org-remove-from-invisibility-spec '(org-cwidth))
4250 (remove-hook 'before-change-functions 'org-before-change-function t)
4251 (when (fboundp 'font-lock-remove-keywords)
4252 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4253 (org-restart-font-lock))
4254 (easy-menu-remove orgtbl-mode-menu)
4255 (force-mode-line-update 'all))))
4257 (defun org-table-cleanup-narrow-column-properties ()
4258 "Remove all properties related to narrow-column invisibility."
4259 (let ((s (point-min)))
4260 (while (setq s (text-property-any s (point-max)
4261 'display org-narrow-column-arrow))
4262 (remove-text-properties s (1+ s) '(display t)))
4263 (setq s (point-min))
4264 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4265 (remove-text-properties s (1+ s) '(org-cwidth t)))
4266 (setq s (point-min))
4267 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4268 (remove-text-properties s (1+ s) '(invisible t)))))
4270 (defun orgtbl-make-binding (fun n &rest keys)
4271 "Create a function for binding in the table minor mode.
4272 FUN is the command to call inside a table. N is used to create a unique
4273 command name. KEYS are keys that should be checked in for a command
4274 to execute outside of tables."
4275 (eval
4276 (list 'defun
4277 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4278 '(arg)
4279 (concat "In tables, run `" (symbol-name fun) "'.\n"
4280 "Outside of tables, run the binding of `"
4281 (mapconcat #'key-description keys "' or `")
4282 "'.")
4283 '(interactive "p")
4284 (list 'if
4285 '(org-at-table-p)
4286 (list 'call-interactively (list 'quote fun))
4287 (list 'let '(orgtbl-mode)
4288 (list 'call-interactively
4289 (append '(or)
4290 (mapcar (lambda (k)
4291 (list 'key-binding k))
4292 keys)
4293 '('orgtbl-error))))))))
4295 (defun orgtbl-error ()
4296 "Error when there is no default binding for a table key."
4297 (interactive)
4298 (user-error "This key has no function outside tables"))
4300 (defun orgtbl-setup ()
4301 "Setup orgtbl keymaps."
4302 (let ((nfunc 0)
4303 (bindings
4304 '(([(meta shift left)] org-table-delete-column)
4305 ([(meta left)] org-table-move-column-left)
4306 ([(meta right)] org-table-move-column-right)
4307 ([(meta shift right)] org-table-insert-column)
4308 ([(meta shift up)] org-table-kill-row)
4309 ([(meta shift down)] org-table-insert-row)
4310 ([(meta up)] org-table-move-row-up)
4311 ([(meta down)] org-table-move-row-down)
4312 ("\C-c\C-w" org-table-cut-region)
4313 ("\C-c\M-w" org-table-copy-region)
4314 ("\C-c\C-y" org-table-paste-rectangle)
4315 ("\C-c\C-w" org-table-wrap-region)
4316 ("\C-c-" org-table-insert-hline)
4317 ("\C-c}" org-table-toggle-coordinate-overlays)
4318 ("\C-c{" org-table-toggle-formula-debugger)
4319 ("\C-m" org-table-next-row)
4320 ([(shift return)] org-table-copy-down)
4321 ("\C-c?" org-table-field-info)
4322 ("\C-c " org-table-blank-field)
4323 ("\C-c+" org-table-sum)
4324 ("\C-c=" org-table-eval-formula)
4325 ("\C-c'" org-table-edit-formulas)
4326 ("\C-c`" org-table-edit-field)
4327 ("\C-c*" org-table-recalculate)
4328 ("\C-c^" org-table-sort-lines)
4329 ("\M-a" org-table-beginning-of-field)
4330 ("\M-e" org-table-end-of-field)
4331 ([(control ?#)] org-table-rotate-recalc-marks)))
4332 elt key fun cmd)
4333 (while (setq elt (pop bindings))
4334 (setq nfunc (1+ nfunc))
4335 (setq key (org-key (car elt))
4336 fun (nth 1 elt)
4337 cmd (orgtbl-make-binding fun nfunc key))
4338 (org-defkey orgtbl-mode-map key cmd))
4340 ;; Special treatment needed for TAB and RET
4341 (org-defkey orgtbl-mode-map [(return)]
4342 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4343 (org-defkey orgtbl-mode-map "\C-m"
4344 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4346 (org-defkey orgtbl-mode-map [(tab)]
4347 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4348 (org-defkey orgtbl-mode-map "\C-i"
4349 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4351 (org-defkey orgtbl-mode-map [(shift tab)]
4352 (orgtbl-make-binding 'org-table-previous-field 104
4353 [(shift tab)] [(tab)] "\C-i"))
4356 (unless (featurep 'xemacs)
4357 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4358 (orgtbl-make-binding 'org-table-previous-field 107
4359 [S-iso-lefttab] [backtab] [(shift tab)]
4360 [(tab)] "\C-i")))
4362 (org-defkey orgtbl-mode-map [backtab]
4363 (orgtbl-make-binding 'org-table-previous-field 108
4364 [backtab] [S-iso-lefttab] [(shift tab)]
4365 [(tab)] "\C-i"))
4367 (org-defkey orgtbl-mode-map "\M-\C-m"
4368 (orgtbl-make-binding 'org-table-wrap-region 105
4369 "\M-\C-m" [(meta return)]))
4370 (org-defkey orgtbl-mode-map [(meta return)]
4371 (orgtbl-make-binding 'org-table-wrap-region 106
4372 [(meta return)] "\M-\C-m"))
4374 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4375 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4377 (when orgtbl-optimized
4378 ;; If the user wants maximum table support, we need to hijack
4379 ;; some standard editing functions
4380 (org-remap orgtbl-mode-map
4381 'self-insert-command 'orgtbl-self-insert-command
4382 'delete-char 'org-delete-char
4383 'delete-backward-char 'org-delete-backward-char)
4384 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4385 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4386 '("OrgTbl"
4387 ["Create or convert" org-table-create-or-convert-from-region
4388 :active (not (org-at-table-p)) :keys "C-c |" ]
4389 "--"
4390 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4391 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4392 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4393 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4394 "--"
4395 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4396 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4397 ["Copy Field from Above"
4398 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4399 "--"
4400 ("Column"
4401 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4402 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4403 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4404 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4405 ("Row"
4406 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4407 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4408 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4409 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4410 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4411 "--"
4412 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4413 ("Rectangle"
4414 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4415 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4416 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4417 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4418 "--"
4419 ("Radio tables"
4420 ["Insert table template" orgtbl-insert-radio-table
4421 (assq major-mode orgtbl-radio-table-templates)]
4422 ["Comment/uncomment table" orgtbl-toggle-comment t])
4423 "--"
4424 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4425 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4426 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4427 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4428 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4429 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4430 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4431 ["Sum Column/Rectangle" org-table-sum
4432 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4433 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4434 ["Debug Formulas"
4435 org-table-toggle-formula-debugger :active (org-at-table-p)
4436 :keys "C-c {"
4437 :style toggle :selected org-table-formula-debug]
4438 ["Show Col/Row Numbers"
4439 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4440 :keys "C-c }"
4441 :style toggle :selected org-table-overlay-coordinates]
4442 "--"
4443 ("Plot"
4444 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4445 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4448 (defun orgtbl-ctrl-c-ctrl-c (arg)
4449 "If the cursor is inside a table, realign the table.
4450 If it is a table to be sent away to a receiver, do it.
4451 With prefix arg, also recompute table."
4452 (interactive "P")
4453 (let ((case-fold-search t) (pos (point)) action)
4454 (save-excursion
4455 (beginning-of-line 1)
4456 (setq action (cond
4457 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4458 ((looking-at "[ \t]*|") pos)
4459 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4460 (cond
4461 ((integerp action)
4462 (goto-char action)
4463 (org-table-maybe-eval-formula)
4464 (if arg
4465 (call-interactively 'org-table-recalculate)
4466 (org-table-maybe-recalculate-line))
4467 (call-interactively 'org-table-align)
4468 (when (orgtbl-send-table 'maybe)
4469 (run-hooks 'orgtbl-after-send-table-hook)))
4470 ((eq action 'recalc)
4471 (save-excursion
4472 (beginning-of-line 1)
4473 (skip-chars-backward " \r\n\t")
4474 (if (org-at-table-p)
4475 (org-call-with-arg 'org-table-recalculate t))))
4476 (t (let (orgtbl-mode)
4477 (call-interactively (key-binding "\C-c\C-c")))))))
4479 (defun orgtbl-create-or-convert-from-region (_arg)
4480 "Create table or convert region to table, if no conflicting binding.
4481 This installs the table binding `C-c |', but only if there is no
4482 conflicting binding to this key outside orgtbl-mode."
4483 (interactive "P")
4484 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4485 (if cmd
4486 (call-interactively cmd)
4487 (call-interactively 'org-table-create-or-convert-from-region))))
4489 (defun orgtbl-tab (arg)
4490 "Justification and field motion for `orgtbl-mode'."
4491 (interactive "P")
4492 (if arg (org-table-edit-field t)
4493 (org-table-justify-field-maybe)
4494 (org-table-next-field)))
4496 (defun orgtbl-ret ()
4497 "Justification and field motion for `orgtbl-mode'."
4498 (interactive)
4499 (if (bobp)
4500 (newline)
4501 (org-table-justify-field-maybe)
4502 (org-table-next-row)))
4504 (defun orgtbl-self-insert-command (N)
4505 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4506 If the cursor is in a table looking at whitespace, the whitespace is
4507 overwritten, and the table is not marked as requiring realignment."
4508 (interactive "p")
4509 (if (and (org-at-table-p)
4511 (and org-table-auto-blank-field
4512 (member last-command
4513 '(orgtbl-hijacker-command-100
4514 orgtbl-hijacker-command-101
4515 orgtbl-hijacker-command-102
4516 orgtbl-hijacker-command-103
4517 orgtbl-hijacker-command-104
4518 orgtbl-hijacker-command-105
4519 yas/expand))
4520 (org-table-blank-field))
4522 (eq N 1)
4523 (looking-at "[^|\n]* +|"))
4524 (let (org-table-may-need-update)
4525 (goto-char (1- (match-end 0)))
4526 (org-delete-backward-char 1)
4527 (goto-char (match-beginning 0))
4528 (self-insert-command N))
4529 (setq org-table-may-need-update t)
4530 (let* (orgtbl-mode
4532 (cmd (or (key-binding
4533 (or (and (listp function-key-map)
4534 (setq a (assoc last-input-event function-key-map))
4535 (cdr a))
4536 (vector last-input-event)))
4537 'self-insert-command)))
4538 (call-interactively cmd)
4539 (if (and org-self-insert-cluster-for-undo
4540 (eq cmd 'self-insert-command))
4541 (if (not (eq last-command 'orgtbl-self-insert-command))
4542 (setq org-self-insert-command-undo-counter 1)
4543 (if (>= org-self-insert-command-undo-counter 20)
4544 (setq org-self-insert-command-undo-counter 1)
4545 (and (> org-self-insert-command-undo-counter 0)
4546 buffer-undo-list
4547 (not (cadr buffer-undo-list)) ; remove nil entry
4548 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4549 (setq org-self-insert-command-undo-counter
4550 (1+ org-self-insert-command-undo-counter))))))))
4552 ;;;###autoload
4553 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4554 "Regular expression matching exponentials as produced by calc.")
4556 (defun orgtbl-gather-send-defs ()
4557 "Gather a plist of :name, :transform, :params for each destination before
4558 a radio table."
4559 (save-excursion
4560 (goto-char (org-table-begin))
4561 (let (rtn)
4562 (beginning-of-line 0)
4563 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4564 (let ((name (org-no-properties (match-string 1)))
4565 (transform (intern (match-string 2)))
4566 (params (if (match-end 3)
4567 (read (concat "(" (match-string 3) ")")))))
4568 (push (list :name name :transform transform :params params)
4569 rtn)
4570 (beginning-of-line 0)))
4571 rtn)))
4573 (defun orgtbl-send-replace-tbl (name txt)
4574 "Find and replace table NAME with TXT."
4575 (save-excursion
4576 (goto-char (point-min))
4577 (unless (re-search-forward
4578 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4579 (user-error "Don't know where to insert translated table"))
4580 (let ((beg (line-beginning-position 2)))
4581 (unless (re-search-forward
4582 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4583 (user-error "Cannot find end of insertion region"))
4584 (beginning-of-line)
4585 (delete-region beg (point)))
4586 (insert txt "\n")))
4588 ;;;###autoload
4589 (defun org-table-to-lisp (&optional txt)
4590 "Convert the table at point to a Lisp structure.
4591 The structure will be a list. Each item is either the symbol `hline'
4592 for a horizontal separator line, or a list of field values as strings.
4593 The table is taken from the parameter TXT, or from the buffer at point."
4594 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4595 (let ((txt (or txt
4596 (buffer-substring-no-properties (org-table-begin)
4597 (org-table-end)))))
4598 (mapcar (lambda (x)
4599 (if (string-match org-table-hline-regexp x) 'hline
4600 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4601 (org-split-string txt "[ \t]*\n[ \t]*"))))
4603 (defun orgtbl-send-table (&optional maybe)
4604 "Send a transformed version of table at point to the receiver position.
4605 With argument MAYBE, fail quietly if no transformation is defined
4606 for this table."
4607 (interactive)
4608 (catch 'exit
4609 (unless (org-at-table-p) (user-error "Not at a table"))
4610 ;; when non-interactive, we assume align has just happened.
4611 (when (org-called-interactively-p 'any) (org-table-align))
4612 (let ((dests (orgtbl-gather-send-defs))
4613 (table (org-table-to-lisp
4614 (buffer-substring-no-properties (org-table-begin)
4615 (org-table-end))))
4616 (ntbl 0))
4617 (unless dests
4618 (if maybe (throw 'exit nil)
4619 (user-error "Don't know how to transform this table")))
4620 (dolist (dest dests)
4621 (let ((name (plist-get dest :name))
4622 (transform (plist-get dest :transform))
4623 (params (plist-get dest :params)))
4624 (unless (fboundp transform)
4625 (user-error "No such transformation function %s" transform))
4626 (orgtbl-send-replace-tbl name (funcall transform table params)))
4627 (incf ntbl))
4628 (message "Table converted and installed at %d receiver location%s"
4629 ntbl (if (> ntbl 1) "s" ""))
4630 (and (> ntbl 0) ntbl))))
4632 (defun org-remove-by-index (list indices &optional i0)
4633 "Remove the elements in LIST with indices in INDICES.
4634 First element has index 0, or I0 if given."
4635 (if (not indices)
4636 list
4637 (if (integerp indices) (setq indices (list indices)))
4638 (setq i0 (1- (or i0 0)))
4639 (delq :rm (mapcar (lambda (x)
4640 (setq i0 (1+ i0))
4641 (if (memq i0 indices) :rm x))
4642 list))))
4644 (defun orgtbl-toggle-comment ()
4645 "Comment or uncomment the orgtbl at point."
4646 (interactive)
4647 (let* ((case-fold-search t)
4648 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4649 (re2 (concat "^" orgtbl-line-start-regexp))
4650 (commented (save-excursion (beginning-of-line 1)
4651 (cond ((looking-at re1) t)
4652 ((looking-at re2) nil)
4653 (t (user-error "Not at an org table")))))
4654 (re (if commented re1 re2))
4655 beg end)
4656 (save-excursion
4657 (beginning-of-line 1)
4658 (while (looking-at re) (beginning-of-line 0))
4659 (beginning-of-line 2)
4660 (setq beg (point))
4661 (while (looking-at re) (beginning-of-line 2))
4662 (setq end (point)))
4663 (comment-region beg end (if commented '(4) nil))))
4665 (defun orgtbl-insert-radio-table ()
4666 "Insert a radio table template appropriate for this major mode."
4667 (interactive)
4668 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4669 (txt (nth 1 e))
4670 name pos)
4671 (unless e (user-error "No radio table setup defined for %s" major-mode))
4672 (setq name (read-string "Table name: "))
4673 (while (string-match "%n" txt)
4674 (setq txt (replace-match name t t txt)))
4675 (or (bolp) (insert "\n"))
4676 (setq pos (point))
4677 (insert txt)
4678 (goto-char pos)))
4680 ;;;###autoload
4681 (defun orgtbl-to-generic (table params)
4682 "Convert the orgtbl-mode TABLE to some other format.
4684 This generic routine can be used for many standard cases.
4686 TABLE is a list, each entry either the symbol `hline' for
4687 a horizontal separator line, or a list of fields for that
4688 line. PARAMS is a property list of parameters that can
4689 influence the conversion.
4691 Valid parameters are:
4693 :backend, :raw
4695 Export back-end used as a basis to transcode elements of the
4696 table, when no specific parameter applies to it. It is also
4697 used to translate cells contents. You can prevent this by
4698 setting :raw property to a non-nil value.
4700 :splice
4702 When non-nil, only convert rows, not the table itself. This is
4703 equivalent to setting to the empty string both :tstart
4704 and :tend, which see.
4706 :skip
4708 When set to an integer N, skip the first N lines of the table.
4709 Horizontal separation lines do count for this parameter!
4711 :skipcols
4713 List of columns that should be skipped. If the table has
4714 a column with calculation marks, that column is automatically
4715 discarded beforehand.
4717 :hline
4719 String to be inserted on horizontal separation lines. May be
4720 nil to ignore these lines altogether.
4722 :sep
4724 Separator between two fields, as a string.
4726 Each in the following group may be either a string or a function
4727 of no arguments returning a string:
4729 :tstart, :tend
4731 Strings to start and end the table. Ignored when :splice is t.
4733 :lstart, :lend
4735 Strings to start and end a new table line.
4737 :llstart, :llend
4739 Strings to start and end the last table line. Default,
4740 respectively, to :lstart and :lend.
4742 Each in the following group may be a string or a function of one
4743 argument (either the cells in the current row, as a list of
4744 strings, or the current cell) returning a string:
4746 :lfmt
4748 Format string for an entire row, with enough %s to capture all
4749 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4751 :llfmt
4753 Format for the entire last line, defaults to :lfmt.
4755 :fmt
4757 A format to be used to wrap the field, should contain %s for
4758 the original field value. For example, to wrap everything in
4759 dollars, you could use :fmt \"$%s$\". This may also be
4760 a property list with column numbers and format strings, or
4761 functions, e.g.,
4763 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4765 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4767 Same as above, specific for the header lines in the table.
4768 All lines before the first hline are treated as header. If
4769 any of these is not present, the data line value is used.
4771 This may be either a string or a function of two arguments:
4773 :efmt
4775 Use this format to print numbers with exponential. The format
4776 should have %s twice for inserting mantissa and exponent, for
4777 example \"%s\\\\times10^{%s}\". This may also be a property
4778 list with column numbers and format strings or functions.
4779 :fmt will still be applied after :efmt."
4780 ;; Make sure `org-export-create-backend' is available.
4781 (require 'ox)
4782 (let* ((backend (plist-get params :backend))
4783 (custom-backend
4784 ;; Build a custom back-end according to PARAMS. Before
4785 ;; defining a translator, check if there is anything to do.
4786 ;; When there isn't, let BACKEND handle the element.
4787 (org-export-create-backend
4788 :parent (or backend 'org)
4789 :transcoders
4790 `((table . ,(org-table--to-generic-table params))
4791 (table-row . ,(org-table--to-generic-row params))
4792 (table-cell . ,(org-table--to-generic-cell params))
4793 ;; Macros are not going to be expanded. However, no
4794 ;; regular back-end has a transcoder for them. We
4795 ;; provide one so they are not ignored, but displayed
4796 ;; as-is instead.
4797 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4798 data info)
4799 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4800 ;; Initialize communication channel in INFO.
4801 (with-temp-buffer
4802 (let ((org-inhibit-startup t)) (org-mode))
4803 (let ((standard-output (current-buffer)))
4804 (dolist (e table)
4805 (cond ((eq e 'hline) (princ "|--\n"))
4806 ((consp e)
4807 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4808 (princ "\n")))))
4809 (setq data
4810 (org-element-map (org-element-parse-buffer) 'table
4811 #'identity nil t))
4812 (setq info (org-export-get-environment backend nil params)))
4813 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4814 (user-error "Unknown :backend value"))
4815 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4816 ;; Handle :skip parameter.
4817 (let ((skip (plist-get info :skip)))
4818 (when skip
4819 (unless (wholenump skip) (user-error "Wrong :skip value"))
4820 (let ((n 0))
4821 (org-element-map data 'table-row
4822 (lambda (row)
4823 (if (>= n skip) t
4824 (org-element-extract-element row)
4825 (incf n)
4826 nil))
4827 nil t))))
4828 ;; Handle :skipcols parameter.
4829 (let ((skipcols (plist-get info :skipcols)))
4830 (when skipcols
4831 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4832 (org-element-map data 'table
4833 (lambda (table)
4834 (let ((specialp (org-export-table-has-special-column-p table)))
4835 (dolist (row (org-element-contents table))
4836 (when (eq (org-element-property :type row) 'standard)
4837 (let ((c 1))
4838 (dolist (cell (nthcdr (if specialp 1 0)
4839 (org-element-contents row)))
4840 (when (memq c skipcols)
4841 (org-element-extract-element cell))
4842 (incf c))))))))))
4843 ;; Since we are going to export using a low-level mechanism,
4844 ;; ignore special column and special rows manually.
4845 (let ((special? (org-export-table-has-special-column-p data))
4846 ignore)
4847 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4848 (lambda (datum)
4849 (when (if (eq (org-element-type datum) 'table-row)
4850 (org-export-table-row-is-special-p datum nil)
4851 (org-export-first-sibling-p datum nil))
4852 (push datum ignore))))
4853 (setq info (plist-put info :ignore-list ignore)))
4854 ;; We use a low-level mechanism to export DATA so as to skip all
4855 ;; usual pre-processing and post-processing, i.e., hooks, filters,
4856 ;; Babel code evaluation, include keywords and macro expansion,
4857 ;; and filters.
4858 (let ((output (org-export-data-with-backend data custom-backend info)))
4859 ;; Remove final newline.
4860 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4862 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4863 (cond ((null value) nil)
4864 ((functionp value) `(funcall ',value ,@args))
4865 ((stringp value)
4866 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4867 (args `(format ,value ,@args))
4868 (t value)))
4869 ((and with-cons (consp value))
4870 `(let ((val (cadr (memq column ',value))))
4871 (cond ((null val) contents)
4872 ((stringp val) (format val ,@args))
4873 ((functionp val) (funcall val ,@args))
4874 (t (user-error "Wrong %s value" ,name)))))
4875 (t (user-error "Wrong %s value" name))))
4877 (defun org-table--to-generic-table (params)
4878 "Return custom table transcoder according to PARAMS.
4879 PARAMS is a plist. See `orgtbl-to-generic' for more
4880 information."
4881 (let ((backend (plist-get params :backend))
4882 (splice (plist-get params :splice))
4883 (tstart (plist-get params :tstart))
4884 (tend (plist-get params :tend)))
4885 `(lambda (table contents info)
4886 (concat
4887 ,(and tstart (not splice)
4888 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4889 ,(if (or (not backend) tstart tend splice) 'contents
4890 `(org-export-with-backend ',backend table contents info))
4891 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4893 (defun org-table--to-generic-row (params)
4894 "Return custom table row transcoder according to PARAMS.
4895 PARAMS is a plist. See `orgtbl-to-generic' for more
4896 information."
4897 (let* ((backend (plist-get params :backend))
4898 (lstart (plist-get params :lstart))
4899 (llstart (plist-get params :llstart))
4900 (hlstart (plist-get params :hlstart))
4901 (hllstart (plist-get params :hllstart))
4902 (lend (plist-get params :lend))
4903 (llend (plist-get params :llend))
4904 (hlend (plist-get params :hlend))
4905 (hllend (plist-get params :hllend))
4906 (lfmt (plist-get params :lfmt))
4907 (llfmt (plist-get params :llfmt))
4908 (hlfmt (plist-get params :hlfmt))
4909 (hllfmt (plist-get params :hllfmt)))
4910 `(lambda (row contents info)
4911 (if (eq (org-element-property :type row) 'rule)
4912 ,(cond
4913 ((plist-member params :hline)
4914 (org-table--generic-apply (plist-get params :hline) ":hline"))
4915 (backend `(org-export-with-backend ',backend row nil info)))
4916 (let ((headerp (org-export-table-row-in-header-p row info))
4917 (lastp (not (org-export-get-next-element row info)))
4918 (last-header-p (org-export-table-row-ends-header-p row info)))
4919 (when contents
4920 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4921 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4922 ;; `:lstart', `:lend' and their relatives.
4923 ,(let ((cells
4924 '(org-element-map row 'table-cell
4925 (lambda (cell)
4926 ;; Export all cells, without separators.
4928 ;; Use `org-export-data-with-backend'
4929 ;; instead of `org-export-data' to eschew
4930 ;; cached values, which
4931 ;; ignore :orgtbl-ignore-sep parameter.
4932 (org-export-data-with-backend
4933 cell
4934 (plist-get info :back-end)
4935 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4936 info)))
4937 `(cond
4938 ,(and hllfmt
4939 `(last-header-p ,(org-table--generic-apply
4940 hllfmt ":hllfmt" nil cells)))
4941 ,(and hlfmt
4942 `(headerp ,(org-table--generic-apply
4943 hlfmt ":hlfmt" nil cells)))
4944 ,(and llfmt
4945 `(lastp ,(org-table--generic-apply
4946 llfmt ":llfmt" nil cells)))
4948 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4949 `(concat
4950 (cond
4951 ,(and
4952 (or hllstart hllend)
4953 `(last-header-p
4954 (concat
4955 ,(org-table--generic-apply hllstart ":hllstart")
4956 contents
4957 ,(org-table--generic-apply hllend ":hllend"))))
4958 ,(and
4959 (or hlstart hlend)
4960 `(headerp
4961 (concat
4962 ,(org-table--generic-apply hlstart ":hlstart")
4963 contents
4964 ,(org-table--generic-apply hlend ":hlend"))))
4965 ,(and
4966 (or llstart llend)
4967 `(lastp
4968 (concat
4969 ,(org-table--generic-apply llstart ":llstart")
4970 contents
4971 ,(org-table--generic-apply llend ":llend"))))
4973 ,(cond
4974 ((or lstart lend)
4975 `(concat
4976 ,(org-table--generic-apply lstart ":lstart")
4977 contents
4978 ,(org-table--generic-apply lend ":lend")))
4979 (backend
4980 `(org-export-with-backend
4981 ',backend row contents info))
4982 (t 'contents)))))))))))))))
4984 (defun org-table--to-generic-cell (params)
4985 "Return custom table cell transcoder according to PARAMS.
4986 PARAMS is a plist. See `orgtbl-to-generic' for more
4987 information."
4988 (let* ((backend (plist-get params :backend))
4989 (efmt (plist-get params :efmt))
4990 (fmt (plist-get params :fmt))
4991 (hfmt (plist-get params :hfmt))
4992 (sep (plist-get params :sep))
4993 (hsep (plist-get params :hsep)))
4994 `(lambda (cell contents info)
4995 (let ((headerp (org-export-table-row-in-header-p
4996 (org-export-get-parent-element cell) info))
4997 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4998 ;; Make sure that contents are exported as Org data when :raw
4999 ;; parameter is non-nil.
5000 ,(when (and backend (plist-get params :raw))
5001 `(setq contents
5002 ;; Since we don't know what are the pseudo object
5003 ;; types defined in backend, we cannot pass them to
5004 ;; `org-element-interpret-data'. As a consequence,
5005 ;; they will be treated as pseudo elements, and
5006 ;; will have newlines appended instead of spaces.
5007 ;; Therefore, we must make sure :post-blank value
5008 ;; is really turned into spaces.
5009 (replace-regexp-in-string
5010 "\n" " "
5011 (org-trim
5012 (org-element-interpret-data
5013 (org-element-contents cell))))))
5014 (when contents
5015 ;; Check if we can apply `:efmt' on CONTENTS.
5016 ,(when efmt
5017 `(when (string-match orgtbl-exp-regexp contents)
5018 (let ((mantissa (match-string 1 contents))
5019 (exponent (match-string 2 contents)))
5020 (setq contents ,(org-table--generic-apply
5021 efmt ":efmt" t 'mantissa 'exponent)))))
5022 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5023 (cond
5024 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5025 hfmt ":hfmt" t 'contents))))
5026 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5027 fmt ":fmt" t 'contents))))))
5028 ;; If a separator is provided, use it instead of BACKEND's.
5029 ;; Separators are ignored when LFMT (or equivalent) is
5030 ;; provided.
5031 ,(cond
5032 ((or hsep sep)
5033 `(if (or ,(and (not sep) '(not headerp))
5034 (plist-get info :orgtbl-ignore-sep)
5035 (not (org-export-get-next-element cell info)))
5036 ,(if (not backend) 'contents
5037 `(org-export-with-backend ',backend cell contents info))
5038 (concat contents
5039 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5040 (or hsep sep)))))
5041 (backend `(org-export-with-backend ',backend cell contents info))
5042 (t 'contents))))))
5044 ;;;###autoload
5045 (defun orgtbl-to-tsv (table params)
5046 "Convert the orgtbl-mode table to TAB separated material."
5047 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5049 ;;;###autoload
5050 (defun orgtbl-to-csv (table params)
5051 "Convert the orgtbl-mode table to CSV material.
5052 This does take care of the proper quoting of fields with comma or quotes."
5053 (orgtbl-to-generic table
5054 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5055 params)))
5057 ;;;###autoload
5058 (defun orgtbl-to-latex (table params)
5059 "Convert the orgtbl-mode TABLE to LaTeX.
5061 TABLE is a list, each entry either the symbol `hline' for
5062 a horizontal separator line, or a list of fields for that line.
5063 PARAMS is a property list of parameters that can influence the
5064 conversion. All parameters from `orgtbl-to-generic' are
5065 supported. It is also possible to use the following ones:
5067 :booktabs
5069 When non-nil, use formal \"booktabs\" style.
5071 :environment
5073 Specify environment to use, as a string. If you use
5074 \"longtable\", you may also want to specify :language property,
5075 as a string, to get proper continuation strings."
5076 (require 'ox-latex)
5077 (orgtbl-to-generic
5078 table
5079 (org-combine-plists
5080 ;; Provide sane default values.
5081 (list :backend 'latex
5082 :latex-default-table-mode 'table
5083 :latex-tables-centered nil
5084 :latex-tables-booktabs (plist-get params :booktabs)
5085 :latex-table-scientific-notation nil
5086 :latex-default-table-environment
5087 (or (plist-get params :environment) "tabular"))
5088 params)))
5090 ;;;###autoload
5091 (defun orgtbl-to-html (table params)
5092 "Convert the orgtbl-mode TABLE to HTML.
5094 TABLE is a list, each entry either the symbol `hline' for
5095 a horizontal separator line, or a list of fields for that line.
5096 PARAMS is a property list of parameters that can influence the
5097 conversion. All parameters from `orgtbl-to-generic' are
5098 supported. It is also possible to use the following one:
5100 :attributes
5102 Attributes and values, as a plist, which will be used in
5103 <table> tag."
5104 (require 'ox-html)
5105 (orgtbl-to-generic
5106 table
5107 (org-combine-plists
5108 ;; Provide sane default values.
5109 (list :backend 'html
5110 :html-table-data-tags '("<td%s>" . "</td>")
5111 :html-table-use-header-tags-for-first-column nil
5112 :html-table-align-individual-fields t
5113 :html-table-row-tags '("<tr>" . "</tr>")
5114 :html-table-attributes
5115 (if (plist-member params :attributes)
5116 (plist-get params :attributes)
5117 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5118 :frame "hsides")))
5119 params)))
5121 ;;;###autoload
5122 (defun orgtbl-to-texinfo (table params)
5123 "Convert the orgtbl-mode TABLE to Texinfo.
5125 TABLE is a list, each entry either the symbol `hline' for
5126 a horizontal separator line, or a list of fields for that line.
5127 PARAMS is a property list of parameters that can influence the
5128 conversion. All parameters from `orgtbl-to-generic' are
5129 supported. It is also possible to use the following one:
5131 :columns
5133 Column widths, as a string. When providing column fractions,
5134 \"@columnfractions\" command can be omitted."
5135 (require 'ox-texinfo)
5136 (let ((output
5137 (orgtbl-to-generic
5138 table
5139 (org-combine-plists
5140 (list :backend 'texinfo
5141 :texinfo-tables-verbatim nil
5142 :texinfo-table-scientific-notation nil)
5143 params)))
5144 (columns (let ((w (plist-get params :columns)))
5145 (cond ((not w) nil)
5146 ((org-string-match-p "{\\|@columnfractions " w) w)
5147 (t (concat "@columnfractions " w))))))
5148 (if (not columns) output
5149 (replace-regexp-in-string
5150 "@multitable \\(.*\\)" columns output t nil 1))))
5152 ;;;###autoload
5153 (defun orgtbl-to-orgtbl (table params)
5154 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5156 TABLE is a list, each entry either the symbol `hline' for
5157 a horizontal separator line, or a list of fields for that line.
5158 PARAMS is a property list of parameters that can influence the
5159 conversion. All parameters from `orgtbl-to-generic' are
5160 supported.
5162 Useful when slicing one table into many. The :hline, :sep,
5163 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5164 be set to provide ORGTBL directives for the generated table."
5165 (require 'ox-org)
5166 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5168 (defun orgtbl-to-table.el (table params)
5169 "Convert the orgtbl-mode TABLE into a table.el table.
5170 TABLE is a list, each entry either the symbol `hline' for
5171 a horizontal separator line, or a list of fields for that line.
5172 PARAMS is a property list of parameters that can influence the
5173 conversion. All parameters from `orgtbl-to-generic' are
5174 supported."
5175 (with-temp-buffer
5176 (insert (orgtbl-to-orgtbl table params))
5177 (org-table-align)
5178 (replace-regexp-in-string
5179 "-|" "-+"
5180 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5182 (defun orgtbl-to-unicode (table params)
5183 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5185 TABLE is a list, each entry either the symbol `hline' for
5186 a horizontal separator line, or a list of fields for that line.
5187 PARAMS is a property list of parameters that can influence the
5188 conversion. All parameters from `orgtbl-to-generic' are
5189 supported. It is also possible to use the following ones:
5191 :ascii-art
5193 When non-nil, use \"ascii-art-to-unicode\" package to translate
5194 the table. You can download it here:
5195 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5197 :narrow
5199 When non-nil, narrow columns width than provided width cookie,
5200 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5201 (require 'ox-ascii)
5202 (orgtbl-to-generic
5203 table
5204 (org-combine-plists
5205 (list :backend 'ascii
5206 :ascii-charset 'utf-8
5207 :ascii-table-widen-columns (not (plist-get params :narrow))
5208 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5209 params)))
5211 ;; Put the cursor in a column containing numerical values
5212 ;; of an Org-Mode table,
5213 ;; type C-c " a
5214 ;; A new column is added with a bar plot.
5215 ;; When the table is refreshed (C-u C-c *),
5216 ;; the plot is updated to reflect the new values.
5218 (defun orgtbl-ascii-draw (value min max &optional width characters)
5219 "Draw an ascii bar in a table.
5220 VALUE is a the value to plot, the width of the bar to draw. A
5221 value equal to MIN will be displayed as empty (zero width bar).
5222 A value equal to MAX will draw a bar filling all the WIDTH.
5223 WIDTH is the expected width in characters of the column.
5224 CHARACTERS is a string that will compose the bar, with shades of
5225 grey from pure white to pure black. It defaults to a 10
5226 characters string of regular ascii characters."
5227 (let* ((characters (or characters " .:;c!lhVHW"))
5228 (width (or width 12))
5229 (value (if (numberp value) value (string-to-number value)))
5230 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5231 (cond
5232 ((< value 0) "too small")
5233 ((> value width) "too large")
5235 (let ((len (1- (length characters))))
5236 (concat
5237 (make-string (floor value) (elt characters len))
5238 (string (elt characters
5239 (floor (* (- value (floor value)) len))))))))))
5241 ;;;###autoload
5242 (defun orgtbl-ascii-plot (&optional ask)
5243 "Draw an ascii bar plot in a column.
5244 With cursor in a column containing numerical values, this
5245 function will draw a plot in a new column.
5246 ASK, if given, is a numeric prefix to override the default 12
5247 characters width of the plot. ASK may also be the
5248 \\[universal-argument] prefix, which will prompt for the width."
5249 (interactive "P")
5250 (let ((col (org-table-current-column))
5251 (min 1e999) ; 1e999 will be converted to infinity
5252 (max -1e999) ; which is the desired result
5253 (table (org-table-to-lisp))
5254 (length
5255 (cond ((consp ask)
5256 (read-number "Length of column " 12))
5257 ((numberp ask) ask)
5258 (t 12))))
5259 ;; Skip any hline a the top of table.
5260 (while (eq (car table) 'hline) (setq table (cdr table)))
5261 ;; Skip table header if any.
5262 (dolist (x (or (cdr (memq 'hline table)) table))
5263 (when (consp x)
5264 (setq x (nth (1- col) x))
5265 (when (string-match
5266 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5268 (setq x (string-to-number x))
5269 (when (> min x) (setq min x))
5270 (when (< max x) (setq max x)))))
5271 (org-table-insert-column)
5272 (org-table-move-column-right)
5273 (org-table-store-formulas
5274 (cons
5275 (cons
5276 (number-to-string (1+ col))
5277 (format "'(%s $%s %s %s %s)"
5278 "orgtbl-ascii-draw" col min max length))
5279 (org-table-get-stored-formulas)))
5280 (org-table-recalculate t)))
5282 ;; Example of extension: unicode characters
5283 ;; Here are two examples of different styles.
5285 ;; Unicode block characters are used to give a smooth effect.
5286 ;; See http://en.wikipedia.org/wiki/Block_Elements
5287 ;; Use one of those drawing functions
5288 ;; - orgtbl-ascii-draw (the default ascii)
5289 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5290 ;; - orgtbl-uc-draw-cont (smooth unicode)
5292 ;; This is best viewed with the "DejaVu Sans Mono" font
5293 ;; (use M-x set-default-font).
5295 (defun orgtbl-uc-draw-grid (value min max &optional width)
5296 "Draw a bar in a table using block unicode characters.
5297 It is a variant of orgtbl-ascii-draw with Unicode block
5298 characters, for a smooth display. Bars appear as grids (to the
5299 extent the font allows)."
5300 ;; http://en.wikipedia.org/wiki/Block_Elements
5301 ;; best viewed with the "DejaVu Sans Mono" font.
5302 (orgtbl-ascii-draw value min max width
5303 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5305 (defun orgtbl-uc-draw-cont (value min max &optional width)
5306 "Draw a bar in a table using block unicode characters.
5307 It is a variant of orgtbl-ascii-draw with Unicode block
5308 characters, for a smooth display. Bars are solid (to the extent
5309 the font allows)."
5310 (orgtbl-ascii-draw value min max width
5311 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5313 (defun org-table-get-remote-range (name-or-id form)
5314 "Get a field value or a list of values in a range from table at ID.
5316 NAME-OR-ID may be the name of a table in the current file as set
5317 by a \"#+NAME:\" directive. The first table following this line
5318 will then be used. Alternatively, it may be an ID referring to
5319 any entry, also in a different file. In this case, the first
5320 table in that entry will be referenced.
5321 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5322 \"@I$2..@II$2\". All the references must be absolute, not relative.
5324 The return value is either a single string for a single field, or a
5325 list of the fields in the rectangle."
5326 (save-match-data
5327 (let ((case-fold-search t) (id-loc nil)
5328 ;; Protect a bunch of variables from being overwritten by
5329 ;; the context of the remote table.
5330 org-table-column-names org-table-column-name-regexp
5331 org-table-local-parameters org-table-named-field-locations
5332 org-table-current-line-types
5333 org-table-current-begin-pos org-table-dlines
5334 org-table-current-ncol
5335 org-table-hlines org-table-last-alignment
5336 org-table-last-column-widths org-table-last-alignment
5337 org-table-last-column-widths
5338 buffer loc)
5339 (setq form (org-table-convert-refs-to-rc form))
5340 (org-with-wide-buffer
5341 (goto-char (point-min))
5342 (if (re-search-forward
5343 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5344 (regexp-quote name-or-id) "[ \t]*$")
5345 nil t)
5346 (setq buffer (current-buffer) loc (match-beginning 0))
5347 (setq id-loc (org-id-find name-or-id 'marker))
5348 (unless (and id-loc (markerp id-loc))
5349 (user-error "Can't find remote table \"%s\"" name-or-id))
5350 (setq buffer (marker-buffer id-loc)
5351 loc (marker-position id-loc))
5352 (move-marker id-loc nil))
5353 (with-current-buffer buffer
5354 (org-with-wide-buffer
5355 (goto-char loc)
5356 (forward-char 1)
5357 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5358 (not (match-beginning 1)))
5359 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5360 (org-table-analyze)
5361 (setq form (org-table-formula-substitute-names
5362 (org-table-formula-handle-first/last-rc form)))
5363 (if (and (string-match org-table-range-regexp form)
5364 (> (length (match-string 0 form)) 1))
5365 (org-table-get-range
5366 (match-string 0 form) org-table-current-begin-pos 1)
5367 form)))))))
5369 (defun org-table-remote-reference-indirection (form)
5370 "Return formula with table remote references substituted by indirection.
5371 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5372 This indirection works only with the format @ROW$COLUMN. The
5373 format \"B3\" is not supported because it can not be
5374 distinguished from a plain table name or ID."
5375 (let ((start 0))
5376 (while (string-match (concat
5377 ;; Same as in `org-table-eval-formula'.
5378 "\\<remote([ \t]*\\("
5379 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5380 "[@$][^ \t,]+"
5381 ;; Same as in `org-table-eval-formula'.
5382 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5383 form
5384 start)
5385 ;; The position of the character as far as possible to the right
5386 ;; that will not be replaced and particularly not be shifted by
5387 ;; `replace-match'.
5388 (setq start (match-beginning 1))
5389 ;; Substitute the remote reference with the value found in the
5390 ;; field.
5391 (setq form
5392 (replace-match
5393 (save-match-data
5394 (org-table-get-range (org-table-formula-handle-first/last-rc
5395 (match-string 1 form))))
5396 t t form 1))))
5397 form)
5399 (defmacro org-define-lookup-function (mode)
5400 (let ((mode-str (symbol-name mode))
5401 (first-p (equal mode 'first))
5402 (all-p (equal mode 'all)))
5403 (let ((plural-str (if all-p "s" "")))
5404 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5405 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5406 If R-LIST is nil, return matching element%s of S-LIST.
5407 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5408 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5409 This function is generated by a call to the macro `org-define-lookup-function'."
5410 mode-str plural-str plural-str plural-str)
5411 (let ,(let ((lvars '((p (or predicate 'equal))
5412 (sl s-list)
5413 (rl (or r-list s-list))
5414 (ret nil))))
5415 (if first-p (cons '(match-p nil) lvars) lvars))
5416 (while ,(if first-p '(and (not match-p) sl) 'sl)
5417 (when (funcall p val (car sl))
5418 ,(when first-p '(setq match-p t))
5419 (let ((rval (car rl)))
5420 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5421 (setq sl (cdr sl) rl (cdr rl)))
5422 ret)))))
5424 (org-define-lookup-function first)
5425 (org-define-lookup-function last)
5426 (org-define-lookup-function all)
5428 (provide 'org-table)
5430 ;; Local variables:
5431 ;; generated-autoload-file: "org-loaddefs.el"
5432 ;; End:
5434 ;;; org-table.el ends here