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