Backport quote-related commits from Emacs
[org-mode.git] / lisp / org-table.el
blob0f4308ed76214f3bc07d220be507623d2f5221aa
1 ;;; org-table.el --- The table editor for Org mode
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 'org)
41 (declare-function org-element-at-point "org-element" ())
42 (declare-function org-element-contents "org-element" (element))
43 (declare-function org-element-extract-element "org-element" (element))
44 (declare-function org-element-interpret-data "org-element" (data))
45 (declare-function org-element-lineage "org-element"
46 (blob &optional types with-self))
47 (declare-function org-element-map "org-element"
48 (data types fun
49 &optional info first-match no-recursion with-affiliated))
50 (declare-function org-element-parse-buffer "org-element"
51 (&optional granularity visible-only))
52 (declare-function org-element-property "org-element" (property element))
53 (declare-function org-element-type "org-element" (element))
55 (declare-function org-export-create-backend "org-export" (&rest rest))
56 (declare-function org-export-data-with-backend "org-export" (arg1 arg2 arg3))
57 (declare-function org-export-first-sibling-p "org-export" (arg1 arg2))
58 (declare-function org-export-get-backend "org-export" (arg1))
59 (declare-function org-export-get-environment "org-export" (&optional arg1 arg2 arg3))
60 (declare-function org-export-table-has-special-column-p "org-export" (arg1))
61 (declare-function org-export-table-row-is-special-p "org-export" (arg1 arg2))
63 (declare-function calc-eval "calc" (str &optional separator &rest args))
65 (defvar orgtbl-mode) ; defined below
66 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
67 (defvar constants-unit-system)
68 (defvar org-table-follow-field-mode)
70 (defvar orgtbl-after-send-table-hook nil
71 "Hook for functions attaching to `C-c C-c', if the table is sent.
72 This can be used to add additional functionality after the table is sent
73 to the receiver position, otherwise, if table is not sent, the functions
74 are not run.")
76 (defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
78 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
79 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
80 In the optimized version, the table editor takes over all simple keys that
81 normally just insert a character. In tables, the characters are inserted
82 in a way to minimize disturbing the table structure (i.e. in overwrite mode
83 for empty fields). Outside tables, the correct binding of the keys is
84 restored.
86 The default for this option is t if the optimized version is also used in
87 Org-mode. See the variable `org-enable-table-editor' for details. Changing
88 this variable requires a restart of Emacs to become effective."
89 :group 'org-table
90 :type 'boolean)
92 (defcustom orgtbl-radio-table-templates
93 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
94 % END RECEIVE ORGTBL %n
95 \\begin{comment}
96 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
97 | | |
98 \\end{comment}\n")
99 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
100 @c END RECEIVE ORGTBL %n
101 @ignore
102 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
103 | | |
104 @end ignore\n")
105 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
106 <!-- END RECEIVE ORGTBL %n -->
107 <!--
108 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
109 | | |
110 -->\n")
111 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
112 #+ END RECEIVE ORGTBL %n
114 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
115 | | |
117 "Templates for radio tables in different major modes.
118 Each template must define lines that will be treated as a comment and that
119 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
120 lines where \"%n\" will be replaced with the name of the table during
121 insertion of the template. The transformed table will later be inserted
122 between these lines.
124 The template should also contain a minimal table in a multiline comment.
125 If multiline comments are not possible in the buffer language,
126 you can pack it into a string that will not be used when the code
127 is compiled or executed. Above the table will you need a line with
128 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
129 convert the table into a data structure useful in the
130 language of the buffer. Check the manual for the section on
131 \"Translator functions\", and more generally check out
132 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
134 All occurrences of %n in a template will be replaced with the name of the
135 table, obtained by prompting the user."
136 :group 'org-table
137 :type '(repeat
138 (list (symbol :tag "Major mode")
139 (string :tag "Format"))))
141 (defgroup org-table-settings nil
142 "Settings for tables in Org-mode."
143 :tag "Org Table Settings"
144 :group 'org-table)
146 (defcustom org-table-default-size "5x2"
147 "The default size for newly created tables, Columns x Rows."
148 :group 'org-table-settings
149 :type 'string)
151 (defcustom org-table-number-regexp
152 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
153 "Regular expression for recognizing numbers in table columns.
154 If a table column contains mostly numbers, it will be aligned to the
155 right. If not, it will be aligned to the left.
157 The default value of this option is a regular expression which allows
158 anything which looks remotely like a number as used in scientific
159 context. For example, all of the following will be considered a
160 number:
161 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
163 Other options offered by the customize interface are more restrictive."
164 :group 'org-table-settings
165 :type '(choice
166 (const :tag "Positive Integers"
167 "^[0-9]+$")
168 (const :tag "Integers"
169 "^[-+]?[0-9]+$")
170 (const :tag "Floating Point Numbers"
171 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
172 (const :tag "Floating Point Number or Integer"
173 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
174 (const :tag "Exponential, Floating point, Integer"
175 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
176 (const :tag "Very General Number-Like, including hex and Calc radix"
177 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
178 (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
179 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
180 (string :tag "Regexp:")))
182 (defcustom org-table-number-fraction 0.5
183 "Fraction of numbers in a column required to make the column align right.
184 In a column all non-white fields are considered. If at least
185 this fraction of fields is matched by `org-table-number-regexp',
186 alignment to the right border applies."
187 :group 'org-table-settings
188 :type 'number)
190 (defgroup org-table-editing nil
191 "Behavior of tables during editing in Org-mode."
192 :tag "Org Table Editing"
193 :group 'org-table)
195 (defcustom org-table-automatic-realign t
196 "Non-nil means automatically re-align table when pressing TAB or RETURN.
197 When nil, aligning is only done with \\[org-table-align], or after column
198 removal/insertion."
199 :group 'org-table-editing
200 :type 'boolean)
202 (defcustom org-table-auto-blank-field t
203 "Non-nil means automatically blank table field when starting to type into it.
204 This only happens when typing immediately after a field motion
205 command (TAB, S-TAB or RET).
206 Only relevant when `org-enable-table-editor' is equal to `optimized'."
207 :group 'org-table-editing
208 :type 'boolean)
210 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
211 "Non-nil means automatically exit the follow mode.
212 When nil, the follow mode will stay on and be active in any table
213 the cursor enters. Since the table follow filed mode messes with the
214 window configuration, it is not recommended to set this variable to nil,
215 except maybe locally in a special file that has mostly tables with long
216 fields."
217 :group 'org-table
218 :version "24.1"
219 :type 'boolean)
221 (defcustom org-table-fix-formulas-confirm nil
222 "Whether the user should confirm when Org fixes formulas."
223 :group 'org-table-editing
224 :version "24.1"
225 :type '(choice
226 (const :tag "with yes-or-no" yes-or-no-p)
227 (const :tag "with y-or-n" y-or-n-p)
228 (const :tag "no confirmation" nil)))
229 (put 'org-table-fix-formulas-confirm
230 'safe-local-variable
231 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
233 (defcustom org-table-tab-jumps-over-hlines t
234 "Non-nil means tab in the last column of a table with jump over a hline.
235 If a horizontal separator line is following the current line,
236 `org-table-next-field' can either create a new row before that line, or jump
237 over the line. When this option is nil, a new line will be created before
238 this line."
239 :group 'org-table-editing
240 :type 'boolean)
242 (defgroup org-table-calculation nil
243 "Options concerning tables in Org-mode."
244 :tag "Org Table Calculation"
245 :group 'org-table)
247 (defcustom org-table-use-standard-references 'from
248 "Should org-mode work with table references like B3 instead of @3$2?
249 Possible values are:
250 nil never use them
251 from accept as input, do not present for editing
252 t accept as input and present for editing"
253 :group 'org-table-calculation
254 :type '(choice
255 (const :tag "Never, don't even check user input for them" nil)
256 (const :tag "Always, both as user input, and when editing" t)
257 (const :tag "Convert user input, don't offer during editing" from)))
259 (defcustom org-table-copy-increment t
260 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
261 :group 'org-table-calculation
262 :version "25.1"
263 :package-version '(Org . "8.3")
264 :type '(choice
265 (const :tag "Use the difference between the current and the above fields" t)
266 (integer :tag "Use a number" 1)
267 (const :tag "Don't increment the value when copying a field" nil)))
269 (defcustom org-calc-default-modes
270 '(calc-internal-prec 12
271 calc-float-format (float 8)
272 calc-angle-mode deg
273 calc-prefer-frac nil
274 calc-symbolic-mode nil
275 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
276 calc-display-working-message t
278 "List with Calc mode settings for use in `calc-eval' for table formulas.
279 The list must contain alternating symbols (Calc modes variables and values).
280 Don't remove any of the default settings, just change the values. Org-mode
281 relies on the variables to be present in the list."
282 :group 'org-table-calculation
283 :type 'plist)
285 (defcustom org-table-duration-custom-format 'hours
286 "Format for the output of calc computations like $1+$2;t.
287 The default value is 'hours, and will output the results as a
288 number of hours. Other allowed values are 'seconds, 'minutes and
289 'days, and the output will be a fraction of seconds, minutes or
290 days."
291 :group 'org-table-calculation
292 :version "24.1"
293 :type '(choice (symbol :tag "Seconds" 'seconds)
294 (symbol :tag "Minutes" 'minutes)
295 (symbol :tag "Hours " 'hours)
296 (symbol :tag "Days " 'days)))
298 (defcustom org-table-formula-field-format "%s"
299 "Format for fields which contain the result of a formula.
300 For example, using \"~%s~\" will display the result within tilde
301 characters. Beware that modifying the display can prevent the
302 field from being used in another formula."
303 :group 'org-table-settings
304 :version "24.1"
305 :type 'string)
307 (defcustom org-table-formula-evaluate-inline t
308 "Non-nil means TAB and RET evaluate a formula in current table field.
309 If the current field starts with an equal sign, it is assumed to be a formula
310 which should be evaluated as described in the manual and in the documentation
311 string of the command `org-table-eval-formula'. This feature requires the
312 Emacs calc package.
313 When this variable is nil, formula calculation is only available through
314 the command \\[org-table-eval-formula]."
315 :group 'org-table-calculation
316 :type 'boolean)
318 (defcustom org-table-formula-use-constants t
319 "Non-nil means interpret constants in formulas in tables.
320 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
321 by the value given in `org-table-formula-constants', or by a value obtained
322 from the `constants.el' package."
323 :group 'org-table-calculation
324 :type 'boolean)
326 (defcustom org-table-formula-constants nil
327 "Alist with constant names and values, for use in table formulas.
328 The car of each element is a name of a constant, without the `$' before it.
329 The cdr is the value as a string. For example, if you'd like to use the
330 speed of light in a formula, you would configure
332 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
334 and then use it in an equation like `$1*$c'.
336 Constants can also be defined on a per-file basis using a line like
338 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
339 :group 'org-table-calculation
340 :type '(repeat
341 (cons (string :tag "name")
342 (string :tag "value"))))
344 (defcustom org-table-allow-automatic-line-recalculation t
345 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
346 \\<org-mode-map>\
347 Automatically means when TAB or RET or \\[org-ctrl-c-ctrl-c] \
348 are pressed in the line."
349 :group 'org-table-calculation
350 :type 'boolean)
352 (defcustom org-table-relative-ref-may-cross-hline t
353 "Non-nil means relative formula references may cross hlines.
354 Here are the allowed values:
356 nil Relative references may not cross hlines. They will reference the
357 field next to the hline instead. Coming from below, the reference
358 will be to the field below the hline. Coming from above, it will be
359 to the field above.
360 t Relative references may cross hlines.
361 error An attempt to cross a hline will throw an error.
363 It is probably good to never set this variable to nil, for the sake of
364 portability of tables."
365 :group 'org-table-calculation
366 :type '(choice
367 (const :tag "Allow to cross" t)
368 (const :tag "Stick to hline" nil)
369 (const :tag "Error on attempt to cross" error)))
371 (defcustom org-table-formula-create-columns nil
372 "Non-nil means that evaluation of a field formula can add new
373 columns if an out-of-bounds field is being set."
374 :group 'org-table-calculation
375 :version "25.1"
376 :package-version '(Org . "8.3")
377 :type '(choice
378 (const :tag "Setting an out-of-bounds field generates an error (default)" nil)
379 (const :tag "Setting an out-of-bounds field silently adds columns as needed" t)
380 (const :tag "Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn)
381 (const :tag "When setting an out-of-bounds field, the user is prompted" prompt)))
383 (defgroup org-table-import-export nil
384 "Options concerning table import and export in Org-mode."
385 :tag "Org Table Import Export"
386 :group 'org-table)
388 (defcustom org-table-export-default-format "orgtbl-to-tsv"
389 "Default export parameters for `org-table-export'.
390 These can be overridden for a specific table by setting the
391 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
392 radio tables for the different export transformations and
393 available parameters."
394 :group 'org-table-import-export
395 :type 'string)
397 (defcustom org-table-convert-region-max-lines 999
398 "Max lines that `org-table-convert-region' will attempt to process.
400 The function can be slow on larger regions; this safety feature
401 prevents it from hanging emacs."
402 :group 'org-table-import-export
403 :type 'integer
404 :version "25.1"
405 :package-version '(Org . "8.3"))
407 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
408 "Regexp matching a line marked for automatic recalculation.")
410 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
411 "Regexp matching a line marked for recalculation.")
413 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
414 "Regexp matching a line marked for calculation.")
416 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
417 "Regexp matching any line outside an Org table.")
419 (defvar org-table-last-highlighted-reference nil)
421 (defvar org-table-formula-history nil)
423 (defvar org-table-column-names nil
424 "Alist with column names, derived from the `!' line.
425 This variable is initialized with `org-table-analyze'.")
427 (defvar org-table-column-name-regexp nil
428 "Regular expression matching the current column names.
429 This variable is initialized with `org-table-analyze'.")
431 (defvar org-table-local-parameters nil
432 "Alist with parameter names, derived from the `$' line.
433 This variable is initialized with `org-table-analyze'.")
435 (defvar org-table-named-field-locations nil
436 "Alist with locations of named fields.
437 Associations follow the pattern (NAME LINE COLUMN) where
438 NAME is the name of the field as a string,
439 LINE is the number of lines from the beginning of the table,
440 COLUMN is the column of the field, as an integer.
441 This variable is initialized with `org-table-analyze'.")
443 (defvar org-table-current-line-types nil
444 "Table row types in current table.
445 This variable is initialized with `org-table-analyze'.")
447 (defvar org-table-current-begin-pos nil
448 "Current table begin position, as a marker.
449 This variable is initialized with `org-table-analyze'.")
451 (defvar org-table-current-ncol nil
452 "Number of columns in current table.
453 This variable is initialized with `org-table-analyze'.")
455 (defvar org-table-dlines nil
456 "Vector of data line line numbers in the current table.
457 Line numbers are counted from the beginning of the table. This
458 variable is initialized with `org-table-analyze'.")
460 (defvar org-table-hlines nil
461 "Vector of hline line numbers in the current table.
462 Line numbers are counted from the beginning of the table. This
463 variable is initialized with `org-table-analyze'.")
465 (defconst org-table-range-regexp
466 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
467 ;; 1 2 3 4 5
468 "Regular expression for matching ranges in formulas.")
470 (defconst org-table-range-regexp2
471 (concat
472 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
473 "\\.\\."
474 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
475 "Match a range for reference display.")
477 (defconst org-table-translate-regexp
478 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
479 "Match a reference that needs translation, for reference display.")
481 (defmacro org-table-save-field (&rest body)
482 "Save current field; execute BODY; restore field.
483 Field is restored even in case of abnormal exit."
484 (declare (debug (body)))
485 (org-with-gensyms (line column)
486 `(let ((,line (copy-marker (line-beginning-position)))
487 (,column (org-table-current-column)))
488 (unwind-protect
489 (progn ,@body)
490 (goto-char ,line)
491 (org-table-goto-column ,column)
492 (set-marker ,line nil)))))
494 ;;;###autoload
495 (defun org-table-create-with-table.el ()
496 "Use the table.el package to insert a new table.
497 If there is already a table at point, convert between Org-mode tables
498 and table.el tables."
499 (interactive)
500 (require 'table)
501 (cond
502 ((org-at-table.el-p)
503 (if (y-or-n-p "Convert table to Org-mode table? ")
504 (org-table-convert)))
505 ((org-at-table-p)
506 (when (y-or-n-p "Convert table to table.el table? ")
507 (org-table-align)
508 (org-table-convert)))
509 (t (call-interactively 'table-insert))))
511 ;;;###autoload
512 (defun org-table-create-or-convert-from-region (arg)
513 "Convert region to table, or create an empty table.
514 If there is an active region, convert it to a table, using the function
515 `org-table-convert-region'. See the documentation of that function
516 to learn how the prefix argument is interpreted to determine the field
517 separator.
518 If there is no such region, create an empty table with `org-table-create'."
519 (interactive "P")
520 (if (org-region-active-p)
521 (org-table-convert-region (region-beginning) (region-end) arg)
522 (org-table-create arg)))
524 ;;;###autoload
525 (defun org-table-create (&optional size)
526 "Query for a size and insert a table skeleton.
527 SIZE is a string Columns x Rows like for example \"3x2\"."
528 (interactive "P")
529 (unless size
530 (setq size (read-string
531 (concat "Table size Columns x Rows [e.g. "
532 org-table-default-size "]: ")
533 "" nil org-table-default-size)))
535 (let* ((pos (point))
536 (indent (make-string (current-column) ?\ ))
537 (split (org-split-string size " *x *"))
538 (rows (string-to-number (nth 1 split)))
539 (columns (string-to-number (car split)))
540 (line (concat (apply 'concat indent "|" (make-list columns " |"))
541 "\n")))
542 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
543 (point-at-bol) (point)))
544 (beginning-of-line 1)
545 (newline))
546 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
547 (dotimes (i rows) (insert line))
548 (goto-char pos)
549 (if (> rows 1)
550 ;; Insert a hline after the first row.
551 (progn
552 (end-of-line 1)
553 (insert "\n|-")
554 (goto-char pos)))
555 (org-table-align)))
557 ;;;###autoload
558 (defun org-table-convert-region (beg0 end0 &optional separator)
559 "Convert region to a table.
560 The region goes from BEG0 to END0, but these borders will be moved
561 slightly, to make sure a beginning of line in the first line is included.
563 SEPARATOR specifies the field separator in the lines. It can have the
564 following values:
566 (4) Use the comma as a field separator
567 (16) Use a TAB as field separator
568 (64) Prompt for a regular expression as field separator
569 integer When a number, use that many spaces as field separator
570 regexp When a regular expression, use it to match the separator
571 nil When nil, the command tries to be smart and figure out the
572 separator in the following way:
573 - when each line contains a TAB, assume TAB-separated material
574 - when each line contains a comma, assume CSV material
575 - else, assume one or more SPACE characters as separator."
576 (interactive "r\nP")
577 (let* ((beg (min beg0 end0))
578 (end (max beg0 end0))
580 (if (> (count-lines beg end) org-table-convert-region-max-lines)
581 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
582 org-table-convert-region-max-lines)
583 (if (equal separator '(64))
584 (setq separator (read-regexp "Regexp for field separator")))
585 (goto-char beg)
586 (beginning-of-line 1)
587 (setq beg (point-marker))
588 (goto-char end)
589 (if (bolp) (backward-char 1) (end-of-line 1))
590 (setq end (point-marker))
591 ;; Get the right field separator
592 (unless separator
593 (goto-char beg)
594 (setq separator
595 (cond
596 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
597 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
598 (t 1))))
599 (goto-char beg)
600 (if (equal separator '(4))
601 (while (< (point) end)
602 ;; parse the csv stuff
603 (cond
604 ((looking-at "^") (insert "| "))
605 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
606 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
607 (replace-match "\\1")
608 (if (looking-at "\"") (insert "\"")))
609 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
610 ((looking-at "[ \t]*,") (replace-match " | "))
611 (t (beginning-of-line 2))))
612 (setq re (cond
613 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
614 ((equal separator '(16)) "^\\|\t")
615 ((integerp separator)
616 (if (< separator 1)
617 (user-error "Number of spaces in separator must be >= 1")
618 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
619 ((stringp separator)
620 (format "^ *\\|%s" separator))
621 (t (error "This should not happen"))))
622 (while (re-search-forward re end t)
623 (replace-match "| " t t)))
624 (goto-char beg)
625 (org-table-align))))
627 ;;;###autoload
628 (defun org-table-import (file arg)
629 "Import FILE as a table.
630 The file is assumed to be tab-separated. Such files can be produced by most
631 spreadsheet and database applications. If no tabs (at least one per line)
632 are found, lines will be split on whitespace into fields."
633 (interactive "f\nP")
634 (or (bolp) (newline))
635 (let ((beg (point))
636 (pm (point-max)))
637 (insert-file-contents file)
638 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
641 ;;;###autoload
642 (defun org-table-export (&optional file format)
643 "Export table to a file, with configurable format.
644 Such a file can be imported into usual spreadsheet programs.
646 FILE can be the output file name. If not given, it will be taken
647 from a TABLE_EXPORT_FILE property in the current entry or higher
648 up in the hierarchy, or the user will be prompted for a file
649 name. FORMAT can be an export format, of the same kind as it
650 used when `orgtbl-mode' sends a table in a different format.
652 The command suggests a format depending on TABLE_EXPORT_FORMAT,
653 whether it is set locally or up in the hierarchy, then on the
654 extension of the given file name, and finally on the variable
655 `org-table-export-default-format'."
656 (interactive)
657 (unless (org-at-table-p) (user-error "No table at point"))
658 (org-table-align) ; Make sure we have everything we need.
659 (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
660 (unless file
661 (setq file (read-file-name "Export table to: "))
662 (unless (or (not (file-exists-p file))
663 (y-or-n-p (format "Overwrite file %s? " file)))
664 (user-error "File not written")))
665 (when (file-directory-p file)
666 (user-error "This is a directory path, not a file"))
667 (when (and (buffer-file-name (buffer-base-buffer))
668 (org-file-equal-p
669 (file-truename file)
670 (file-truename (buffer-file-name (buffer-base-buffer)))))
671 (user-error "Please specify a file name that is different from current"))
672 (let ((fileext (concat (file-name-extension file) "$"))
673 (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
674 (unless format
675 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
676 "orgtbl-to-html" "orgtbl-to-generic"
677 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
678 "orgtbl-to-unicode"))
679 (deffmt-readable
680 (replace-regexp-in-string
681 "\t" "\\t"
682 (replace-regexp-in-string
683 "\n" "\\n"
684 (or (car (delq nil
685 (mapcar
686 (lambda (f)
687 (and (org-string-match-p fileext f) f))
688 formats)))
689 org-table-export-default-format)
690 t t) t t)))
691 (setq format
692 (org-completing-read
693 "Format: " formats nil nil deffmt-readable))))
694 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
695 (let ((transform (intern (match-string 1 format)))
696 (params (and (match-end 2)
697 (read (concat "(" (match-string 2 format) ")"))))
698 (table (org-table-to-lisp
699 (buffer-substring-no-properties
700 (org-table-begin) (org-table-end)))))
701 (unless (fboundp transform)
702 (user-error "No such transformation function %s" transform))
703 (let (buf)
704 (with-current-buffer (find-file-noselect file)
705 (setq buf (current-buffer))
706 (erase-buffer)
707 (fundamental-mode)
708 (insert (funcall transform table params) "\n")
709 (save-buffer))
710 (kill-buffer buf))
711 (message "Export done."))
712 (user-error "TABLE_EXPORT_FORMAT invalid")))))
714 (defvar org-table-aligned-begin-marker (make-marker)
715 "Marker at the beginning of the table last aligned.
716 Used to check if cursor still is in that table, to minimize realignment.")
717 (defvar org-table-aligned-end-marker (make-marker)
718 "Marker at the end of the table last aligned.
719 Used to check if cursor still is in that table, to minimize realignment.")
720 (defvar org-table-last-alignment nil
721 "List of flags for flushright alignment, from the last re-alignment.
722 This is being used to correctly align a single field after TAB or RET.")
723 (defvar org-table-last-column-widths nil
724 "List of max width of fields in each column.
725 This is being used to correctly align a single field after TAB or RET.")
726 (defvar org-table-formula-debug nil
727 "Non-nil means debug table formulas.
728 When nil, simply write \"#ERROR\" in corrupted fields.")
729 (make-variable-buffer-local 'org-table-formula-debug)
730 (defvar org-table-overlay-coordinates nil
731 "Overlay coordinates after each align of a table.")
732 (make-variable-buffer-local 'org-table-overlay-coordinates)
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 (p)
1895 (let ((tp table))
1896 (mapcar
1897 (lambda (rown)
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 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
2028 (org-set-local 'org-window-configuration cw)
2029 (org-set-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 (refass (assoc ref stored-list))
2197 (nameass (assoc name stored-list))
2198 (scol (if named
2199 (if (and name (not (string-match "^LR[0-9]+$" name)))
2200 name
2201 ref)
2202 (int-to-string (org-table-current-column))))
2203 (dummy (and (or nameass refass) (not named)
2204 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2205 (message "Formula not replaced")))
2206 (name (or name ref))
2207 (org-table-may-need-update nil)
2208 (stored (cdr (assoc scol stored-list)))
2209 (eq (cond
2210 ((and stored equation (string-match "^ *=? *$" equation))
2211 stored)
2212 ((stringp equation)
2213 equation)
2214 (t (org-table-formula-from-user
2215 (read-string
2216 (org-table-formula-to-user
2217 (format "%s formula %s%s="
2218 (if named "Field" "Column")
2219 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2220 scol))
2221 (if stored (org-table-formula-to-user stored) "")
2222 'org-table-formula-history
2223 )))))
2224 mustsave)
2225 (when (not (string-match "\\S-" eq))
2226 ;; remove formula
2227 (setq stored-list (delq (assoc scol stored-list) stored-list))
2228 (org-table-store-formulas stored-list)
2229 (user-error "Formula removed"))
2230 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2231 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2232 (if (and name (not named))
2233 ;; We set the column equation, delete the named one.
2234 (setq stored-list (delq (assoc name stored-list) stored-list)
2235 mustsave t))
2236 (if stored
2237 (setcdr (assoc scol stored-list) eq)
2238 (setq stored-list (cons (cons scol eq) stored-list)))
2239 (if (or mustsave (not (equal stored eq)))
2240 (org-table-store-formulas stored-list))
2241 eq))
2243 (defun org-table-store-formulas (alist)
2244 "Store the list of formulas below the current table."
2245 (setq alist (sort alist 'org-table-formula-less-p))
2246 (let ((case-fold-search t))
2247 (save-excursion
2248 (goto-char (org-table-end))
2249 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2250 (progn
2251 ;; don't overwrite TBLFM, we might use text properties to store stuff
2252 (goto-char (match-beginning 3))
2253 (delete-region (match-beginning 3) (match-end 0)))
2254 (org-indent-line)
2255 (insert (or (match-string 2) "#+TBLFM:")))
2256 (insert " "
2257 (mapconcat (lambda (x)
2258 (concat
2259 (if (equal (string-to-char (car x)) ?@) "" "$")
2260 (car x) "=" (cdr x)))
2261 alist "::")
2262 "\n"))))
2264 (defsubst org-table-formula-make-cmp-string (a)
2265 (when (string-match "\\`$[<>]" a)
2266 (let ((arrow (string-to-char (substring a 1))))
2267 ;; Fake a high number to make sure this is sorted at the end.
2268 (setq a (org-table-formula-handle-first/last-rc a))
2269 (setq a (format "$%d" (+ 10000
2270 (if (= arrow ?<) -1000 0)
2271 (string-to-number (substring a 1)))))))
2272 (when (string-match
2273 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2275 (concat
2276 (if (match-end 2)
2277 (format "@%05d" (string-to-number (match-string 2 a))) "")
2278 (if (match-end 4)
2279 (format "$%05d" (string-to-number (match-string 4 a))) "")
2280 (if (match-end 5)
2281 (concat "@@" (match-string 5 a))))))
2283 (defun org-table-formula-less-p (a b)
2284 "Compare two formulas for sorting."
2285 (let ((as (org-table-formula-make-cmp-string (car a)))
2286 (bs (org-table-formula-make-cmp-string (car b))))
2287 (and as bs (string< as bs))))
2289 ;;;###autoload
2290 (defun org-table-get-stored-formulas (&optional noerror)
2291 "Return an alist with the stored formulas directly after current table."
2292 (interactive) ;; FIXME interactive?
2293 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2294 (save-excursion
2295 (goto-char (org-table-end))
2296 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2297 (setq strings (org-split-string (org-match-string-no-properties 2)
2298 " *:: *"))
2299 (while (setq string (pop strings))
2300 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2301 (setq scol (if (match-end 2)
2302 (match-string 2 string)
2303 (match-string 1 string))
2304 scol (if (member (string-to-char scol) '(?< ?>))
2305 (concat "$" scol) scol)
2306 eq (match-string 3 string)
2307 eq-alist (cons (cons scol eq) eq-alist))
2308 (if (member scol seen)
2309 (if noerror
2310 (progn
2311 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2312 (ding)
2313 (sit-for 2))
2314 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2315 (push scol seen))))))
2316 (nreverse eq-alist)))
2318 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2319 "Modify the equations after the table structure has been edited.
2320 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2321 For all numbers larger than LIMIT, shift them by DELTA."
2322 (save-excursion
2323 (goto-char (org-table-end))
2324 (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2325 (let ((msg "The formulas in #+TBLFM have been updated")
2326 (re (concat key "\\([0-9]+\\)"))
2327 (re2
2328 (when remove
2329 (if (or (equal key "$") (equal key "$LR"))
2330 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2331 (regexp-quote key) remove)
2332 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2333 s n a)
2334 (when remove
2335 (while (re-search-forward re2 (point-at-eol) t)
2336 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2337 (if (equal (char-before (match-beginning 0)) ?.)
2338 (user-error
2339 "Change makes TBLFM term %s invalid, use undo to recover"
2340 (match-string 0))
2341 (replace-match "")))))
2342 (while (re-search-forward re (point-at-eol) t)
2343 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2344 (setq s (match-string 1) n (string-to-number s))
2345 (cond
2346 ((setq a (assoc s replace))
2347 (replace-match (concat key (cdr a)) t t)
2348 (message msg))
2349 ((and limit (> n limit))
2350 (replace-match (concat key (int-to-string (+ n delta))) t t)
2351 (message msg))))))
2352 (forward-line))))
2354 ;;;###autoload
2355 (defun org-table-maybe-eval-formula ()
2356 "Check if the current field starts with \"=\" or \":=\".
2357 If yes, store the formula and apply it."
2358 ;; We already know we are in a table. Get field will only return a formula
2359 ;; when appropriate. It might return a separator line, but no problem.
2360 (when org-table-formula-evaluate-inline
2361 (let* ((field (org-trim (or (org-table-get-field) "")))
2362 named eq)
2363 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2364 (setq named (equal (string-to-char field) ?:)
2365 eq (match-string 1 field))
2366 (if (or (fboundp 'calc-eval)
2367 (equal (substring eq 0 (min 2 (length eq))) "'("))
2368 (org-table-eval-formula (if named '(4) nil)
2369 (org-table-formula-from-user eq))
2370 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2372 (defvar org-recalc-commands nil
2373 "List of commands triggering the recalculation of a line.
2374 Will be filled automatically during use.")
2376 (defvar org-recalc-marks
2377 '((" " . "Unmarked: no special line, no automatic recalculation")
2378 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2379 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2380 ("!" . "Column name definition line. Reference in formula as $name.")
2381 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2382 ("_" . "Names for values in row below this one.")
2383 ("^" . "Names for values in row above this one.")))
2385 ;;;###autoload
2386 (defun org-table-rotate-recalc-marks (&optional newchar)
2387 "Rotate the recalculation mark in the first column.
2388 If in any row, the first field is not consistent with a mark,
2389 insert a new column for the markers.
2390 When there is an active region, change all the lines in the region,
2391 after prompting for the marking character.
2392 After each change, a message will be displayed indicating the meaning
2393 of the new mark."
2394 (interactive)
2395 (unless (org-at-table-p) (user-error "Not at a table"))
2396 (let* ((region (org-region-active-p))
2397 (l1 (and region
2398 (save-excursion (goto-char (region-beginning))
2399 (copy-marker (line-beginning-position)))))
2400 (l2 (and region
2401 (save-excursion (goto-char (region-end))
2402 (copy-marker (line-beginning-position)))))
2403 (l (copy-marker (line-beginning-position)))
2404 (col (org-table-current-column))
2405 (newchar (if region
2406 (char-to-string
2407 (read-char-exclusive
2408 "Change region to what mark? Type # * ! $ or SPC: "))
2409 newchar))
2410 (no-special-column
2411 (save-excursion
2412 (goto-char (org-table-begin))
2413 (re-search-forward
2414 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
2415 (when (and newchar (not (assoc newchar org-recalc-marks)))
2416 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2417 newchar))
2418 (when l1 (goto-char l1))
2419 (save-excursion
2420 (beginning-of-line)
2421 (unless (looking-at org-table-dataline-regexp)
2422 (user-error "Not at a table data line")))
2423 (when no-special-column
2424 (org-table-goto-column 1)
2425 (org-table-insert-column))
2426 (let ((previous-line-end (line-end-position))
2427 (newchar
2428 (save-excursion
2429 (beginning-of-line)
2430 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2431 (newchar)
2432 (t (cadr (member (match-string 1)
2433 (append (mapcar #'car org-recalc-marks)
2434 '(" ")))))))))
2435 ;; Rotate mark in first row.
2436 (org-table-get-field 1 (format " %s " newchar))
2437 ;; Rotate marks in additional rows if a region is active.
2438 (when region
2439 (save-excursion
2440 (forward-line)
2441 (while (<= (point) l2)
2442 (when (looking-at org-table-dataline-regexp)
2443 (org-table-get-field 1 (format " %s " newchar)))
2444 (forward-line))))
2445 ;; Only align if rotation actually changed lines' length.
2446 (when (/= previous-line-end (line-end-position)) (org-table-align)))
2447 (goto-char l)
2448 (org-table-goto-column (if no-special-column (1+ col) col))
2449 (when l1 (set-marker l1 nil))
2450 (when l2 (set-marker l2 nil))
2451 (set-marker l nil)
2452 (when (org-called-interactively-p 'interactive)
2453 (message "%s" (cdr (assoc newchar org-recalc-marks))))))
2455 ;;;###autoload
2456 (defun org-table-analyze ()
2457 "Analyze table at point and store results.
2459 This function sets up the following dynamically scoped variables:
2461 `org-table-column-name-regexp',
2462 `org-table-column-names',
2463 `org-table-current-begin-pos',
2464 `org-table-current-line-types',
2465 `org-table-current-ncol',
2466 `org-table-dlines',
2467 `org-table-hlines',
2468 `org-table-local-parameters',
2469 `org-table-named-field-locations'."
2470 (let ((beg (org-table-begin))
2471 (end (org-table-end)))
2472 (save-excursion
2473 (goto-char beg)
2474 ;; Extract column names.
2475 (setq org-table-column-names nil)
2476 (when (save-excursion
2477 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
2478 (let ((c 1))
2479 (dolist (name (org-split-string (match-string 1) " *| *"))
2480 (incf c)
2481 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
2482 (push (cons name (int-to-string c)) org-table-column-names)))))
2483 (setq org-table-column-names (nreverse org-table-column-names))
2484 (setq org-table-column-name-regexp
2485 (format "\\$\\(%s\\)\\>"
2486 (regexp-opt (mapcar #'car org-table-column-names) t)))
2487 ;; Extract local parameters.
2488 (setq org-table-local-parameters nil)
2489 (save-excursion
2490 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2491 (dolist (field (org-split-string (match-string 1) " *| *"))
2492 (when (string-match
2493 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2494 (push (cons (match-string 1 field) (match-string 2 field))
2495 org-table-local-parameters)))))
2496 ;; Update named fields locations. We minimize `count-lines'
2497 ;; processing by storing last known number of lines in LAST.
2498 (setq org-table-named-field-locations nil)
2499 (save-excursion
2500 (let ((last (cons (point) 0)))
2501 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2502 (let ((c (match-string 1))
2503 (fields (org-split-string (match-string 2) " *| *")))
2504 (save-excursion
2505 (forward-line (if (equal c "_") 1 -1))
2506 (let ((fields1
2507 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2508 (org-split-string (match-string 1) " *| *")))
2509 (line (incf (cdr last) (count-lines (car last) (point))))
2510 (col 1))
2511 (setcar last (point)) ; Update last known position.
2512 (while (and fields fields1)
2513 (let ((field (pop fields))
2514 (v (pop fields1)))
2515 (incf col)
2516 (when (and (stringp field)
2517 (stringp v)
2518 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2519 field))
2520 (push (cons field v) org-table-local-parameters)
2521 (push (list field line col)
2522 org-table-named-field-locations))))))))))
2523 ;; Re-use existing markers when possible.
2524 (if (markerp org-table-current-begin-pos)
2525 (move-marker org-table-current-begin-pos (point))
2526 (setq org-table-current-begin-pos (point-marker)))
2527 ;; Analyze the line types.
2528 (let ((l 0) hlines dlines types)
2529 (while (looking-at "[ \t]*|\\(-\\)?")
2530 (push (if (match-end 1) 'hline 'dline) types)
2531 (if (match-end 1) (push l hlines) (push l dlines))
2532 (forward-line)
2533 (incf l))
2534 (push 'hline types) ; Add an imaginary extra hline to the end.
2535 (setq org-table-current-line-types (apply #'vector (nreverse types)))
2536 (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
2537 (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines))))
2538 (forward-line -1)
2539 (let* ((last-dline (car dlines))
2540 (fields (org-split-string
2541 (buffer-substring (line-beginning-position)
2542 (line-end-position))
2543 "[ \t]*|[ \t]*"))
2544 (nfields (length fields))
2545 al al2)
2546 (setq org-table-current-ncol nfields)
2547 (dotimes (i nfields)
2548 (let ((column (1+ i)))
2549 (push (list (format "LR%d" column) last-dline column) al)
2550 (push (cons (format "LR%d" column) (nth i fields)) al2)))
2551 (setq org-table-named-field-locations
2552 (append org-table-named-field-locations al))
2553 (setq org-table-local-parameters
2554 (append org-table-local-parameters al2)))))))
2556 (defun org-table-goto-field (ref &optional create-column-p)
2557 "Move point to a specific field in the current table.
2559 REF is either the name of a field its absolute reference, as
2560 a string. No column is created unless CREATE-COLUMN-P is
2561 non-nil. If it is a function, it is called with the column
2562 number as its argument as is used as a predicate to know if the
2563 column can be created.
2565 This function assumes the table is already analyzed (i.e., using
2566 `org-table-analyze')."
2567 (let* ((coordinates
2568 (cond
2569 ((cdr (assoc ref org-table-named-field-locations)))
2570 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
2571 (list (condition-case nil
2572 (aref org-table-dlines
2573 (string-to-number (match-string 1 ref)))
2574 (error (user-error "Invalid row number in %s" ref)))
2575 (string-to-number (match-string 2 ref))))
2576 (t (user-error "Unknown field: %s" ref))))
2577 (line (car coordinates))
2578 (column (nth 1 coordinates))
2579 (create-new-column (if (functionp create-column-p)
2580 (funcall create-column-p column)
2581 create-column-p)))
2582 (when coordinates
2583 (goto-char org-table-current-begin-pos)
2584 (forward-line line)
2585 (org-table-goto-column column nil create-new-column))))
2587 ;;;###autoload
2588 (defun org-table-maybe-recalculate-line ()
2589 "Recompute the current line if marked for it, and if we haven't just done it."
2590 (interactive)
2591 (and org-table-allow-automatic-line-recalculation
2592 (not (and (memq last-command org-recalc-commands)
2593 (eq org-last-recalc-line (line-beginning-position))))
2594 (save-excursion (beginning-of-line 1)
2595 (looking-at org-table-auto-recalculate-regexp))
2596 (org-table-recalculate) t))
2598 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2599 (defsubst org-set-calc-mode (var &optional value)
2600 (if (stringp var)
2601 (setq var (assoc var '(("D" calc-angle-mode deg)
2602 ("R" calc-angle-mode rad)
2603 ("F" calc-prefer-frac t)
2604 ("S" calc-symbolic-mode t)))
2605 value (nth 2 var) var (nth 1 var)))
2606 (if (memq var org-tbl-calc-modes)
2607 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2608 (cons var (cons value org-tbl-calc-modes)))
2609 org-tbl-calc-modes)
2611 ;;;###autoload
2612 (defun org-table-eval-formula (&optional arg equation
2613 suppress-align suppress-const
2614 suppress-store suppress-analysis)
2615 "Replace the table field value at the cursor by the result of a calculation.
2617 This function makes use of Dave Gillespie's Calc package, in my view the
2618 most exciting program ever written for GNU Emacs. So you need to have Calc
2619 installed in order to use this function.
2621 In a table, this command replaces the value in the current field with the
2622 result of a formula. It also installs the formula as the \"current\" column
2623 formula, by storing it in a special line below the table. When called
2624 with a `C-u' prefix, the current field must be a named field, and the
2625 formula is installed as valid in only this specific field.
2627 When called with two `C-u' prefixes, insert the active equation
2628 for the field back into the current field, so that it can be
2629 edited there. This is useful in order to use \\[org-table-show-reference]
2630 to check the referenced fields.
2632 When called, the command first prompts for a formula, which is read in
2633 the minibuffer. Previously entered formulas are available through the
2634 history list, and the last used formula is offered as a default.
2635 These stored formulas are adapted correctly when moving, inserting, or
2636 deleting columns with the corresponding commands.
2638 The formula can be any algebraic expression understood by the Calc package.
2639 For details, see the Org-mode manual.
2641 This function can also be called from Lisp programs and offers
2642 additional arguments: EQUATION can be the formula to apply. If this
2643 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2644 used to speed-up recursive calls by by-passing unnecessary aligns.
2645 SUPPRESS-CONST suppresses the interpretation of constants in the
2646 formula, assuming that this has been done already outside the function.
2647 SUPPRESS-STORE means the formula should not be stored, either because
2648 it is already stored, or because it is a modified equation that should
2649 not overwrite the stored one."
2650 (interactive "P")
2651 (org-table-check-inside-data-field)
2652 (or suppress-analysis (org-table-analyze))
2653 (if (equal arg '(16))
2654 (let ((eq (org-table-current-field-formula)))
2655 (or eq (user-error "No equation active for current field"))
2656 (org-table-get-field nil eq)
2657 (org-table-align)
2658 (setq org-table-may-need-update t))
2659 (let* (fields
2660 (ndown (if (integerp arg) arg 1))
2661 (org-table-automatic-realign nil)
2662 (case-fold-search nil)
2663 (down (> ndown 1))
2664 (formula (if (and equation suppress-store)
2665 equation
2666 (org-table-get-formula equation (equal arg '(4)))))
2667 (n0 (org-table-current-column))
2668 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2669 (numbers nil) ; was a variable, now fixed default
2670 (keep-empty nil)
2671 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2672 duration duration-output-format)
2673 ;; Parse the format string. Since we have a lot of modes, this is
2674 ;; a lot of work. However, I think calc still uses most of the time.
2675 (if (string-match ";" formula)
2676 (let ((tmp (org-split-string formula ";")))
2677 (setq formula (car tmp)
2678 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2679 (nth 1 tmp)))
2680 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2681 (setq c (string-to-char (match-string 1 fmt))
2682 n (string-to-number (match-string 2 fmt)))
2683 (if (= c ?p)
2684 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2685 (setq org-tbl-calc-modes
2686 (org-set-calc-mode
2687 'calc-float-format
2688 (list (cdr (assoc c '((?n . float) (?f . fix)
2689 (?s . sci) (?e . eng))))
2690 n))))
2691 (setq fmt (replace-match "" t t fmt)))
2692 (if (string-match "T" fmt)
2693 (setq duration t numbers t
2694 duration-output-format nil
2695 fmt (replace-match "" t t fmt)))
2696 (if (string-match "t" fmt)
2697 (setq duration t
2698 duration-output-format org-table-duration-custom-format
2699 numbers t
2700 fmt (replace-match "" t t fmt)))
2701 (if (string-match "N" fmt)
2702 (setq numbers t
2703 fmt (replace-match "" t t fmt)))
2704 (if (string-match "L" fmt)
2705 (setq literal t
2706 fmt (replace-match "" t t fmt)))
2707 (if (string-match "E" fmt)
2708 (setq keep-empty t
2709 fmt (replace-match "" t t fmt)))
2710 (while (string-match "[DRFS]" fmt)
2711 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2712 (setq fmt (replace-match "" t t fmt)))
2713 (unless (string-match "\\S-" fmt)
2714 (setq fmt nil))))
2715 (if (and (not suppress-const) org-table-formula-use-constants)
2716 (setq formula (org-table-formula-substitute-names formula)))
2717 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2718 (while (> ndown 0)
2719 (setq fields (org-split-string
2720 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2721 " *| *"))
2722 ;; replace fields with duration values if relevant
2723 (if duration
2724 (setq fields
2725 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2726 fields)))
2727 (if (eq numbers t)
2728 (setq fields (mapcar
2729 (lambda (x)
2730 (if (string-match "\\S-" x)
2731 (number-to-string (string-to-number x))
2733 fields)))
2734 (setq ndown (1- ndown))
2735 (setq form (copy-sequence formula)
2736 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2737 (if (and lispp literal) (setq lispp 'literal))
2739 ;; Insert row and column number of formula result field
2740 (while (string-match "[@$]#" form)
2741 (setq form
2742 (replace-match
2743 (format "%d"
2744 (save-match-data
2745 (if (equal (substring form (match-beginning 0)
2746 (1+ (match-beginning 0)))
2747 "@")
2748 (org-table-current-dline)
2749 (org-table-current-column))))
2750 t t form)))
2752 ;; Check for old vertical references
2753 (org-table--error-on-old-row-references form)
2754 ;; Insert remote references
2755 (setq form (org-table-remote-reference-indirection form))
2756 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2757 (setq form
2758 (replace-match
2759 (save-match-data
2760 (org-table-make-reference
2761 (let ((rmtrng (org-table-get-remote-range
2762 (match-string 1 form) (match-string 2 form))))
2763 (if duration
2764 (if (listp rmtrng)
2765 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2766 (org-table-time-string-to-seconds rmtrng))
2767 rmtrng))
2768 keep-empty numbers lispp))
2769 t t form)))
2770 ;; Insert complex ranges
2771 (while (and (string-match org-table-range-regexp form)
2772 (> (length (match-string 0 form)) 1))
2773 (setq formrg
2774 (save-match-data
2775 (org-table-get-range
2776 (match-string 0 form) org-table-current-begin-pos n0)))
2777 (setq formrpl
2778 (save-match-data
2779 (org-table-make-reference
2780 ;; possibly handle durations
2781 (if duration
2782 (if (listp formrg)
2783 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2784 (org-table-time-string-to-seconds formrg))
2785 formrg)
2786 keep-empty numbers lispp)))
2787 (if (not (save-match-data
2788 (string-match (regexp-quote form) formrpl)))
2789 (setq form (replace-match formrpl t t form))
2790 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2791 ;; Insert simple ranges, i.e. included in the current row.
2792 (while (string-match
2793 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2794 form)
2795 (setq form
2796 (replace-match
2797 (save-match-data
2798 (org-table-make-reference
2799 (org-sublist fields
2800 (+ (if (match-end 2) n0 0)
2801 (string-to-number (match-string 1 form)))
2802 (+ (if (match-end 4) n0 0)
2803 (string-to-number (match-string 3 form))))
2804 keep-empty numbers lispp))
2805 t t form)))
2806 (setq form0 form)
2807 ;; Insert the references to fields in same row
2808 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2809 (setq n (+ (string-to-number (match-string 1 form))
2810 (if (match-end 2) n0 0))
2811 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2812 formrpl (save-match-data
2813 (org-table-make-reference
2814 x keep-empty numbers lispp)))
2815 (when (or (not x)
2816 (save-match-data
2817 (string-match (regexp-quote formula) formrpl)))
2818 (user-error "Invalid field specifier \"%s\""
2819 (match-string 0 form)))
2820 (setq form (replace-match formrpl t t form)))
2822 (if lispp
2823 (setq ev (condition-case nil
2824 (eval (eval (read form)))
2825 (error "#ERROR"))
2826 ev (if (numberp ev) (number-to-string ev) ev)
2827 ev (if duration (org-table-time-seconds-to-string
2828 (string-to-number ev)
2829 duration-output-format) ev))
2830 (or (fboundp 'calc-eval)
2831 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2832 ;; Use <...> time-stamps so that Calc can handle them
2833 (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
2834 (setq form (replace-match "<\\1>" nil nil form)))
2835 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2836 (when (string-match org-ts-regexp2 form)
2837 (let* ((ts (match-string 0 form))
2838 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2839 (system-time-locale "C")
2840 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2841 (cdr org-time-stamp-formats))
2842 (car org-time-stamp-formats))))
2843 (setq form (replace-match (format-time-string tf tsp) t t form))))
2845 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2846 form
2847 (calc-eval (cons form org-tbl-calc-modes)
2848 (when (and (not keep-empty) numbers) 'num)))
2849 ev (if duration (org-table-time-seconds-to-string
2850 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2851 (string-to-number (org-table-time-string-to-seconds ev))
2852 (string-to-number ev))
2853 duration-output-format)
2854 ev)))
2856 (when org-table-formula-debug
2857 (with-output-to-temp-buffer "*Substitution History*"
2858 (princ (format "Substitution history of formula
2859 Orig: %s
2860 $xyz-> %s
2861 @r$c-> %s
2862 $1-> %s\n" orig formula form0 form))
2863 (if (consp ev)
2864 (princ (format " %s^\nError: %s"
2865 (make-string (car ev) ?\-) (nth 1 ev)))
2866 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2867 ev (or fmt "NONE")
2868 (if fmt (format fmt (string-to-number ev)) ev)))))
2869 (setq bw (get-buffer-window "*Substitution History*"))
2870 (org-fit-window-to-buffer bw)
2871 (unless (and (org-called-interactively-p 'any) (not ndown))
2872 (unless (let (inhibit-redisplay)
2873 (y-or-n-p "Debugging Formula. Continue to next? "))
2874 (org-table-align)
2875 (user-error "Abort"))
2876 (delete-window bw)
2877 (message "")))
2878 (when (consp ev) (setq fmt nil ev "#ERROR"))
2879 (org-table-justify-field-maybe
2880 (format org-table-formula-field-format
2881 (if fmt (format fmt (string-to-number ev)) ev)))
2882 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2883 (call-interactively 'org-return)
2884 (setq ndown 0)))
2885 (and down (org-table-maybe-recalculate-line))
2886 (or suppress-align (and org-table-may-need-update
2887 (org-table-align))))))
2889 (defun org-table-put-field-property (prop value)
2890 (save-excursion
2891 (put-text-property (progn (skip-chars-backward "^|") (point))
2892 (progn (skip-chars-forward "^|") (point))
2893 prop value)))
2895 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2896 "Get a calc vector from a column, according to descriptor DESC.
2898 Optional arguments TBEG and COL can give the beginning of the table and
2899 the current column, to avoid unnecessary parsing.
2901 HIGHLIGHT means just highlight the range.
2903 When CORNERS-ONLY is set, only return the corners of the range as
2904 a list (line1 column1 line2 column2) where line1 and line2 are
2905 line numbers relative to beginning of table, or TBEG, and column1
2906 and column2 are table column numbers."
2907 (let* ((desc (if (eq (string-to-char desc) ?@) desc (concat "@" desc)))
2908 (col (or col (org-table-current-column)))
2909 (tbeg (or tbeg (org-table-begin)))
2910 (thisline (count-lines tbeg (line-beginning-position))))
2911 (unless (string-match org-table-range-regexp desc)
2912 (user-error "Invalid table range specifier `%s'" desc))
2913 (let ((rangep (match-end 3))
2914 (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
2915 (or (save-match-data
2916 (and (org-string-nw-p r)
2917 (org-table--descriptor-line r thisline)))
2918 thisline)))
2919 (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
2920 (or (save-match-data
2921 (and (org-string-nw-p r)
2922 (org-table--descriptor-line r thisline)))
2923 thisline)))
2924 (c1 (let ((c (and (match-end 2) (substring (match-string 2 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 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
2929 (if (or (not c) (= (string-to-number c) 0)) col
2930 (+ (string-to-number c)
2931 (if (memq (string-to-char c) '(?- ?+)) col 0))))))
2932 (save-excursion
2933 (if (and (not corners-only)
2934 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2935 ;; Just one field.
2936 (progn
2937 (forward-line (- r1 thisline))
2938 (while (not (looking-at org-table-dataline-regexp))
2939 (forward-line))
2940 (prog1 (org-trim (org-table-get-field c1))
2941 (when highlight (org-table-highlight-rectangle))))
2942 ;; A range, return a vector. First sort the numbers to get
2943 ;; a regular rectangle.
2944 (let ((first-row (min r1 r2))
2945 (last-row (max r1 r2))
2946 (first-column (min c1 c2))
2947 (last-column (max c1 c2)))
2948 (if corners-only (list first-row first-column last-row last-column)
2949 ;; Copy the range values into a list.
2950 (forward-line (- first-row thisline))
2951 (while (not (looking-at org-table-dataline-regexp))
2952 (forward-line)
2953 (incf first-row))
2954 (org-table-goto-column first-column)
2955 (let ((beg (point)))
2956 (forward-line (- last-row first-row))
2957 (while (not (looking-at org-table-dataline-regexp))
2958 (forward-line -1))
2959 (org-table-goto-column last-column)
2960 (let ((end (point)))
2961 (when highlight
2962 (org-table-highlight-rectangle
2963 beg (progn (skip-chars-forward "^|\n") (point))))
2964 ;; Return string representation of calc vector.
2965 (mapcar #'org-trim
2966 (apply #'append
2967 (org-table-copy-region beg end))))))))))))
2969 (defun org-table--descriptor-line (desc cline)
2970 "Return relative line number corresponding to descriptor DESC.
2971 The cursor is currently in relative line number CLINE."
2972 (if (string-match "\\`[0-9]+\\'" desc)
2973 (aref org-table-dlines (string-to-number desc))
2974 (when (or (not (string-match
2975 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
2976 ;; 1 2 3 4 5 6
2977 desc))
2978 (and (not (match-end 3)) (not (match-end 6)))
2979 (and (match-end 3) (match-end 6) (not (match-end 5))))
2980 (user-error "Invalid row descriptor `%s'" desc))
2981 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
2982 (hdir (match-string 2 desc))
2983 (odir (match-string 5 desc))
2984 (on (and (match-end 6) (string-to-number (match-string 6 desc))))
2985 (rel (and (match-end 6)
2986 (or (and (match-end 1) (not (match-end 3)))
2987 (match-end 5)))))
2988 (when (and hn (not hdir))
2989 (setq cline 0)
2990 (setq hdir "+")
2991 (when (eq (aref org-table-current-line-types 0) 'hline) (decf hn)))
2992 (when (and (not hn) on (not odir)) (user-error "Should never happen"))
2993 (when hn
2994 (setq cline
2995 (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
2996 (when on
2997 (setq cline
2998 (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
2999 cline)))
3001 (defun org-table--row-type (type n i backwards relative desc)
3002 "Return relative line of Nth row with type TYPE.
3003 Search starts from relative line I. When BACKWARDS in non-nil,
3004 look before I. When RELATIVE is non-nil, the reference is
3005 relative. DESC is the original descriptor that started the
3006 search, as a string."
3007 (let ((l (length org-table-current-line-types)))
3008 (catch :exit
3009 (dotimes (_ n)
3010 (while (and (incf i (if backwards -1 1))
3011 (>= i 0)
3012 (< i l)
3013 (not (eq (aref org-table-current-line-types i) type))
3014 ;; We are going to cross a hline. Check if this is
3015 ;; an authorized move.
3016 (cond
3017 ((not relative))
3018 ((not (eq (aref org-table-current-line-types i) 'hline)))
3019 ((eq org-table-relative-ref-may-cross-hline t))
3020 ((eq org-table-relative-ref-may-cross-hline 'error)
3021 (user-error "Row descriptor %s crosses hline" desc))
3022 (t (decf i (if backwards -1 1)) ; Step back.
3023 (throw :exit nil)))))))
3024 (cond ((or (< i 0) (>= i l))
3025 (user-error "Row descriptor %s leads outside table" desc))
3026 ;; The last hline doesn't exist. Instead, point to last row
3027 ;; in table.
3028 ((= i (1- l)) (1- i))
3029 (t i))))
3031 (defun org-table--error-on-old-row-references (s)
3032 (when (string-match "&[-+0-9I]" s)
3033 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3035 (defun org-table-make-reference (elements keep-empty numbers lispp)
3036 "Convert list ELEMENTS to something appropriate to insert into formula.
3037 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3038 NUMBERS indicates that everything should be converted to numbers.
3039 LISPP non-nil means to return something appropriate for a Lisp
3040 list, 'literal is for the format specifier L."
3041 ;; Calc nan (not a number) is used for the conversion of the empty
3042 ;; field to a reference for several reasons: (i) It is accepted in a
3043 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3044 ;; (ii) In a single field (not in range) it can be distinguished
3045 ;; from "(nan)" which is the reference made from a single field
3046 ;; containing "nan".
3047 (if (stringp elements)
3048 ;; field reference
3049 (if lispp
3050 (if (eq lispp 'literal)
3051 elements
3052 (if (and (eq elements "") (not keep-empty))
3054 (prin1-to-string
3055 (if numbers (string-to-number elements) elements))))
3056 (if (string-match "\\S-" elements)
3057 (progn
3058 (when numbers (setq elements (number-to-string
3059 (string-to-number elements))))
3060 (concat "(" elements ")"))
3061 (if (or (not keep-empty) numbers) "(0)" "nan")))
3062 ;; range reference
3063 (unless keep-empty
3064 (setq elements
3065 (delq nil
3066 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3067 elements))))
3068 (setq elements (or elements '())) ; if delq returns nil then we need '()
3069 (if lispp
3070 (mapconcat
3071 (lambda (x)
3072 (if (eq lispp 'literal)
3074 (prin1-to-string (if numbers (string-to-number x) x))))
3075 elements " ")
3076 (concat "[" (mapconcat
3077 (lambda (x)
3078 (if (string-match "\\S-" x)
3079 (if numbers
3080 (number-to-string (string-to-number x))
3082 (if (or (not keep-empty) numbers) "0" "nan")))
3083 elements
3084 ",") "]"))))
3086 (defun org-table-message-once-per-second (t1 &rest args)
3087 "If there has been more than one second since T1, display message.
3088 ARGS are passed as arguments to the `message' function. Returns
3089 current time if a message is printed, otherwise returns T1. If
3090 T1 is nil, always messages."
3091 (let ((curtime (current-time)))
3092 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3093 (progn (apply 'message args)
3094 curtime)
3095 t1)))
3097 ;;;###autoload
3098 (defun org-table-recalculate (&optional all noalign)
3099 "Recalculate the current table line by applying all stored formulas.
3100 With prefix arg ALL, do this for all lines in the table.
3101 With the prefix argument ALL is `(16)' \
3102 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3103 it is the symbol `iterate', recompute the table until it no longer changes.
3104 If NOALIGN is not nil, do not re-align the table after the computations
3105 are done. This is typically used internally to save time, if it is
3106 known that the table will be realigned a little later anyway."
3107 (interactive "P")
3108 (unless (memq this-command org-recalc-commands)
3109 (push this-command org-recalc-commands))
3110 (unless (org-at-table-p) (user-error "Not at a table"))
3111 (if (or (eq all 'iterate) (equal all '(16)))
3112 (org-table-iterate)
3113 (org-table-analyze)
3114 (let* ((eqlist (sort (org-table-get-stored-formulas)
3115 (lambda (a b) (string< (car a) (car b)))))
3116 (eqlist1 (copy-sequence eqlist))
3117 (inhibit-redisplay (not debug-on-error))
3118 (line-re org-table-dataline-regexp)
3119 (log-first-time (current-time))
3120 (log-last-time log-first-time)
3121 (cnt 0)
3122 beg end eqlnum eqlname)
3123 ;; Insert constants in all formulas
3124 (when eqlist
3125 (org-table-save-field
3126 (setq eqlist
3127 (mapcar
3128 (lambda (x)
3129 (when (string-match "\\`@-?I+" (car x))
3130 (user-error "Can't assign to hline relative reference"))
3131 (when (string-match "\\`$[<>]" (car x))
3132 (let ((old-lhs (car x)))
3133 (setq x
3134 (cons
3135 (substring
3136 (org-table-formula-handle-first/last-rc old-lhs)
3138 (cdr x)))
3139 (when (assoc (car x) eqlist1)
3140 (user-error "\"%s=\" formula tries to overwrite \
3141 existing formula for column %s"
3142 old-lhs
3143 (car x)))))
3144 (cons (org-table-formula-handle-first/last-rc (car x))
3145 (org-table-formula-substitute-names
3146 (org-table-formula-handle-first/last-rc (cdr x)))))
3147 eqlist))
3148 ;; Split the equation list.
3149 (dolist (eq eqlist)
3150 (if (<= (string-to-char (car eq)) ?9)
3151 (push eq eqlnum)
3152 (push eq eqlname)))
3153 (setq eqlnum (nreverse eqlnum))
3154 ;; Expand ranges in lhs of formulas
3155 (setq eqlname (org-table-expand-lhs-ranges (nreverse eqlname)))
3156 ;; Get the correct line range to process
3157 (if all
3158 (progn
3159 (setq end (copy-marker (org-table-end)))
3160 (goto-char (setq beg org-table-current-begin-pos))
3161 (cond
3162 ((re-search-forward org-table-calculate-mark-regexp end t)
3163 ;; This is a table with marked lines, compute selected
3164 ;; lines.
3165 (setq line-re org-table-recalculate-regexp))
3166 ;; Move forward to the first non-header line.
3167 ((and (re-search-forward org-table-dataline-regexp end t)
3168 (re-search-forward org-table-hline-regexp end t)
3169 (re-search-forward org-table-dataline-regexp end t))
3170 (setq beg (match-beginning 0)))
3171 ;; Just leave BEG where it is.
3172 (t nil)))
3173 (setq beg (line-beginning-position)
3174 end (copy-marker (line-beginning-position 2))))
3175 (goto-char beg)
3176 ;; Mark named fields untouchable. Also check if several
3177 ;; field/range formulas try to set the same field.
3178 (remove-text-properties beg end '(org-untouchable t))
3179 (let ((current-line (count-lines org-table-current-begin-pos
3180 (line-beginning-position)))
3181 seen-fields)
3182 (dolist (eq eqlname)
3183 (let* ((name (car eq))
3184 (location (assoc name org-table-named-field-locations))
3185 (eq-line (or (nth 1 location)
3186 (and (string-match "\\`@\\([0-9]+\\)" name)
3187 (aref org-table-dlines
3188 (string-to-number
3189 (match-string 1 name))))))
3190 (reference
3191 (if location
3192 ;; Turn field coordinates associated to NAME
3193 ;; into an absolute reference.
3194 (format "@%d$%d"
3195 (org-table-line-to-dline eq-line)
3196 (nth 2 location))
3197 name)))
3198 (when (member reference seen-fields)
3199 (user-error "Several field/range formulas try to set %s"
3200 reference))
3201 (push reference seen-fields)
3202 (when (or all (eq eq-line current-line))
3203 (org-table-goto-field name)
3204 (org-table-put-field-property :org-untouchable t)))))
3205 ;; Evaluate the column formulas, but skip fields covered by
3206 ;; field formulas.
3207 (goto-char beg)
3208 (while (re-search-forward line-re end t)
3209 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3210 ;; Unprotected line, recalculate.
3211 (incf cnt)
3212 (when all
3213 (setq log-last-time
3214 (org-table-message-once-per-second
3215 log-last-time
3216 "Re-applying formulas to full table...(line %d)" cnt)))
3217 (if (markerp org-last-recalc-line)
3218 (move-marker org-last-recalc-line (line-beginning-position))
3219 (setq org-last-recalc-line
3220 (copy-marker (line-beginning-position))))
3221 (dolist (entry eqlnum)
3222 (goto-char org-last-recalc-line)
3223 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3224 (unless (get-text-property (point) :org-untouchable)
3225 (org-table-eval-formula
3226 nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
3227 ;; Evaluate the field formulas.
3228 (dolist (eq eqlname)
3229 (let ((reference (car eq))
3230 (formula (cdr eq)))
3231 (setq log-last-time
3232 (org-table-message-once-per-second
3233 (and all log-last-time)
3234 "Re-applying formula to field: %s" (car eq)))
3235 (org-table-goto-field
3236 reference
3237 ;; Possibly create a new column, as long as
3238 ;; `org-table-formula-create-columns' allows it.
3239 (let ((column-count (progn (end-of-line)
3240 (1- (org-table-current-column)))))
3241 `(lambda (column)
3242 (when (> column 1000)
3243 (user-error "Formula column target too large"))
3244 (and (> column ,column-count)
3245 (or (eq org-table-formula-create-columns t)
3246 (and (eq org-table-formula-create-columns 'warn)
3247 (progn
3248 (org-display-warning
3249 "Out-of-bounds formula added columns")
3251 (and (eq org-table-formula-create-columns 'prompt)
3252 (yes-or-no-p
3253 "Out-of-bounds formula. Add columns? ")))))))
3254 (org-table-eval-formula nil formula t t t t))))
3255 ;; Clean up markers and internal text property.
3256 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3257 (set-marker end nil)
3258 (unless noalign
3259 (when org-table-may-need-update (org-table-align))
3260 (when all
3261 (org-table-message-once-per-second
3262 log-first-time "Re-applying formulas to %d lines... done" cnt)))
3263 (org-table-message-once-per-second
3264 (and all log-first-time) "Re-applying formulas... done")))))
3266 ;;;###autoload
3267 (defun org-table-iterate (&optional arg)
3268 "Recalculate the table until it does not change anymore.
3269 The maximum number of iterations is 10, but you can choose a different value
3270 with the prefix ARG."
3271 (interactive "P")
3272 (let ((imax (if arg (prefix-numeric-value arg) 10))
3273 (i 0)
3274 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3275 thistbl)
3276 (catch 'exit
3277 (while (< i imax)
3278 (setq i (1+ i))
3279 (org-table-recalculate 'all)
3280 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3281 (if (not (string= lasttbl thistbl))
3282 (setq lasttbl thistbl)
3283 (if (> i 1)
3284 (message "Convergence after %d iterations" i)
3285 (message "Table was already stable"))
3286 (throw 'exit t)))
3287 (user-error "No convergence after %d iterations" i))))
3289 ;;;###autoload
3290 (defun org-table-recalculate-buffer-tables ()
3291 "Recalculate all tables in the current buffer."
3292 (interactive)
3293 (save-excursion
3294 (save-restriction
3295 (widen)
3296 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3298 ;;;###autoload
3299 (defun org-table-iterate-buffer-tables ()
3300 "Iterate all tables in the buffer, to converge inter-table dependencies."
3301 (interactive)
3302 (let* ((imax 10)
3303 (i imax)
3304 (checksum (md5 (buffer-string)))
3306 (save-excursion
3307 (save-restriction
3308 (widen)
3309 (catch 'exit
3310 (while (> i 0)
3311 (setq i (1- i))
3312 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3313 (if (equal checksum (setq c1 (md5 (buffer-string))))
3314 (progn
3315 (message "Convergence after %d iterations" (- imax i))
3316 (throw 'exit t))
3317 (setq checksum c1)))
3318 (user-error "No convergence after %d iterations" imax))))))
3320 (defun org-table-calc-current-TBLFM (&optional arg)
3321 "Apply the #+TBLFM in the line at point to the table."
3322 (interactive "P")
3323 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3324 (let ((formula (buffer-substring
3325 (line-beginning-position)
3326 (line-end-position))))
3327 (save-excursion
3328 ;; Insert a temporary formula at right after the table
3329 (goto-char (org-table-TBLFM-begin))
3330 (let ((s (point-marker)))
3331 (insert formula "\n")
3332 (let ((e (point-marker)))
3333 ;; Recalculate the table.
3334 (beginning-of-line 0) ; move to the inserted line
3335 (skip-chars-backward " \r\n\t")
3336 (unwind-protect
3337 (org-call-with-arg #'org-table-recalculate (or arg t))
3338 ;; Delete the formula inserted temporarily.
3339 (delete-region s e)
3340 (set-marker s nil)
3341 (set-marker e nil)))))))
3343 (defun org-table-TBLFM-begin ()
3344 "Find the beginning of the TBLFM lines and return its position.
3345 Return nil when the beginning of TBLFM line was not found."
3346 (save-excursion
3347 (when (progn (forward-line 1)
3348 (re-search-backward org-table-TBLFM-begin-regexp nil t))
3349 (line-beginning-position 2))))
3351 (defun org-table-expand-lhs-ranges (equations)
3352 "Expand list of formulas.
3353 If some of the RHS in the formulas are ranges or a row reference, expand
3354 them to individual field equations for each field."
3355 (let (res)
3356 (dolist (e equations (nreverse res))
3357 (let ((lhs (car e))
3358 (rhs (cdr e)))
3359 (cond
3360 ((string-match "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
3361 ;; This just refers to one fixed field.
3362 (push e res))
3363 ((string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
3364 ;; This just refers to one fixed named field.
3365 (push e res))
3366 ((string-match "\\`@[0-9]+\\'" lhs)
3367 (dotimes (ic org-table-current-ncol)
3368 (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
3369 rhs)
3370 res)))
3372 (let* ((range (org-table-get-range
3373 lhs org-table-current-begin-pos 1 nil 'corners))
3374 (r1 (org-table-line-to-dline (nth 0 range)))
3375 (c1 (nth 1 range))
3376 (r2 (org-table-line-to-dline (nth 2 range) 'above))
3377 (c2 (nth 3 range)))
3378 (loop for ir from r1 to r2 do
3379 (loop for ic from c1 to c2 do
3380 (push
3381 (cons (propertize (format "@%d$%d" ir ic) :orig-eqn e)
3382 rhs)
3383 res))))))))))
3385 (defun org-table-formula-handle-first/last-rc (s)
3386 "Replace @<, @>, $<, $> with first/last row/column of the table.
3387 So @< and $< will always be replaced with @1 and $1, respectively.
3388 The advantage of these special markers are that structure editing of
3389 the table will not change them, while @1 and $1 will be modified
3390 when a line/row is swapped out of that privileged position. So for
3391 formulas that use a range of rows or columns, it may often be better
3392 to anchor the formula with \"I\" row markers, or to offset from the
3393 borders of the table using the @< @> $< $> makers."
3394 (let (n nmax len char (start 0))
3395 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3396 s start)
3397 (if (match-end 3)
3398 (setq start (match-end 3))
3399 (setq nmax (if (equal (match-string 1 s) "@")
3400 (1- (length org-table-dlines))
3401 org-table-current-ncol)
3402 len (- (match-end 2) (match-beginning 2))
3403 char (string-to-char (match-string 2 s))
3404 n (if (= char ?<)
3406 (- nmax len -1)))
3407 (if (or (< n 1) (> n nmax))
3408 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3409 (match-string 0 s) s))
3410 (setq start (match-beginning 0))
3411 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3414 (defun org-table-formula-substitute-names (f)
3415 "Replace $const with values in string F."
3416 (let ((start 0)
3417 (pp (/= (string-to-char f) ?'))
3418 (duration (org-string-match-p ";.*[Tt].*\\'" f))
3419 (new (replace-regexp-in-string ; Check for column names.
3420 org-table-column-name-regexp
3421 (lambda (m)
3422 (concat "$" (cdr (assoc (match-string 1 m)
3423 org-table-column-names))))
3424 f t t)))
3425 ;; Parameters and constants.
3426 (while (setq start
3427 (string-match
3428 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3429 new start))
3430 (if (match-end 2) (setq start (match-end 2))
3431 (incf start)
3432 ;; When a duration is expected, convert value on the fly.
3433 (let ((value
3434 (save-match-data
3435 (let ((v (org-table-get-constant (match-string 1 new))))
3436 (if (and (org-string-nw-p v) duration)
3437 (org-table-time-string-to-seconds v)
3438 v)))))
3439 (when value
3440 (setq new (replace-match
3441 (concat (and pp "(") value (and pp ")")) t t new))))))
3442 (if org-table-formula-debug (org-propertize new :orig-formula f)) new))
3444 (defun org-table-get-constant (const)
3445 "Find the value for a parameter or constant in a formula.
3446 Parameters get priority."
3447 (or (cdr (assoc const org-table-local-parameters))
3448 (cdr (assoc const org-table-formula-constants-local))
3449 (cdr (assoc const org-table-formula-constants))
3450 (and (fboundp 'constants-get) (constants-get const))
3451 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3452 (org-entry-get nil (substring const 5) 'inherit))
3453 "#UNDEFINED_NAME"))
3455 (defvar org-table-fedit-map
3456 (let ((map (make-sparse-keymap)))
3457 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3458 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3459 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3460 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3461 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3462 (org-defkey map "\C-c?" 'org-table-show-reference)
3463 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3464 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3465 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3466 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3467 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3468 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3469 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3470 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3471 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3472 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3473 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3474 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3475 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3476 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3477 map))
3479 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3480 '("Edit-Formulas"
3481 ["Finish and Install" org-table-fedit-finish t]
3482 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3483 ["Abort" org-table-fedit-abort t]
3484 "--"
3485 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3486 ["Complete Lisp Symbol" lisp-complete-symbol t]
3487 "--"
3488 "Shift Reference at Point"
3489 ["Up" org-table-fedit-ref-up t]
3490 ["Down" org-table-fedit-ref-down t]
3491 ["Left" org-table-fedit-ref-left t]
3492 ["Right" org-table-fedit-ref-right t]
3494 "Change Test Row for Column Formulas"
3495 ["Up" org-table-fedit-line-up t]
3496 ["Down" org-table-fedit-line-down t]
3497 "--"
3498 ["Scroll Table Window" org-table-fedit-scroll t]
3499 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3500 ["Show Table Grid" org-table-fedit-toggle-coordinates
3501 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3502 org-table-overlay-coordinates)]
3503 "--"
3504 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3505 :style toggle :selected org-table-buffer-is-an]))
3507 (defvar org-pos)
3509 ;;;###autoload
3510 (defun org-table-edit-formulas ()
3511 "Edit the formulas of the current table in a separate buffer."
3512 (interactive)
3513 (when (save-excursion (beginning-of-line)
3514 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3515 (beginning-of-line 0))
3516 (unless (org-at-table-p) (user-error "Not at a table"))
3517 (org-table-analyze)
3518 (let ((key (org-table-current-field-formula 'key 'noerror))
3519 (eql (sort (org-table-get-stored-formulas 'noerror)
3520 #'org-table-formula-less-p))
3521 (pos (point-marker))
3522 (startline 1)
3523 (wc (current-window-configuration))
3524 (sel-win (selected-window))
3525 (titles '((column . "# Column Formulas\n")
3526 (field . "# Field and Range Formulas\n")
3527 (named . "# Named Field Formulas\n"))))
3528 (org-switch-to-buffer-other-window "*Edit Formulas*")
3529 (erase-buffer)
3530 ;; Keep global-font-lock-mode from turning on font-lock-mode
3531 (let ((font-lock-global-modes '(not fundamental-mode)))
3532 (fundamental-mode))
3533 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3534 (org-set-local 'org-pos pos)
3535 (org-set-local 'org-window-configuration wc)
3536 (org-set-local 'org-selected-window sel-win)
3537 (use-local-map org-table-fedit-map)
3538 (org-add-hook 'post-command-hook #'org-table-fedit-post-command t t)
3539 (easy-menu-add org-table-fedit-menu)
3540 (setq startline (org-current-line))
3541 (dolist (entry eql)
3542 (let* ((type (cond
3543 ((string-match "\\`$[<>]" (car entry)) 'column)
3544 ((equal (string-to-char (car entry)) ?@) 'field)
3545 ((string-match "\\'[0-9]" (car entry)) 'column)
3546 (t 'named)))
3547 (title (assq type titles)))
3548 (when title
3549 (unless (bobp) (insert "\n"))
3550 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3551 (setq titles (remove title titles)))
3552 (when (equal key (car entry)) (setq startline (org-current-line)))
3553 (let ((s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3554 (car entry) " = " (cdr entry) "\n")))
3555 (remove-text-properties 0 (length s) '(face nil) s)
3556 (insert s))))
3557 (when (eq org-table-use-standard-references t)
3558 (org-table-fedit-toggle-ref-type))
3559 (org-goto-line startline)
3560 (message
3561 (substitute-command-keys "\\<org-mode-map>\
3562 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3563 See menu for more commands."))))
3565 (defun org-table-fedit-post-command ()
3566 (when (not (memq this-command '(lisp-complete-symbol)))
3567 (let ((win (selected-window)))
3568 (save-excursion
3569 (ignore-errors (org-table-show-reference))
3570 (select-window win)))))
3572 (defun org-table-formula-to-user (s)
3573 "Convert a formula from internal to user representation."
3574 (if (eq org-table-use-standard-references t)
3575 (org-table-convert-refs-to-an s)
3578 (defun org-table-formula-from-user (s)
3579 "Convert a formula from user to internal representation."
3580 (if org-table-use-standard-references
3581 (org-table-convert-refs-to-rc s)
3584 (defun org-table-convert-refs-to-rc (s)
3585 "Convert spreadsheet references from A7 to @7$28.
3586 Works for single references, but also for entire formulas and even the
3587 full TBLFM line."
3588 (let ((start 0))
3589 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3590 (cond
3591 ((match-end 3)
3592 ;; format match, just advance
3593 (setq start (match-end 0)))
3594 ((and (> (match-beginning 0) 0)
3595 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3596 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3597 ;; 3.e5 or something like this.
3598 (setq start (match-end 0)))
3599 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3600 ;; (member (match-string 1 s)
3601 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3603 ;; function name, just advance
3604 (setq start (match-end 0)))
3606 (setq start (match-beginning 0)
3607 s (replace-match
3608 (if (equal (match-string 2 s) "&")
3609 (format "$%d" (org-letters-to-number (match-string 1 s)))
3610 (format "@%d$%d"
3611 (string-to-number (match-string 2 s))
3612 (org-letters-to-number (match-string 1 s))))
3613 t t s)))))
3616 (defun org-table-convert-refs-to-an (s)
3617 "Convert spreadsheet references from to @7$28 to AB7.
3618 Works for single references, but also for entire formulas and even the
3619 full TBLFM line."
3620 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3621 (setq s (replace-match
3622 (format "%s%d"
3623 (org-number-to-letters
3624 (string-to-number (match-string 2 s)))
3625 (string-to-number (match-string 1 s)))
3626 t t s)))
3627 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3628 (setq s (replace-match (concat "\\1"
3629 (org-number-to-letters
3630 (string-to-number (match-string 2 s))) "&")
3631 t nil s)))
3634 (defun org-letters-to-number (s)
3635 "Convert a base 26 number represented by letters into an integer.
3636 For example: AB -> 28."
3637 (let ((n 0))
3638 (setq s (upcase s))
3639 (while (> (length s) 0)
3640 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3641 s (substring s 1)))
3644 (defun org-number-to-letters (n)
3645 "Convert an integer into a base 26 number represented by letters.
3646 For example: 28 -> AB."
3647 (let ((s ""))
3648 (while (> n 0)
3649 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3650 n (/ (1- n) 26)))
3653 (defun org-table-time-string-to-seconds (s)
3654 "Convert a time string into numerical duration in seconds.
3655 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3656 If S is a string representing a number, keep this number."
3657 (if (equal s "")
3659 (let (hour minus min sec res)
3660 (cond
3661 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3662 (setq minus (< 0 (length (match-string 1 s)))
3663 hour (string-to-number (match-string 2 s))
3664 min (string-to-number (match-string 3 s))
3665 sec (string-to-number (match-string 4 s)))
3666 (if minus
3667 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3668 (setq res (+ (* hour 3600) (* min 60) sec))))
3669 ((and (not (string-match org-ts-regexp-both s))
3670 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3671 (setq minus (< 0 (length (match-string 1 s)))
3672 hour (string-to-number (match-string 2 s))
3673 min (string-to-number (match-string 3 s)))
3674 (if minus
3675 (setq res (- (+ (* hour 3600) (* min 60))))
3676 (setq res (+ (* hour 3600) (* min 60)))))
3677 (t (setq res (string-to-number s))))
3678 (number-to-string res))))
3680 (defun org-table-time-seconds-to-string (secs &optional output-format)
3681 "Convert a number of seconds to a time string.
3682 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3683 minutes or seconds."
3684 (let* ((secs0 (abs secs))
3685 (res
3686 (cond ((eq output-format 'days)
3687 (format "%.3f" (/ (float secs0) 86400)))
3688 ((eq output-format 'hours)
3689 (format "%.2f" (/ (float secs0) 3600)))
3690 ((eq output-format 'minutes)
3691 (format "%.1f" (/ (float secs0) 60)))
3692 ((eq output-format 'seconds)
3693 (format "%d" secs0))
3694 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3695 (if (< secs 0) (concat "-" res) res)))
3697 (defun org-table-fedit-convert-buffer (function)
3698 "Convert all references in this buffer, using FUNCTION."
3699 (let ((origin (copy-marker (line-beginning-position))))
3700 (goto-char (point-min))
3701 (while (not (eobp))
3702 (insert (funcall function (buffer-substring (point) (line-end-position))))
3703 (delete-region (point) (line-end-position))
3704 (forward-line))
3705 (goto-char origin)
3706 (set-marker origin nil)))
3708 (defun org-table-fedit-toggle-ref-type ()
3709 "Convert all references in the buffer from B3 to @3$2 and back."
3710 (interactive)
3711 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3712 (org-table-fedit-convert-buffer
3713 (if org-table-buffer-is-an
3714 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3715 (message "Reference type switched to %s"
3716 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3718 (defun org-table-fedit-ref-up ()
3719 "Shift the reference at point one row/hline up."
3720 (interactive)
3721 (org-table-fedit-shift-reference 'up))
3722 (defun org-table-fedit-ref-down ()
3723 "Shift the reference at point one row/hline down."
3724 (interactive)
3725 (org-table-fedit-shift-reference 'down))
3726 (defun org-table-fedit-ref-left ()
3727 "Shift the reference at point one field to the left."
3728 (interactive)
3729 (org-table-fedit-shift-reference 'left))
3730 (defun org-table-fedit-ref-right ()
3731 "Shift the reference at point one field to the right."
3732 (interactive)
3733 (org-table-fedit-shift-reference 'right))
3735 (defun org-table-fedit-shift-reference (dir)
3736 (cond
3737 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3738 (if (memq dir '(left right))
3739 (org-rematch-and-replace 1 (eq dir 'left))
3740 (user-error "Cannot shift reference in this direction")))
3741 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3742 ;; A B3-like reference
3743 (if (memq dir '(up down))
3744 (org-rematch-and-replace 2 (eq dir 'up))
3745 (org-rematch-and-replace 1 (eq dir 'left))))
3746 ((org-in-regexp
3747 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3748 ;; An internal reference
3749 (if (memq dir '(up down))
3750 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3751 (org-rematch-and-replace 5 (eq dir 'left))))))
3753 (defun org-rematch-and-replace (n &optional decr hline)
3754 "Re-match the group N, and replace it with the shifted reference."
3755 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3756 (goto-char (match-beginning n))
3757 (and (looking-at (regexp-quote (match-string n)))
3758 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3759 t t)))
3761 (defun org-table-shift-refpart (ref &optional decr hline)
3762 "Shift a reference part REF.
3763 If DECR is set, decrease the references row/column, else increase.
3764 If HLINE is set, this may be a hline reference, it certainly is not
3765 a translation reference."
3766 (save-match-data
3767 (let* ((sign (string-match "^[-+]" ref)) n)
3769 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3770 (cond
3771 ((and hline (string-match "^I+" ref))
3772 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3773 (setq n (+ n (if decr -1 1)))
3774 (if (= n 0) (setq n (+ n (if decr -1 1))))
3775 (if sign
3776 (setq sign (if (< n 0) "-" "+") n (abs n))
3777 (setq n (max 1 n)))
3778 (concat sign (make-string n ?I)))
3780 ((string-match "^[0-9]+" ref)
3781 (setq n (string-to-number (concat sign ref)))
3782 (setq n (+ n (if decr -1 1)))
3783 (if sign
3784 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3785 (number-to-string (max 1 n))))
3787 ((string-match "^[a-zA-Z]+" ref)
3788 (org-number-to-letters
3789 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3791 (t (user-error "Cannot shift reference"))))))
3793 (defun org-table-fedit-toggle-coordinates ()
3794 "Toggle the display of coordinates in the referenced table."
3795 (interactive)
3796 (let ((pos (marker-position org-pos)))
3797 (with-current-buffer (marker-buffer org-pos)
3798 (save-excursion
3799 (goto-char pos)
3800 (org-table-toggle-coordinate-overlays)))))
3802 (defun org-table-fedit-finish (&optional arg)
3803 "Parse the buffer for formula definitions and install them.
3804 With prefix ARG, apply the new formulas to the table."
3805 (interactive "P")
3806 (org-table-remove-rectangle-highlight)
3807 (if org-table-use-standard-references
3808 (progn
3809 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3810 (setq org-table-buffer-is-an nil)))
3811 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3812 (goto-char (point-min))
3813 (while (re-search-forward
3814 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3815 nil t)
3816 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3817 form (match-string 3))
3818 (setq form (org-trim form))
3819 (when (not (equal form ""))
3820 (while (string-match "[ \t]*\n[ \t]*" form)
3821 (setq form (replace-match " " t t form)))
3822 (when (assoc var eql)
3823 (user-error "Double formulas for %s" var))
3824 (push (cons var form) eql)))
3825 (setq org-pos nil)
3826 (set-window-configuration org-window-configuration)
3827 (select-window sel-win)
3828 (goto-char pos)
3829 (unless (org-at-table-p)
3830 (user-error "Lost table position - cannot install formulas"))
3831 (org-table-store-formulas eql)
3832 (move-marker pos nil)
3833 (kill-buffer "*Edit Formulas*")
3834 (if arg
3835 (org-table-recalculate 'all)
3836 (message "New formulas installed - press C-u C-c C-c to apply."))))
3838 (defun org-table-fedit-abort ()
3839 "Abort editing formulas, without installing the changes."
3840 (interactive)
3841 (org-table-remove-rectangle-highlight)
3842 (let ((pos org-pos) (sel-win org-selected-window))
3843 (set-window-configuration org-window-configuration)
3844 (select-window sel-win)
3845 (goto-char pos)
3846 (move-marker pos nil)
3847 (message "Formula editing aborted without installing changes")))
3849 (defun org-table-fedit-lisp-indent ()
3850 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3851 (interactive)
3852 (let ((pos (point)) beg end ind)
3853 (beginning-of-line 1)
3854 (cond
3855 ((looking-at "[ \t]")
3856 (goto-char pos)
3857 (call-interactively 'lisp-indent-line))
3858 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3859 ((not (fboundp 'pp-buffer))
3860 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3861 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3862 (goto-char (- (match-end 0) 2))
3863 (setq beg (point))
3864 (setq ind (make-string (current-column) ?\ ))
3865 (condition-case nil (forward-sexp 1)
3866 (error
3867 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3868 (setq end (point))
3869 (save-restriction
3870 (narrow-to-region beg end)
3871 (if (eq last-command this-command)
3872 (progn
3873 (goto-char (point-min))
3874 (setq this-command nil)
3875 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3876 (replace-match " ")))
3877 (pp-buffer)
3878 (untabify (point-min) (point-max))
3879 (goto-char (1+ (point-min)))
3880 (while (re-search-forward "^." nil t)
3881 (beginning-of-line 1)
3882 (insert ind))
3883 (goto-char (point-max))
3884 (org-delete-backward-char 1)))
3885 (goto-char beg))
3886 (t nil))))
3888 (defvar org-show-positions nil)
3890 (defun org-table-show-reference (&optional local)
3891 "Show the location/value of the $ expression at point."
3892 (interactive)
3893 (org-table-remove-rectangle-highlight)
3894 (when local (org-table-analyze))
3895 (catch 'exit
3896 (let ((pos (if local (point) org-pos))
3897 (table-start (if local org-table-current-begin-pos (org-table-begin)))
3898 (face2 'highlight)
3899 (org-inhibit-highlight-removal t)
3900 (win (selected-window))
3901 (org-show-positions nil)
3902 var name e what match dest)
3903 (setq what (cond
3904 ((org-in-regexp "^@[0-9]+[ \t=]")
3905 (setq match (concat (substring (match-string 0) 0 -1)
3906 "$1.."
3907 (substring (match-string 0) 0 -1)
3908 "$100"))
3909 'range)
3910 ((or (org-in-regexp org-table-range-regexp2)
3911 (org-in-regexp org-table-translate-regexp)
3912 (org-in-regexp org-table-range-regexp))
3913 (setq match
3914 (save-match-data
3915 (org-table-convert-refs-to-rc (match-string 0))))
3916 'range)
3917 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3918 ((org-in-regexp "\\$[0-9]+") 'column)
3919 ((not local) nil)
3920 (t (user-error "No reference at point")))
3921 match (and what (or match (match-string 0))))
3922 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3923 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3924 'secondary-selection))
3925 (org-add-hook 'before-change-functions
3926 #'org-table-remove-rectangle-highlight)
3927 (when (eq what 'name) (setq var (substring match 1)))
3928 (when (eq what 'range)
3929 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
3930 (setq match (org-table-formula-substitute-names match)))
3931 (unless local
3932 (save-excursion
3933 (end-of-line)
3934 (re-search-backward "^\\S-" nil t)
3935 (beginning-of-line)
3936 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3937 \\([0-9]+\\|&\\)\\) *=")
3938 (setq dest
3939 (save-match-data
3940 (org-table-convert-refs-to-rc (match-string 1))))
3941 (org-table-add-rectangle-overlay
3942 (match-beginning 1) (match-end 1) face2))))
3943 (if (and (markerp pos) (marker-buffer pos))
3944 (if (get-buffer-window (marker-buffer pos))
3945 (select-window (get-buffer-window (marker-buffer pos)))
3946 (org-switch-to-buffer-other-window (get-buffer-window
3947 (marker-buffer pos)))))
3948 (goto-char pos)
3949 (org-table-force-dataline)
3950 (when dest
3951 (setq name (substring dest 1))
3952 (cond
3953 ((org-string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3954 (org-table-goto-field dest))
3955 ((org-string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
3956 dest)
3957 (org-table-goto-field dest))
3958 (t (org-table-goto-column (string-to-number name))))
3959 (move-marker pos (point))
3960 (org-table-highlight-rectangle nil nil face2))
3961 (cond
3962 ((equal dest match))
3963 ((not match))
3964 ((eq what 'range)
3965 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
3966 ((setq e (assoc var org-table-named-field-locations))
3967 (org-table-goto-field var)
3968 (org-table-highlight-rectangle)
3969 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3970 ((setq e (assoc var org-table-column-names))
3971 (org-table-goto-column (string-to-number (cdr e)))
3972 (org-table-highlight-rectangle)
3973 (goto-char table-start)
3974 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3975 (org-table-end) t)
3976 (progn
3977 (goto-char (match-beginning 1))
3978 (org-table-highlight-rectangle)
3979 (message "Named column (column %s)" (cdr e)))
3980 (user-error "Column name not found")))
3981 ((eq what 'column)
3982 ;; Column number.
3983 (org-table-goto-column (string-to-number (substring match 1)))
3984 (org-table-highlight-rectangle)
3985 (message "Column %s" (substring match 1)))
3986 ((setq e (assoc var org-table-local-parameters))
3987 (goto-char table-start)
3988 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3989 (progn
3990 (goto-char (match-beginning 1))
3991 (org-table-highlight-rectangle)
3992 (message "Local parameter."))
3993 (user-error "Parameter not found")))
3994 ((not var) (user-error "No reference at point"))
3995 ((setq e (assoc var org-table-formula-constants-local))
3996 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3997 var (cdr e)))
3998 ((setq e (assoc var org-table-formula-constants))
3999 (message "Constant: $%s=%s in `org-table-formula-constants'."
4000 var (cdr e)))
4001 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4002 (message "Constant: $%s=%s, from `constants.el'%s."
4003 var e (format " (%s units)" constants-unit-system)))
4004 (t (user-error "Undefined name $%s" var)))
4005 (goto-char pos)
4006 (when (and org-show-positions
4007 (not (memq this-command '(org-table-fedit-scroll
4008 org-table-fedit-scroll-down))))
4009 (push pos org-show-positions)
4010 (push table-start org-show-positions)
4011 (let ((min (apply 'min org-show-positions))
4012 (max (apply 'max org-show-positions)))
4013 (set-window-start (selected-window) min)
4014 (goto-char max)
4015 (or (pos-visible-in-window-p max)
4016 (set-window-start (selected-window) max))))
4017 (select-window win))))
4019 (defun org-table-force-dataline ()
4020 "Make sure the cursor is in a dataline in a table."
4021 (unless (save-excursion
4022 (beginning-of-line 1)
4023 (looking-at org-table-dataline-regexp))
4024 (let* ((re org-table-dataline-regexp)
4025 (p1 (save-excursion (re-search-forward re nil 'move)))
4026 (p2 (save-excursion (re-search-backward re nil 'move))))
4027 (cond ((and p1 p2)
4028 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4029 p1 p2)))
4030 ((or p1 p2) (goto-char (or p1 p2)))
4031 (t (user-error "No table dataline around here"))))))
4033 (defun org-table-fedit-line-up ()
4034 "Move cursor one line up in the window showing the table."
4035 (interactive)
4036 (org-table-fedit-move 'previous-line))
4038 (defun org-table-fedit-line-down ()
4039 "Move cursor one line down in the window showing the table."
4040 (interactive)
4041 (org-table-fedit-move 'next-line))
4043 (defun org-table-fedit-move (command)
4044 "Move the cursor in the window showing the table.
4045 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4046 (let ((org-table-allow-automatic-line-recalculation nil)
4047 (pos org-pos) (win (selected-window)) p)
4048 (select-window (get-buffer-window (marker-buffer org-pos)))
4049 (setq p (point))
4050 (call-interactively command)
4051 (while (and (org-at-table-p)
4052 (org-at-table-hline-p))
4053 (call-interactively command))
4054 (or (org-at-table-p) (goto-char p))
4055 (move-marker pos (point))
4056 (select-window win)))
4058 (defun org-table-fedit-scroll (N)
4059 (interactive "p")
4060 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4061 (scroll-other-window N)))
4063 (defun org-table-fedit-scroll-down (N)
4064 (interactive "p")
4065 (org-table-fedit-scroll (- N)))
4067 (defvar org-table-rectangle-overlays nil)
4069 (defun org-table-add-rectangle-overlay (beg end &optional face)
4070 "Add a new overlay."
4071 (let ((ov (make-overlay beg end)))
4072 (overlay-put ov 'face (or face 'secondary-selection))
4073 (push ov org-table-rectangle-overlays)))
4075 (defun org-table-highlight-rectangle (&optional beg end face)
4076 "Highlight rectangular region in a table.
4077 When buffer positions BEG and END are provided, use them to
4078 delimit the region to highlight. Otherwise, refer to point. Use
4079 FACE, when non-nil, for the highlight."
4080 (let* ((beg (or beg (point)))
4081 (end (or end (point)))
4082 (b (min beg end))
4083 (e (max beg end))
4084 (start-coordinates
4085 (save-excursion
4086 (goto-char b)
4087 (cons (line-beginning-position) (org-table-current-column))))
4088 (end-coordinates
4089 (save-excursion
4090 (goto-char e)
4091 (cons (line-beginning-position) (org-table-current-column)))))
4092 (when (boundp 'org-show-positions)
4093 (setq org-show-positions (cons b (cons e org-show-positions))))
4094 (goto-char (car start-coordinates))
4095 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4096 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4097 (last-row (car end-coordinates)))
4098 (while (<= (point) last-row)
4099 (when (looking-at org-table-dataline-regexp)
4100 (org-table-goto-column column-start)
4101 (skip-chars-backward "^|\n")
4102 (let ((p (point)))
4103 (org-table-goto-column column-end)
4104 (skip-chars-forward "^|\n")
4105 (org-table-add-rectangle-overlay p (point) face)))
4106 (forward-line)))
4107 (goto-char (car start-coordinates)))
4108 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4110 (defun org-table-remove-rectangle-highlight (&rest ignore)
4111 "Remove the rectangle overlays."
4112 (unless org-inhibit-highlight-removal
4113 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4114 (mapc 'delete-overlay org-table-rectangle-overlays)
4115 (setq org-table-rectangle-overlays nil)))
4117 (defvar org-table-coordinate-overlays nil
4118 "Collects the coordinate grid overlays, so that they can be removed.")
4119 (make-variable-buffer-local 'org-table-coordinate-overlays)
4121 (defun org-table-overlay-coordinates ()
4122 "Add overlays to the table at point, to show row/column coordinates."
4123 (interactive)
4124 (mapc 'delete-overlay org-table-coordinate-overlays)
4125 (setq org-table-coordinate-overlays nil)
4126 (save-excursion
4127 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4128 (goto-char (org-table-begin))
4129 (while (org-at-table-p)
4130 (setq eol (point-at-eol))
4131 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4132 (push ov org-table-coordinate-overlays)
4133 (setq hline (looking-at org-table-hline-regexp))
4134 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4135 (format "%4d" (setq id (1+ id)))))
4136 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4137 (when hline
4138 (setq ic 0)
4139 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4140 (setq beg (1+ (match-beginning 0))
4141 ic (1+ ic)
4142 s1 (concat "$" (int-to-string ic))
4143 s2 (org-number-to-letters ic)
4144 str (if (eq org-table-use-standard-references t) s2 s1))
4145 (setq ov (make-overlay beg (+ beg (length str))))
4146 (push ov org-table-coordinate-overlays)
4147 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4148 (beginning-of-line 2)))))
4150 ;;;###autoload
4151 (defun org-table-toggle-coordinate-overlays ()
4152 "Toggle the display of Row/Column numbers in tables."
4153 (interactive)
4154 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4155 (message "Tables Row/Column numbers display turned %s"
4156 (if org-table-overlay-coordinates "on" "off"))
4157 (if (and (org-at-table-p) org-table-overlay-coordinates)
4158 (org-table-align))
4159 (unless org-table-overlay-coordinates
4160 (mapc 'delete-overlay org-table-coordinate-overlays)
4161 (setq org-table-coordinate-overlays nil)))
4163 ;;;###autoload
4164 (defun org-table-toggle-formula-debugger ()
4165 "Toggle the formula debugger in tables."
4166 (interactive)
4167 (setq org-table-formula-debug (not org-table-formula-debug))
4168 (message "Formula debugging has been turned %s"
4169 (if org-table-formula-debug "on" "off")))
4171 ;;; The orgtbl minor mode
4173 ;; Define a minor mode which can be used in other modes in order to
4174 ;; integrate the org-mode table editor.
4176 ;; This is really a hack, because the org-mode table editor uses several
4177 ;; keys which normally belong to the major mode, for example the TAB and
4178 ;; RET keys. Here is how it works: The minor mode defines all the keys
4179 ;; necessary to operate the table editor, but wraps the commands into a
4180 ;; function which tests if the cursor is currently inside a table. If that
4181 ;; is the case, the table editor command is executed. However, when any of
4182 ;; those keys is used outside a table, the function uses `key-binding' to
4183 ;; look up if the key has an associated command in another currently active
4184 ;; keymap (minor modes, major mode, global), and executes that command.
4185 ;; There might be problems if any of the keys used by the table editor is
4186 ;; otherwise used as a prefix key.
4188 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4189 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4190 ;; addresses this by checking explicitly for both bindings.
4192 ;; The optimized version (see variable `orgtbl-optimized') takes over
4193 ;; all keys which are bound to `self-insert-command' in the *global map*.
4194 ;; Some modes bind other commands to simple characters, for example
4195 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4196 ;; active, this binding is ignored inside tables and replaced with a
4197 ;; modified self-insert.
4200 (defvar orgtbl-mode-map (make-keymap)
4201 "Keymap for `orgtbl-mode'.")
4203 (defvar org-old-auto-fill-inhibit-regexp nil
4204 "Local variable used by `orgtbl-mode'.")
4206 (defconst orgtbl-line-start-regexp
4207 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4208 "Matches a line belonging to an orgtbl.")
4210 (defconst orgtbl-extra-font-lock-keywords
4211 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4212 0 (quote 'org-table) 'prepend))
4213 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4215 ;; Install it as a minor mode.
4216 (put 'orgtbl-mode :included t)
4217 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4219 ;;;###autoload
4220 (define-minor-mode orgtbl-mode
4221 "The `org-mode' table editor as a minor mode for use in other modes."
4222 :lighter " OrgTbl" :keymap orgtbl-mode-map
4223 (org-load-modules-maybe)
4224 (cond
4225 ((derived-mode-p 'org-mode)
4226 ;; Exit without error, in case some hook functions calls this
4227 ;; by accident in org-mode.
4228 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4229 (orgtbl-mode
4230 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4231 ;; Make sure we are first in minor-mode-map-alist
4232 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4233 ;; FIXME: maybe it should use emulation-mode-map-alists?
4234 (and c (setq minor-mode-map-alist
4235 (cons c (delq c minor-mode-map-alist)))))
4236 (org-set-local (quote org-table-may-need-update) t)
4237 (org-add-hook 'before-change-functions 'org-before-change-function
4238 nil 'local)
4239 (org-set-local 'org-old-auto-fill-inhibit-regexp
4240 auto-fill-inhibit-regexp)
4241 (org-set-local 'auto-fill-inhibit-regexp
4242 (if auto-fill-inhibit-regexp
4243 (concat orgtbl-line-start-regexp "\\|"
4244 auto-fill-inhibit-regexp)
4245 orgtbl-line-start-regexp))
4246 (add-to-invisibility-spec '(org-cwidth))
4247 (when (fboundp 'font-lock-add-keywords)
4248 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4249 (org-restart-font-lock))
4250 (easy-menu-add orgtbl-mode-menu))
4252 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4253 (org-table-cleanup-narrow-column-properties)
4254 (org-remove-from-invisibility-spec '(org-cwidth))
4255 (remove-hook 'before-change-functions 'org-before-change-function t)
4256 (when (fboundp 'font-lock-remove-keywords)
4257 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4258 (org-restart-font-lock))
4259 (easy-menu-remove orgtbl-mode-menu)
4260 (force-mode-line-update 'all))))
4262 (defun org-table-cleanup-narrow-column-properties ()
4263 "Remove all properties related to narrow-column invisibility."
4264 (let ((s (point-min)))
4265 (while (setq s (text-property-any s (point-max)
4266 'display org-narrow-column-arrow))
4267 (remove-text-properties s (1+ s) '(display t)))
4268 (setq s (point-min))
4269 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4270 (remove-text-properties s (1+ s) '(org-cwidth t)))
4271 (setq s (point-min))
4272 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4273 (remove-text-properties s (1+ s) '(invisible t)))))
4275 (defun orgtbl-make-binding (fun n &rest keys)
4276 "Create a function for binding in the table minor mode.
4277 FUN is the command to call inside a table. N is used to create a unique
4278 command name. KEYS are keys that should be checked in for a command
4279 to execute outside of tables."
4280 (eval
4281 (list 'defun
4282 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4283 '(arg)
4284 (concat "In tables, run `" (symbol-name fun) "'.\n"
4285 "Outside of tables, run the binding of `"
4286 (mapconcat #'key-description keys "' or `")
4287 "'.")
4288 '(interactive "p")
4289 (list 'if
4290 '(org-at-table-p)
4291 (list 'call-interactively (list 'quote fun))
4292 (list 'let '(orgtbl-mode)
4293 (list 'call-interactively
4294 (append '(or)
4295 (mapcar (lambda (k)
4296 (list 'key-binding k))
4297 keys)
4298 '('orgtbl-error))))))))
4300 (defun orgtbl-error ()
4301 "Error when there is no default binding for a table key."
4302 (interactive)
4303 (user-error "This key has no function outside tables"))
4305 (defun orgtbl-setup ()
4306 "Setup orgtbl keymaps."
4307 (let ((nfunc 0)
4308 (bindings
4309 '(([(meta shift left)] org-table-delete-column)
4310 ([(meta left)] org-table-move-column-left)
4311 ([(meta right)] org-table-move-column-right)
4312 ([(meta shift right)] org-table-insert-column)
4313 ([(meta shift up)] org-table-kill-row)
4314 ([(meta shift down)] org-table-insert-row)
4315 ([(meta up)] org-table-move-row-up)
4316 ([(meta down)] org-table-move-row-down)
4317 ("\C-c\C-w" org-table-cut-region)
4318 ("\C-c\M-w" org-table-copy-region)
4319 ("\C-c\C-y" org-table-paste-rectangle)
4320 ("\C-c\C-w" org-table-wrap-region)
4321 ("\C-c-" org-table-insert-hline)
4322 ("\C-c}" org-table-toggle-coordinate-overlays)
4323 ("\C-c{" org-table-toggle-formula-debugger)
4324 ("\C-m" org-table-next-row)
4325 ([(shift return)] org-table-copy-down)
4326 ("\C-c?" org-table-field-info)
4327 ("\C-c " org-table-blank-field)
4328 ("\C-c+" org-table-sum)
4329 ("\C-c=" org-table-eval-formula)
4330 ("\C-c'" org-table-edit-formulas)
4331 ("\C-c`" org-table-edit-field)
4332 ("\C-c*" org-table-recalculate)
4333 ("\C-c^" org-table-sort-lines)
4334 ("\M-a" org-table-beginning-of-field)
4335 ("\M-e" org-table-end-of-field)
4336 ([(control ?#)] org-table-rotate-recalc-marks)))
4337 elt key fun cmd)
4338 (while (setq elt (pop bindings))
4339 (setq nfunc (1+ nfunc))
4340 (setq key (org-key (car elt))
4341 fun (nth 1 elt)
4342 cmd (orgtbl-make-binding fun nfunc key))
4343 (org-defkey orgtbl-mode-map key cmd))
4345 ;; Special treatment needed for TAB and RET
4346 (org-defkey orgtbl-mode-map [(return)]
4347 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4348 (org-defkey orgtbl-mode-map "\C-m"
4349 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4351 (org-defkey orgtbl-mode-map [(tab)]
4352 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4353 (org-defkey orgtbl-mode-map "\C-i"
4354 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4356 (org-defkey orgtbl-mode-map [(shift tab)]
4357 (orgtbl-make-binding 'org-table-previous-field 104
4358 [(shift tab)] [(tab)] "\C-i"))
4361 (unless (featurep 'xemacs)
4362 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4363 (orgtbl-make-binding 'org-table-previous-field 107
4364 [S-iso-lefttab] [backtab] [(shift tab)]
4365 [(tab)] "\C-i")))
4367 (org-defkey orgtbl-mode-map [backtab]
4368 (orgtbl-make-binding 'org-table-previous-field 108
4369 [backtab] [S-iso-lefttab] [(shift tab)]
4370 [(tab)] "\C-i"))
4372 (org-defkey orgtbl-mode-map "\M-\C-m"
4373 (orgtbl-make-binding 'org-table-wrap-region 105
4374 "\M-\C-m" [(meta return)]))
4375 (org-defkey orgtbl-mode-map [(meta return)]
4376 (orgtbl-make-binding 'org-table-wrap-region 106
4377 [(meta return)] "\M-\C-m"))
4379 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4380 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4382 (when orgtbl-optimized
4383 ;; If the user wants maximum table support, we need to hijack
4384 ;; some standard editing functions
4385 (org-remap orgtbl-mode-map
4386 'self-insert-command 'orgtbl-self-insert-command
4387 'delete-char 'org-delete-char
4388 'delete-backward-char 'org-delete-backward-char)
4389 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4390 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4391 '("OrgTbl"
4392 ["Create or convert" org-table-create-or-convert-from-region
4393 :active (not (org-at-table-p)) :keys "C-c |" ]
4394 "--"
4395 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4396 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4397 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4398 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4399 "--"
4400 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4401 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4402 ["Copy Field from Above"
4403 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4404 "--"
4405 ("Column"
4406 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4407 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4408 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4409 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4410 ("Row"
4411 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4412 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4413 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4414 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4415 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4416 "--"
4417 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4418 ("Rectangle"
4419 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4420 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4421 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4422 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4423 "--"
4424 ("Radio tables"
4425 ["Insert table template" orgtbl-insert-radio-table
4426 (assq major-mode orgtbl-radio-table-templates)]
4427 ["Comment/uncomment table" orgtbl-toggle-comment t])
4428 "--"
4429 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4430 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4431 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4432 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4433 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4434 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4435 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4436 ["Sum Column/Rectangle" org-table-sum
4437 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4438 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4439 ["Debug Formulas"
4440 org-table-toggle-formula-debugger :active (org-at-table-p)
4441 :keys "C-c {"
4442 :style toggle :selected org-table-formula-debug]
4443 ["Show Col/Row Numbers"
4444 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4445 :keys "C-c }"
4446 :style toggle :selected org-table-overlay-coordinates]
4447 "--"
4448 ("Plot"
4449 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4450 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4453 (defun orgtbl-ctrl-c-ctrl-c (arg)
4454 "If the cursor is inside a table, realign the table.
4455 If it is a table to be sent away to a receiver, do it.
4456 With prefix arg, also recompute table."
4457 (interactive "P")
4458 (let ((case-fold-search t) (pos (point)) action)
4459 (save-excursion
4460 (beginning-of-line 1)
4461 (setq action (cond
4462 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4463 ((looking-at "[ \t]*|") pos)
4464 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4465 (cond
4466 ((integerp action)
4467 (goto-char action)
4468 (org-table-maybe-eval-formula)
4469 (if arg
4470 (call-interactively 'org-table-recalculate)
4471 (org-table-maybe-recalculate-line))
4472 (call-interactively 'org-table-align)
4473 (when (orgtbl-send-table 'maybe)
4474 (run-hooks 'orgtbl-after-send-table-hook)))
4475 ((eq action 'recalc)
4476 (save-excursion
4477 (beginning-of-line 1)
4478 (skip-chars-backward " \r\n\t")
4479 (if (org-at-table-p)
4480 (org-call-with-arg 'org-table-recalculate t))))
4481 (t (let (orgtbl-mode)
4482 (call-interactively (key-binding "\C-c\C-c")))))))
4484 (defun orgtbl-create-or-convert-from-region (arg)
4485 "Create table or convert region to table, if no conflicting binding.
4486 This installs the table binding `C-c |', but only if there is no
4487 conflicting binding to this key outside orgtbl-mode."
4488 (interactive "P")
4489 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4490 (if cmd
4491 (call-interactively cmd)
4492 (call-interactively 'org-table-create-or-convert-from-region))))
4494 (defun orgtbl-tab (arg)
4495 "Justification and field motion for `orgtbl-mode'."
4496 (interactive "P")
4497 (if arg (org-table-edit-field t)
4498 (org-table-justify-field-maybe)
4499 (org-table-next-field)))
4501 (defun orgtbl-ret ()
4502 "Justification and field motion for `orgtbl-mode'."
4503 (interactive)
4504 (if (bobp)
4505 (newline)
4506 (org-table-justify-field-maybe)
4507 (org-table-next-row)))
4509 (defun orgtbl-self-insert-command (N)
4510 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4511 If the cursor is in a table looking at whitespace, the whitespace is
4512 overwritten, and the table is not marked as requiring realignment."
4513 (interactive "p")
4514 (if (and (org-at-table-p)
4516 (and org-table-auto-blank-field
4517 (member last-command
4518 '(orgtbl-hijacker-command-100
4519 orgtbl-hijacker-command-101
4520 orgtbl-hijacker-command-102
4521 orgtbl-hijacker-command-103
4522 orgtbl-hijacker-command-104
4523 orgtbl-hijacker-command-105
4524 yas/expand))
4525 (org-table-blank-field))
4527 (eq N 1)
4528 (looking-at "[^|\n]* +|"))
4529 (let (org-table-may-need-update)
4530 (goto-char (1- (match-end 0)))
4531 (org-delete-backward-char 1)
4532 (goto-char (match-beginning 0))
4533 (self-insert-command N))
4534 (setq org-table-may-need-update t)
4535 (let* (orgtbl-mode
4537 (cmd (or (key-binding
4538 (or (and (listp function-key-map)
4539 (setq a (assoc last-input-event function-key-map))
4540 (cdr a))
4541 (vector last-input-event)))
4542 'self-insert-command)))
4543 (call-interactively cmd)
4544 (if (and org-self-insert-cluster-for-undo
4545 (eq cmd 'self-insert-command))
4546 (if (not (eq last-command 'orgtbl-self-insert-command))
4547 (setq org-self-insert-command-undo-counter 1)
4548 (if (>= org-self-insert-command-undo-counter 20)
4549 (setq org-self-insert-command-undo-counter 1)
4550 (and (> org-self-insert-command-undo-counter 0)
4551 buffer-undo-list
4552 (not (cadr buffer-undo-list)) ; remove nil entry
4553 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4554 (setq org-self-insert-command-undo-counter
4555 (1+ org-self-insert-command-undo-counter))))))))
4557 ;;;###autoload
4558 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4559 "Regular expression matching exponentials as produced by calc.")
4561 (defun orgtbl-gather-send-defs ()
4562 "Gather a plist of :name, :transform, :params for each destination before
4563 a radio table."
4564 (save-excursion
4565 (goto-char (org-table-begin))
4566 (let (rtn)
4567 (beginning-of-line 0)
4568 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4569 (let ((name (org-no-properties (match-string 1)))
4570 (transform (intern (match-string 2)))
4571 (params (if (match-end 3)
4572 (read (concat "(" (match-string 3) ")")))))
4573 (push (list :name name :transform transform :params params)
4574 rtn)
4575 (beginning-of-line 0)))
4576 rtn)))
4578 (defun orgtbl-send-replace-tbl (name txt)
4579 "Find and replace table NAME with TXT."
4580 (save-excursion
4581 (goto-char (point-min))
4582 (unless (re-search-forward
4583 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4584 (user-error "Don't know where to insert translated table"))
4585 (let ((beg (line-beginning-position 2)))
4586 (unless (re-search-forward
4587 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4588 (user-error "Cannot find end of insertion region"))
4589 (beginning-of-line)
4590 (delete-region beg (point)))
4591 (insert txt "\n")))
4593 ;;;###autoload
4594 (defun org-table-to-lisp (&optional txt)
4595 "Convert the table at point to a Lisp structure.
4596 The structure will be a list. Each item is either the symbol `hline'
4597 for a horizontal separator line, or a list of field values as strings.
4598 The table is taken from the parameter TXT, or from the buffer at point."
4599 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4600 (let ((txt (or txt
4601 (buffer-substring-no-properties (org-table-begin)
4602 (org-table-end)))))
4603 (mapcar (lambda (x)
4604 (if (string-match org-table-hline-regexp x) 'hline
4605 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4606 (org-split-string txt "[ \t]*\n[ \t]*"))))
4608 (defun orgtbl-send-table (&optional maybe)
4609 "Send a transformed version of table at point to the receiver position.
4610 With argument MAYBE, fail quietly if no transformation is defined
4611 for this table."
4612 (interactive)
4613 (catch 'exit
4614 (unless (org-at-table-p) (user-error "Not at a table"))
4615 ;; when non-interactive, we assume align has just happened.
4616 (when (org-called-interactively-p 'any) (org-table-align))
4617 (let ((dests (orgtbl-gather-send-defs))
4618 (table (org-table-to-lisp
4619 (buffer-substring-no-properties (org-table-begin)
4620 (org-table-end))))
4621 (ntbl 0))
4622 (unless dests
4623 (if maybe (throw 'exit nil)
4624 (user-error "Don't know how to transform this table")))
4625 (dolist (dest dests)
4626 (let ((name (plist-get dest :name))
4627 (transform (plist-get dest :transform))
4628 (params (plist-get dest :params)))
4629 (unless (fboundp transform)
4630 (user-error "No such transformation function %s" transform))
4631 (orgtbl-send-replace-tbl name (funcall transform table params)))
4632 (incf ntbl))
4633 (message "Table converted and installed at %d receiver location%s"
4634 ntbl (if (> ntbl 1) "s" ""))
4635 (and (> ntbl 0) ntbl))))
4637 (defun org-remove-by-index (list indices &optional i0)
4638 "Remove the elements in LIST with indices in INDICES.
4639 First element has index 0, or I0 if given."
4640 (if (not indices)
4641 list
4642 (if (integerp indices) (setq indices (list indices)))
4643 (setq i0 (1- (or i0 0)))
4644 (delq :rm (mapcar (lambda (x)
4645 (setq i0 (1+ i0))
4646 (if (memq i0 indices) :rm x))
4647 list))))
4649 (defun orgtbl-toggle-comment ()
4650 "Comment or uncomment the orgtbl at point."
4651 (interactive)
4652 (let* ((case-fold-search t)
4653 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4654 (re2 (concat "^" orgtbl-line-start-regexp))
4655 (commented (save-excursion (beginning-of-line 1)
4656 (cond ((looking-at re1) t)
4657 ((looking-at re2) nil)
4658 (t (user-error "Not at an org table")))))
4659 (re (if commented re1 re2))
4660 beg end)
4661 (save-excursion
4662 (beginning-of-line 1)
4663 (while (looking-at re) (beginning-of-line 0))
4664 (beginning-of-line 2)
4665 (setq beg (point))
4666 (while (looking-at re) (beginning-of-line 2))
4667 (setq end (point)))
4668 (comment-region beg end (if commented '(4) nil))))
4670 (defun orgtbl-insert-radio-table ()
4671 "Insert a radio table template appropriate for this major mode."
4672 (interactive)
4673 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4674 (txt (nth 1 e))
4675 name pos)
4676 (unless e (user-error "No radio table setup defined for %s" major-mode))
4677 (setq name (read-string "Table name: "))
4678 (while (string-match "%n" txt)
4679 (setq txt (replace-match name t t txt)))
4680 (or (bolp) (insert "\n"))
4681 (setq pos (point))
4682 (insert txt)
4683 (goto-char pos)))
4685 ;;;###autoload
4686 (defun orgtbl-to-generic (table params)
4687 "Convert the orgtbl-mode TABLE to some other format.
4689 This generic routine can be used for many standard cases.
4691 TABLE is a list, each entry either the symbol `hline' for
4692 a horizontal separator line, or a list of fields for that
4693 line. PARAMS is a property list of parameters that can
4694 influence the conversion.
4696 Valid parameters are:
4698 :backend, :raw
4700 Export back-end used as a basis to transcode elements of the
4701 table, when no specific parameter applies to it. It is also
4702 used to translate cells contents. You can prevent this by
4703 setting :raw property to a non-nil value.
4705 :splice
4707 When non-nil, only convert rows, not the table itself. This is
4708 equivalent to setting to the empty string both :tstart
4709 and :tend, which see.
4711 :skip
4713 When set to an integer N, skip the first N lines of the table.
4714 Horizontal separation lines do count for this parameter!
4716 :skipcols
4718 List of columns that should be skipped. If the table has
4719 a column with calculation marks, that column is automatically
4720 discarded beforehand.
4722 :hline
4724 String to be inserted on horizontal separation lines. May be
4725 nil to ignore these lines altogether.
4727 :sep
4729 Separator between two fields, as a string.
4731 Each in the following group may be either a string or a function
4732 of no arguments returning a string:
4734 :tstart, :tend
4736 Strings to start and end the table. Ignored when :splice is t.
4738 :lstart, :lend
4740 Strings to start and end a new table line.
4742 :llstart, :llend
4744 Strings to start and end the last table line. Default,
4745 respectively, to :lstart and :lend.
4747 Each in the following group may be a string or a function of one
4748 argument (either the cells in the current row, as a list of
4749 strings, or the current cell) returning a string:
4751 :lfmt
4753 Format string for an entire row, with enough %s to capture all
4754 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4756 :llfmt
4758 Format for the entire last line, defaults to :lfmt.
4760 :fmt
4762 A format to be used to wrap the field, should contain %s for
4763 the original field value. For example, to wrap everything in
4764 dollars, you could use :fmt \"$%s$\". This may also be
4765 a property list with column numbers and format strings, or
4766 functions, e.g.,
4768 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4770 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4772 Same as above, specific for the header lines in the table.
4773 All lines before the first hline are treated as header. If
4774 any of these is not present, the data line value is used.
4776 This may be either a string or a function of two arguments:
4778 :efmt
4780 Use this format to print numbers with exponential. The format
4781 should have %s twice for inserting mantissa and exponent, for
4782 example \"%s\\\\times10^{%s}\". This may also be a property
4783 list with column numbers and format strings or functions.
4784 :fmt will still be applied after :efmt."
4785 (let* ((backend (plist-get params :backend))
4786 (custom-backend
4787 ;; Build a custom back-end according to PARAMS. Before
4788 ;; defining a translator, check if there is anything to do.
4789 ;; When there isn't, let BACKEND handle the element.
4790 (org-export-create-backend
4791 :parent (or backend 'org)
4792 :transcoders
4793 `((table . ,(org-table--to-generic-table params))
4794 (table-row . ,(org-table--to-generic-row params))
4795 (table-cell . ,(org-table--to-generic-cell params))
4796 ;; Macros are not going to be expanded. However, no
4797 ;; regular back-end has a transcoder for them. We
4798 ;; provide one so they are not ignored, but displayed
4799 ;; as-is instead.
4800 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4801 data info)
4802 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4803 ;; Initialize communication channel in INFO.
4804 (with-temp-buffer
4805 (let ((org-inhibit-startup t)) (org-mode))
4806 (let ((standard-output (current-buffer)))
4807 (dolist (e table)
4808 (cond ((eq e 'hline) (princ "|--\n"))
4809 ((consp e)
4810 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4811 (princ "\n")))))
4812 (setq data
4813 (org-element-map (org-element-parse-buffer) 'table
4814 #'identity nil t))
4815 (setq info (org-export-get-environment backend nil params)))
4816 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4817 (user-error "Unknown :backend value"))
4818 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4819 ;; Handle :skip parameter.
4820 (let ((skip (plist-get info :skip)))
4821 (when skip
4822 (unless (wholenump skip) (user-error "Wrong :skip value"))
4823 (let ((n 0))
4824 (org-element-map data 'table-row
4825 (lambda (row)
4826 (if (>= n skip) t
4827 (org-element-extract-element row)
4828 (incf n)
4829 nil))
4830 nil t))))
4831 ;; Handle :skipcols parameter.
4832 (let ((skipcols (plist-get info :skipcols)))
4833 (when skipcols
4834 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4835 (org-element-map data 'table
4836 (lambda (table)
4837 (let ((specialp (org-export-table-has-special-column-p table)))
4838 (dolist (row (org-element-contents table))
4839 (when (eq (org-element-property :type row) 'standard)
4840 (let ((c 1))
4841 (dolist (cell (nthcdr (if specialp 1 0)
4842 (org-element-contents row)))
4843 (when (memq c skipcols)
4844 (org-element-extract-element cell))
4845 (incf c))))))))))
4846 ;; Since we are going to export using a low-level mechanism,
4847 ;; ignore special column and special rows manually.
4848 (let ((special? (org-export-table-has-special-column-p data))
4849 ignore)
4850 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4851 (lambda (datum)
4852 (when (if (eq (org-element-type datum) 'table-row)
4853 (org-export-table-row-is-special-p datum nil)
4854 (org-export-first-sibling-p datum nil))
4855 (push datum ignore))))
4856 (setq info (plist-put info :ignore-list ignore)))
4857 ;; We use a low-level mechanism to export DATA so as to skip all
4858 ;; usual pre-processing and post-processing, i.e., hooks, filters,
4859 ;; Babel code evaluation, include keywords and macro expansion,
4860 ;; and filters.
4861 (let ((output (org-export-data-with-backend data custom-backend info)))
4862 ;; Remove final newline.
4863 (if (org-string-nw-p output) (substring output 0 -1) ""))))
4865 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4866 (cond ((null value) nil)
4867 ((functionp value) `(funcall ',value ,@args))
4868 ((stringp value)
4869 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4870 (args `(format ,value ,@args))
4871 (t value)))
4872 ((and with-cons (consp value))
4873 `(let ((val (cadr (memq column ',value))))
4874 (cond ((null val) contents)
4875 ((stringp val) (format val ,@args))
4876 ((functionp val) (funcall val ,@args))
4877 (t (user-error "Wrong %s value" ,name)))))
4878 (t (user-error "Wrong %s value" name))))
4880 (defun org-table--to-generic-table (params)
4881 "Return custom table transcoder according to PARAMS.
4882 PARAMS is a plist. See `orgtbl-to-generic' for more
4883 information."
4884 (let ((backend (plist-get params :backend))
4885 (splice (plist-get params :splice))
4886 (tstart (plist-get params :tstart))
4887 (tend (plist-get params :tend)))
4888 `(lambda (table contents info)
4889 (concat
4890 ,(and tstart (not splice)
4891 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4892 ,(if (or (not backend) tstart tend splice) 'contents
4893 `(org-export-with-backend ',backend table contents info))
4894 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4896 (defun org-table--to-generic-row (params)
4897 "Return custom table row transcoder according to PARAMS.
4898 PARAMS is a plist. See `orgtbl-to-generic' for more
4899 information."
4900 (let* ((backend (plist-get params :backend))
4901 (lstart (plist-get params :lstart))
4902 (llstart (plist-get params :llstart))
4903 (hlstart (plist-get params :hlstart))
4904 (hllstart (plist-get params :hllstart))
4905 (lend (plist-get params :lend))
4906 (llend (plist-get params :llend))
4907 (hlend (plist-get params :hlend))
4908 (hllend (plist-get params :hllend))
4909 (lfmt (plist-get params :lfmt))
4910 (llfmt (plist-get params :llfmt))
4911 (hlfmt (plist-get params :hlfmt))
4912 (hllfmt (plist-get params :hllfmt)))
4913 `(lambda (row contents info)
4914 (if (eq (org-element-property :type row) 'rule)
4915 ,(cond
4916 ((plist-member params :hline)
4917 (org-table--generic-apply (plist-get params :hline) ":hline"))
4918 (backend `(org-export-with-backend ',backend row nil info)))
4919 (let ((headerp (org-export-table-row-in-header-p row info))
4920 (lastp (not (org-export-get-next-element row info)))
4921 (last-header-p (org-export-table-row-ends-header-p row info)))
4922 (when contents
4923 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4924 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4925 ;; `:lstart', `:lend' and their relatives.
4926 ,(let ((cells
4927 '(org-element-map row 'table-cell
4928 (lambda (cell)
4929 ;; Export all cells, without separators.
4931 ;; Use `org-export-data-with-backend'
4932 ;; instead of `org-export-data' to eschew
4933 ;; cached values, which
4934 ;; ignore :orgtbl-ignore-sep parameter.
4935 (org-export-data-with-backend
4936 cell
4937 (plist-get info :back-end)
4938 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4939 info)))
4940 `(cond
4941 ,(and hllfmt
4942 `(last-header-p ,(org-table--generic-apply
4943 hllfmt ":hllfmt" nil cells)))
4944 ,(and hlfmt
4945 `(headerp ,(org-table--generic-apply
4946 hlfmt ":hlfmt" nil cells)))
4947 ,(and llfmt
4948 `(lastp ,(org-table--generic-apply
4949 llfmt ":llfmt" nil cells)))
4951 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4952 `(concat
4953 (cond
4954 ,(and
4955 (or hllstart hllend)
4956 `(last-header-p
4957 (concat
4958 ,(org-table--generic-apply hllstart ":hllstart")
4959 contents
4960 ,(org-table--generic-apply hllend ":hllend"))))
4961 ,(and
4962 (or hlstart hlend)
4963 `(headerp
4964 (concat
4965 ,(org-table--generic-apply hlstart ":hlstart")
4966 contents
4967 ,(org-table--generic-apply hlend ":hlend"))))
4968 ,(and
4969 (or llstart llend)
4970 `(lastp
4971 (concat
4972 ,(org-table--generic-apply llstart ":llstart")
4973 contents
4974 ,(org-table--generic-apply llend ":llend"))))
4976 ,(cond
4977 ((or lstart lend)
4978 `(concat
4979 ,(org-table--generic-apply lstart ":lstart")
4980 contents
4981 ,(org-table--generic-apply lend ":lend")))
4982 (backend
4983 `(org-export-with-backend
4984 ',backend row contents info))
4985 (t 'contents)))))))))))))))
4987 (defun org-table--to-generic-cell (params)
4988 "Return custom table cell transcoder according to PARAMS.
4989 PARAMS is a plist. See `orgtbl-to-generic' for more
4990 information."
4991 (let* ((backend (plist-get params :backend))
4992 (efmt (plist-get params :efmt))
4993 (fmt (plist-get params :fmt))
4994 (hfmt (plist-get params :hfmt))
4995 (sep (plist-get params :sep))
4996 (hsep (plist-get params :hsep)))
4997 `(lambda (cell contents info)
4998 (let ((headerp (org-export-table-row-in-header-p
4999 (org-export-get-parent-element cell) info))
5000 (column (1+ (cdr (org-export-table-cell-address cell info)))))
5001 ;; Make sure that contents are exported as Org data when :raw
5002 ;; parameter is non-nil.
5003 ,(when (and backend (plist-get params :raw))
5004 `(setq contents
5005 ;; Since we don't know what are the pseudo object
5006 ;; types defined in backend, we cannot pass them to
5007 ;; `org-element-interpret-data'. As a consequence,
5008 ;; they will be treated as pseudo elements, and
5009 ;; will have newlines appended instead of spaces.
5010 ;; Therefore, we must make sure :post-blank value
5011 ;; is really turned into spaces.
5012 (replace-regexp-in-string
5013 "\n" " "
5014 (org-trim
5015 (org-element-interpret-data
5016 (org-element-contents cell))))))
5017 (when contents
5018 ;; Check if we can apply `:efmt' on CONTENTS.
5019 ,(when efmt
5020 `(when (string-match orgtbl-exp-regexp contents)
5021 (let ((mantissa (match-string 1 contents))
5022 (exponent (match-string 2 contents)))
5023 (setq contents ,(org-table--generic-apply
5024 efmt ":efmt" t 'mantissa 'exponent)))))
5025 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5026 (cond
5027 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5028 hfmt ":hfmt" t 'contents))))
5029 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5030 fmt ":fmt" t 'contents))))))
5031 ;; If a separator is provided, use it instead of BACKEND's.
5032 ;; Separators are ignored when LFMT (or equivalent) is
5033 ;; provided.
5034 ,(cond
5035 ((or hsep sep)
5036 `(if (or ,(and (not sep) '(not headerp))
5037 (plist-get info :orgtbl-ignore-sep)
5038 (not (org-export-get-next-element cell info)))
5039 ,(if (not backend) 'contents
5040 `(org-export-with-backend ',backend cell contents info))
5041 (concat contents
5042 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5043 (or hsep sep)))))
5044 (backend `(org-export-with-backend ',backend cell contents info))
5045 (t 'contents))))))
5047 ;;;###autoload
5048 (defun orgtbl-to-tsv (table params)
5049 "Convert the orgtbl-mode table to TAB separated material."
5050 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5052 ;;;###autoload
5053 (defun orgtbl-to-csv (table params)
5054 "Convert the orgtbl-mode table to CSV material.
5055 This does take care of the proper quoting of fields with comma or quotes."
5056 (orgtbl-to-generic table
5057 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5058 params)))
5060 ;;;###autoload
5061 (defun orgtbl-to-latex (table params)
5062 "Convert the orgtbl-mode TABLE to LaTeX.
5064 TABLE is a list, each entry either the symbol `hline' for
5065 a horizontal separator line, or a list of fields for that line.
5066 PARAMS is a property list of parameters that can influence the
5067 conversion. All parameters from `orgtbl-to-generic' are
5068 supported. It is also possible to use the following ones:
5070 :booktabs
5072 When non-nil, use formal \"booktabs\" style.
5074 :environment
5076 Specify environment to use, as a string. If you use
5077 \"longtable\", you may also want to specify :language property,
5078 as a string, to get proper continuation strings."
5079 (require 'ox-latex)
5080 (orgtbl-to-generic
5081 table
5082 (org-combine-plists
5083 ;; Provide sane default values.
5084 (list :backend 'latex
5085 :latex-default-table-mode 'table
5086 :latex-tables-centered nil
5087 :latex-tables-booktabs (plist-get params :booktabs)
5088 :latex-table-scientific-notation nil
5089 :latex-default-table-environment
5090 (or (plist-get params :environment) "tabular"))
5091 params)))
5093 ;;;###autoload
5094 (defun orgtbl-to-html (table params)
5095 "Convert the orgtbl-mode TABLE to HTML.
5097 TABLE is a list, each entry either the symbol `hline' for
5098 a horizontal separator line, or a list of fields for that line.
5099 PARAMS is a property list of parameters that can influence the
5100 conversion. All parameters from `orgtbl-to-generic' are
5101 supported. It is also possible to use the following one:
5103 :attributes
5105 Attributes and values, as a plist, which will be used in
5106 <table> tag."
5107 (require 'ox-html)
5108 (orgtbl-to-generic
5109 table
5110 (org-combine-plists
5111 ;; Provide sane default values.
5112 (list :backend 'html
5113 :html-table-data-tags '("<td%s>" . "</td>")
5114 :html-table-use-header-tags-for-first-column nil
5115 :html-table-align-individual-fields t
5116 :html-table-row-tags '("<tr>" . "</tr>")
5117 :html-table-attributes
5118 (if (plist-member params :attributes)
5119 (plist-get params :attributes)
5120 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5121 :frame "hsides")))
5122 params)))
5124 ;;;###autoload
5125 (defun orgtbl-to-texinfo (table params)
5126 "Convert the orgtbl-mode TABLE to Texinfo.
5128 TABLE is a list, each entry either the symbol `hline' for
5129 a horizontal separator line, or a list of fields for that line.
5130 PARAMS is a property list of parameters that can influence the
5131 conversion. All parameters from `orgtbl-to-generic' are
5132 supported. It is also possible to use the following one:
5134 :columns
5136 Column widths, as a string. When providing column fractions,
5137 \"@columnfractions\" command can be omitted."
5138 (require 'ox-texinfo)
5139 (let ((output
5140 (orgtbl-to-generic
5141 table
5142 (org-combine-plists
5143 (list :backend 'texinfo
5144 :texinfo-tables-verbatim nil
5145 :texinfo-table-scientific-notation nil)
5146 params)))
5147 (columns (let ((w (plist-get params :columns)))
5148 (cond ((not w) nil)
5149 ((org-string-match-p "{\\|@columnfractions " w) w)
5150 (t (concat "@columnfractions " w))))))
5151 (if (not columns) output
5152 (replace-regexp-in-string
5153 "@multitable \\(.*\\)" columns output t nil 1))))
5155 ;;;###autoload
5156 (defun orgtbl-to-orgtbl (table params)
5157 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5159 TABLE is a list, each entry either the symbol `hline' for
5160 a horizontal separator line, or a list of fields for that line.
5161 PARAMS is a property list of parameters that can influence the
5162 conversion. All parameters from `orgtbl-to-generic' are
5163 supported.
5165 Useful when slicing one table into many. The :hline, :sep,
5166 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5167 be set to provide ORGTBL directives for the generated table."
5168 (require 'ox-org)
5169 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5171 (defun orgtbl-to-table.el (table params)
5172 "Convert the orgtbl-mode TABLE into a table.el table.
5173 TABLE is a list, each entry either the symbol `hline' for
5174 a horizontal separator line, or a list of fields for that line.
5175 PARAMS is a property list of parameters that can influence the
5176 conversion. All parameters from `orgtbl-to-generic' are
5177 supported."
5178 (with-temp-buffer
5179 (insert (orgtbl-to-orgtbl table params))
5180 (org-table-align)
5181 (replace-regexp-in-string
5182 "-|" "-+"
5183 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5185 (defun orgtbl-to-unicode (table params)
5186 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5188 TABLE is a list, each entry either the symbol `hline' for
5189 a horizontal separator line, or a list of fields for that line.
5190 PARAMS is a property list of parameters that can influence the
5191 conversion. All parameters from `orgtbl-to-generic' are
5192 supported. It is also possible to use the following ones:
5194 :ascii-art
5196 When non-nil, use \"ascii-art-to-unicode\" package to translate
5197 the table. You can download it here:
5198 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5200 :narrow
5202 When non-nil, narrow columns width than provided width cookie,
5203 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5204 (require 'ox-ascii)
5205 (orgtbl-to-generic
5206 table
5207 (org-combine-plists
5208 (list :backend 'ascii
5209 :ascii-charset 'utf-8
5210 :ascii-table-widen-columns (not (plist-get params :narrow))
5211 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5212 params)))
5214 ;; Put the cursor in a column containing numerical values
5215 ;; of an Org-Mode table,
5216 ;; type C-c " a
5217 ;; A new column is added with a bar plot.
5218 ;; When the table is refreshed (C-u C-c *),
5219 ;; the plot is updated to reflect the new values.
5221 (defun orgtbl-ascii-draw (value min max &optional width characters)
5222 "Draw an ascii bar in a table.
5223 VALUE is a the value to plot, the width of the bar to draw. A
5224 value equal to MIN will be displayed as empty (zero width bar).
5225 A value equal to MAX will draw a bar filling all the WIDTH.
5226 WIDTH is the expected width in characters of the column.
5227 CHARACTERS is a string that will compose the bar, with shades of
5228 grey from pure white to pure black. It defaults to a 10
5229 characters string of regular ascii characters."
5230 (let* ((characters (or characters " .:;c!lhVHW"))
5231 (width (or width 12))
5232 (value (if (numberp value) value (string-to-number value)))
5233 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5234 (cond
5235 ((< value 0) "too small")
5236 ((> value width) "too large")
5238 (let ((len (1- (length characters))))
5239 (concat
5240 (make-string (floor value) (elt characters len))
5241 (string (elt characters
5242 (floor (* (- value (floor value)) len))))))))))
5244 ;;;###autoload
5245 (defun orgtbl-ascii-plot (&optional ask)
5246 "Draw an ascii bar plot in a column.
5247 With cursor in a column containing numerical values, this
5248 function will draw a plot in a new column.
5249 ASK, if given, is a numeric prefix to override the default 12
5250 characters width of the plot. ASK may also be the
5251 \\[universal-argument] prefix, which will prompt for the width."
5252 (interactive "P")
5253 (let ((col (org-table-current-column))
5254 (min 1e999) ; 1e999 will be converted to infinity
5255 (max -1e999) ; which is the desired result
5256 (table (org-table-to-lisp))
5257 (length
5258 (cond ((consp ask)
5259 (read-number "Length of column " 12))
5260 ((numberp ask) ask)
5261 (t 12))))
5262 ;; Skip any hline a the top of table.
5263 (while (eq (car table) 'hline) (setq table (cdr table)))
5264 ;; Skip table header if any.
5265 (dolist (x (or (cdr (memq 'hline table)) table))
5266 (when (consp x)
5267 (setq x (nth (1- col) x))
5268 (when (string-match
5269 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5271 (setq x (string-to-number x))
5272 (when (> min x) (setq min x))
5273 (when (< max x) (setq max x)))))
5274 (org-table-insert-column)
5275 (org-table-move-column-right)
5276 (org-table-store-formulas
5277 (cons
5278 (cons
5279 (number-to-string (1+ col))
5280 (format "'(%s $%s %s %s %s)"
5281 "orgtbl-ascii-draw" col min max length))
5282 (org-table-get-stored-formulas)))
5283 (org-table-recalculate t)))
5285 ;; Example of extension: unicode characters
5286 ;; Here are two examples of different styles.
5288 ;; Unicode block characters are used to give a smooth effect.
5289 ;; See http://en.wikipedia.org/wiki/Block_Elements
5290 ;; Use one of those drawing functions
5291 ;; - orgtbl-ascii-draw (the default ascii)
5292 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5293 ;; - orgtbl-uc-draw-cont (smooth unicode)
5295 ;; This is best viewed with the "DejaVu Sans Mono" font
5296 ;; (use M-x set-default-font).
5298 (defun orgtbl-uc-draw-grid (value min max &optional width)
5299 "Draw a bar in a table using block unicode characters.
5300 It is a variant of orgtbl-ascii-draw with Unicode block
5301 characters, for a smooth display. Bars appear as grids (to the
5302 extent the font allows)."
5303 ;; http://en.wikipedia.org/wiki/Block_Elements
5304 ;; best viewed with the "DejaVu Sans Mono" font.
5305 (orgtbl-ascii-draw value min max width
5306 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5308 (defun orgtbl-uc-draw-cont (value min max &optional width)
5309 "Draw a bar in a table using block unicode characters.
5310 It is a variant of orgtbl-ascii-draw with Unicode block
5311 characters, for a smooth display. Bars are solid (to the extent
5312 the font allows)."
5313 (orgtbl-ascii-draw value min max width
5314 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5316 (defun org-table-get-remote-range (name-or-id form)
5317 "Get a field value or a list of values in a range from table at ID.
5319 NAME-OR-ID may be the name of a table in the current file as set
5320 by a \"#+NAME:\" directive. The first table following this line
5321 will then be used. Alternatively, it may be an ID referring to
5322 any entry, also in a different file. In this case, the first
5323 table in that entry will be referenced.
5324 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5325 \"@I$2..@II$2\". All the references must be absolute, not relative.
5327 The return value is either a single string for a single field, or a
5328 list of the fields in the rectangle."
5329 (save-match-data
5330 (let ((case-fold-search t) (id-loc nil)
5331 ;; Protect a bunch of variables from being overwritten by
5332 ;; the context of the remote table.
5333 org-table-column-names org-table-column-name-regexp
5334 org-table-local-parameters org-table-named-field-locations
5335 org-table-current-line-types
5336 org-table-current-begin-pos org-table-dlines
5337 org-table-current-ncol
5338 org-table-hlines org-table-last-alignment
5339 org-table-last-column-widths org-table-last-alignment
5340 org-table-last-column-widths
5341 buffer loc)
5342 (setq form (org-table-convert-refs-to-rc form))
5343 (org-with-wide-buffer
5344 (goto-char (point-min))
5345 (if (re-search-forward
5346 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5347 (regexp-quote name-or-id) "[ \t]*$")
5348 nil t)
5349 (setq buffer (current-buffer) loc (match-beginning 0))
5350 (setq id-loc (org-id-find name-or-id 'marker))
5351 (unless (and id-loc (markerp id-loc))
5352 (user-error "Can't find remote table \"%s\"" name-or-id))
5353 (setq buffer (marker-buffer id-loc)
5354 loc (marker-position id-loc))
5355 (move-marker id-loc nil))
5356 (with-current-buffer buffer
5357 (org-with-wide-buffer
5358 (goto-char loc)
5359 (forward-char 1)
5360 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5361 (not (match-beginning 1)))
5362 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5363 (org-table-analyze)
5364 (setq form (org-table-formula-substitute-names
5365 (org-table-formula-handle-first/last-rc form)))
5366 (if (and (string-match org-table-range-regexp form)
5367 (> (length (match-string 0 form)) 1))
5368 (org-table-get-range
5369 (match-string 0 form) org-table-current-begin-pos 1)
5370 form)))))))
5372 (defun org-table-remote-reference-indirection (form)
5373 "Return formula with table remote references substituted by indirection.
5374 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5375 This indirection works only with the format @ROW$COLUMN. The
5376 format \"B3\" is not supported because it can not be
5377 distinguished from a plain table name or ID."
5378 (let ((start 0))
5379 (while (string-match (concat
5380 ;; Same as in `org-table-eval-formula'.
5381 "\\<remote([ \t]*\\("
5382 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5383 "[@$][^ \t,]+"
5384 ;; Same as in `org-table-eval-formula'.
5385 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5386 form
5387 start)
5388 ;; The position of the character as far as possible to the right
5389 ;; that will not be replaced and particularly not be shifted by
5390 ;; `replace-match'.
5391 (setq start (match-beginning 1))
5392 ;; Substitute the remote reference with the value found in the
5393 ;; field.
5394 (setq form
5395 (replace-match
5396 (save-match-data
5397 (org-table-get-range (org-table-formula-handle-first/last-rc
5398 (match-string 1 form))))
5399 t t form 1))))
5400 form)
5402 (defmacro org-define-lookup-function (mode)
5403 (let ((mode-str (symbol-name mode))
5404 (first-p (equal mode 'first))
5405 (all-p (equal mode 'all)))
5406 (let ((plural-str (if all-p "s" "")))
5407 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5408 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5409 If R-LIST is nil, return matching element%s of S-LIST.
5410 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5411 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5412 This function is generated by a call to the macro `org-define-lookup-function'."
5413 mode-str plural-str plural-str plural-str)
5414 (let ,(let ((lvars '((p (or predicate 'equal))
5415 (sl s-list)
5416 (rl (or r-list s-list))
5417 (ret nil))))
5418 (if first-p (add-to-list 'lvars '(match-p nil)))
5419 lvars)
5420 (while ,(if first-p '(and (not match-p) sl) 'sl)
5421 (progn
5422 (if (funcall p val (car sl))
5423 (progn
5424 ,(if first-p '(setq match-p t))
5425 (let ((rval (car rl)))
5426 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5427 (setq sl (cdr sl) rl (cdr rl))))
5428 ret)))))
5430 (org-define-lookup-function first)
5431 (org-define-lookup-function last)
5432 (org-define-lookup-function all)
5434 (provide 'org-table)
5436 ;; Local variables:
5437 ;; generated-autoload-file: "org-loaddefs.el"
5438 ;; End:
5440 ;;; org-table.el ends here