Backport commit ec90220 from Emacs
[org-mode.git] / lisp / org-table.el
blobe43f0f84c2942df8e458a72515550fd625e3f52a
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-first-sibling-p "org-export" (arg1 arg2))
58 (declare-function org-export-get-backend "org-export" (arg1))
59 (declare-function org-export-get-environment "org-export" (&optional arg1 arg2 arg3))
60 (declare-function org-export-table-has-special-column-p "org-export" (arg1))
61 (declare-function org-export-table-row-is-special-p "org-export" (arg1 arg2))
63 (declare-function calc-eval "calc" (str &optional separator &rest args))
65 (defvar orgtbl-mode) ; defined below
66 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
67 (defvar constants-unit-system)
68 (defvar org-table-follow-field-mode)
70 (defvar orgtbl-after-send-table-hook nil
71 "Hook for functions attaching to `C-c C-c', if the table is sent.
72 This can be used to add additional functionality after the table is sent
73 to the receiver position, otherwise, if table is not sent, the functions
74 are not run.")
76 (defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
78 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
79 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
80 In the optimized version, the table editor takes over all simple keys that
81 normally just insert a character. In tables, the characters are inserted
82 in a way to minimize disturbing the table structure (i.e. in overwrite mode
83 for empty fields). Outside tables, the correct binding of the keys is
84 restored.
86 The default for this option is t if the optimized version is also used in
87 Org-mode. See the variable `org-enable-table-editor' for details. Changing
88 this variable requires a restart of Emacs to become effective."
89 :group 'org-table
90 :type 'boolean)
92 (defcustom orgtbl-radio-table-templates
93 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
94 % END RECEIVE ORGTBL %n
95 \\begin{comment}
96 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
97 | | |
98 \\end{comment}\n")
99 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
100 @c END RECEIVE ORGTBL %n
101 @ignore
102 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
103 | | |
104 @end ignore\n")
105 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
106 <!-- END RECEIVE ORGTBL %n -->
107 <!--
108 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
109 | | |
110 -->\n")
111 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
112 #+ END RECEIVE ORGTBL %n
114 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
115 | | |
117 "Templates for radio tables in different major modes.
118 Each template must define lines that will be treated as a comment and that
119 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
120 lines where \"%n\" will be replaced with the name of the table during
121 insertion of the template. The transformed table will later be inserted
122 between these lines.
124 The template should also contain a minimal table in a multiline comment.
125 If multiline comments are not possible in the buffer language,
126 you can pack it into a string that will not be used when the code
127 is compiled or executed. Above the table will you need a line with
128 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
129 convert the table into a data structure useful in the
130 language of the buffer. Check the manual for the section on
131 \"Translator functions\", and more generally check out
132 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
134 All occurrences of %n in a template will be replaced with the name of the
135 table, obtained by prompting the user."
136 :group 'org-table
137 :type '(repeat
138 (list (symbol :tag "Major mode")
139 (string :tag "Format"))))
141 (defgroup org-table-settings nil
142 "Settings for tables in Org-mode."
143 :tag "Org Table Settings"
144 :group 'org-table)
146 (defcustom org-table-default-size "5x2"
147 "The default size for newly created tables, Columns x Rows."
148 :group 'org-table-settings
149 :type 'string)
151 (defcustom org-table-number-regexp
152 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
153 "Regular expression for recognizing numbers in table columns.
154 If a table column contains mostly numbers, it will be aligned to the
155 right. If not, it will be aligned to the left.
157 The default value of this option is a regular expression which allows
158 anything which looks remotely like a number as used in scientific
159 context. For example, all of the following will be considered a
160 number:
161 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
163 Other options offered by the customize interface are more restrictive."
164 :group 'org-table-settings
165 :type '(choice
166 (const :tag "Positive Integers"
167 "^[0-9]+$")
168 (const :tag "Integers"
169 "^[-+]?[0-9]+$")
170 (const :tag "Floating Point Numbers"
171 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
172 (const :tag "Floating Point Number or Integer"
173 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
174 (const :tag "Exponential, Floating point, Integer"
175 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
176 (const :tag "Very General Number-Like, including hex and Calc radix"
177 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
178 (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
179 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
180 (string :tag "Regexp:")))
182 (defcustom org-table-number-fraction 0.5
183 "Fraction of numbers in a column required to make the column align right.
184 In a column all non-white fields are considered. If at least
185 this fraction of fields is matched by `org-table-number-regexp',
186 alignment to the right border applies."
187 :group 'org-table-settings
188 :type 'number)
190 (defgroup org-table-editing nil
191 "Behavior of tables during editing in Org-mode."
192 :tag "Org Table Editing"
193 :group 'org-table)
195 (defcustom org-table-automatic-realign t
196 "Non-nil means automatically re-align table when pressing TAB or RETURN.
197 When nil, aligning is only done with \\[org-table-align], or after column
198 removal/insertion."
199 :group 'org-table-editing
200 :type 'boolean)
202 (defcustom org-table-auto-blank-field t
203 "Non-nil means automatically blank table field when starting to type into it.
204 This only happens when typing immediately after a field motion
205 command (TAB, S-TAB or RET).
206 Only relevant when `org-enable-table-editor' is equal to `optimized'."
207 :group 'org-table-editing
208 :type 'boolean)
210 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
211 "Non-nil means automatically exit the follow mode.
212 When nil, the follow mode will stay on and be active in any table
213 the cursor enters. Since the table follow filed mode messes with the
214 window configuration, it is not recommended to set this variable to nil,
215 except maybe locally in a special file that has mostly tables with long
216 fields."
217 :group 'org-table
218 :version "24.1"
219 :type 'boolean)
221 (defcustom org-table-fix-formulas-confirm nil
222 "Whether the user should confirm when Org fixes formulas."
223 :group 'org-table-editing
224 :version "24.1"
225 :type '(choice
226 (const :tag "with yes-or-no" yes-or-no-p)
227 (const :tag "with y-or-n" y-or-n-p)
228 (const :tag "no confirmation" nil)))
229 (put 'org-table-fix-formulas-confirm
230 'safe-local-variable
231 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
233 (defcustom org-table-tab-jumps-over-hlines t
234 "Non-nil means tab in the last column of a table with jump over a hline.
235 If a horizontal separator line is following the current line,
236 `org-table-next-field' can either create a new row before that line, or jump
237 over the line. When this option is nil, a new line will be created before
238 this line."
239 :group 'org-table-editing
240 :type 'boolean)
242 (defgroup org-table-calculation nil
243 "Options concerning tables in Org-mode."
244 :tag "Org Table Calculation"
245 :group 'org-table)
247 (defcustom org-table-use-standard-references 'from
248 "Should org-mode work with table references like B3 instead of @3$2?
249 Possible values are:
250 nil never use them
251 from accept as input, do not present for editing
252 t accept as input and present for editing"
253 :group 'org-table-calculation
254 :type '(choice
255 (const :tag "Never, don't even check user input for them" nil)
256 (const :tag "Always, both as user input, and when editing" t)
257 (const :tag "Convert user input, don't offer during editing" from)))
259 (defcustom org-table-copy-increment t
260 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
261 :group 'org-table-calculation
262 :version "25.1"
263 :package-version '(Org . "8.3")
264 :type '(choice
265 (const :tag "Use the difference between the current and the above fields" t)
266 (integer :tag "Use a number" 1)
267 (const :tag "Don't increment the value when copying a field" nil)))
269 (defcustom org-calc-default-modes
270 '(calc-internal-prec 12
271 calc-float-format (float 8)
272 calc-angle-mode deg
273 calc-prefer-frac nil
274 calc-symbolic-mode nil
275 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
276 calc-display-working-message t
278 "List with Calc mode settings for use in `calc-eval' for table formulas.
279 The list must contain alternating symbols (Calc modes variables and values).
280 Don't remove any of the default settings, just change the values. Org-mode
281 relies on the variables to be present in the list."
282 :group 'org-table-calculation
283 :type 'plist)
285 (defcustom org-table-duration-custom-format 'hours
286 "Format for the output of calc computations like $1+$2;t.
287 The default value is `hours', and will output the results as a
288 number of hours. Other allowed values are `seconds', `minutes' and
289 `days', and the output will be a fraction of seconds, minutes or
290 days."
291 :group 'org-table-calculation
292 :version "24.1"
293 :type '(choice (symbol :tag "Seconds" 'seconds)
294 (symbol :tag "Minutes" 'minutes)
295 (symbol :tag "Hours " 'hours)
296 (symbol :tag "Days " 'days)))
298 (defcustom org-table-formula-field-format "%s"
299 "Format for fields which contain the result of a formula.
300 For example, using \"~%s~\" will display the result within tilde
301 characters. Beware that modifying the display can prevent the
302 field from being used in another formula."
303 :group 'org-table-settings
304 :version "24.1"
305 :type 'string)
307 (defcustom org-table-formula-evaluate-inline t
308 "Non-nil means TAB and RET evaluate a formula in current table field.
309 If the current field starts with an equal sign, it is assumed to be a formula
310 which should be evaluated as described in the manual and in the documentation
311 string of the command `org-table-eval-formula'. This feature requires the
312 Emacs calc package.
313 When this variable is nil, formula calculation is only available through
314 the command \\[org-table-eval-formula]."
315 :group 'org-table-calculation
316 :type 'boolean)
318 (defcustom org-table-formula-use-constants t
319 "Non-nil means interpret constants in formulas in tables.
320 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
321 by the value given in `org-table-formula-constants', or by a value obtained
322 from the `constants.el' package."
323 :group 'org-table-calculation
324 :type 'boolean)
326 (defcustom org-table-formula-constants nil
327 "Alist with constant names and values, for use in table formulas.
328 The car of each element is a name of a constant, without the `$' before it.
329 The cdr is the value as a string. For example, if you'd like to use the
330 speed of light in a formula, you would configure
332 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
334 and then use it in an equation like `$1*$c'.
336 Constants can also be defined on a per-file basis using a line like
338 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
339 :group 'org-table-calculation
340 :type '(repeat
341 (cons (string :tag "name")
342 (string :tag "value"))))
344 (defcustom org-table-allow-automatic-line-recalculation t
345 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
346 \\<org-mode-map>\
347 Automatically means when TAB or RET or \\[org-ctrl-c-ctrl-c] \
348 are pressed in the line."
349 :group 'org-table-calculation
350 :type 'boolean)
352 (defcustom org-table-relative-ref-may-cross-hline t
353 "Non-nil means relative formula references may cross hlines.
354 Here are the allowed values:
356 nil Relative references may not cross hlines. They will reference the
357 field next to the hline instead. Coming from below, the reference
358 will be to the field below the hline. Coming from above, it will be
359 to the field above.
360 t Relative references may cross hlines.
361 error An attempt to cross a hline will throw an error.
363 It is probably good to never set this variable to nil, for the sake of
364 portability of tables."
365 :group 'org-table-calculation
366 :type '(choice
367 (const :tag "Allow to cross" t)
368 (const :tag "Stick to hline" nil)
369 (const :tag "Error on attempt to cross" error)))
371 (defcustom org-table-formula-create-columns nil
372 "Non-nil means that evaluation of a field formula can add new
373 columns if an out-of-bounds field is being set."
374 :group 'org-table-calculation
375 :version "25.1"
376 :package-version '(Org . "8.3")
377 :type '(choice
378 (const :tag "Setting an out-of-bounds field generates an error (default)" nil)
379 (const :tag "Setting an out-of-bounds field silently adds columns as needed" t)
380 (const :tag "Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn)
381 (const :tag "When setting an out-of-bounds field, the user is prompted" prompt)))
383 (defgroup org-table-import-export nil
384 "Options concerning table import and export in Org-mode."
385 :tag "Org Table Import Export"
386 :group 'org-table)
388 (defcustom org-table-export-default-format "orgtbl-to-tsv"
389 "Default export parameters for `org-table-export'.
390 These can be overridden for a specific table by setting the
391 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
392 radio tables for the different export transformations and
393 available parameters."
394 :group 'org-table-import-export
395 :type 'string)
397 (defcustom org-table-convert-region-max-lines 999
398 "Max lines that `org-table-convert-region' will attempt to process.
400 The function can be slow on larger regions; this safety feature
401 prevents it from hanging emacs."
402 :group 'org-table-import-export
403 :type 'integer
404 :version "25.1"
405 :package-version '(Org . "8.3"))
407 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
408 "Regexp matching a line marked for automatic recalculation.")
410 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
411 "Regexp matching a line marked for recalculation.")
413 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
414 "Regexp matching a line marked for calculation.")
416 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
417 "Regexp matching any line outside an Org table.")
419 (defvar org-table-last-highlighted-reference nil)
421 (defvar org-table-formula-history nil)
423 (defvar org-table-column-names nil
424 "Alist with column names, derived from the `!' line.
425 This variable is initialized with `org-table-analyze'.")
427 (defvar org-table-column-name-regexp nil
428 "Regular expression matching the current column names.
429 This variable is initialized with `org-table-analyze'.")
431 (defvar org-table-local-parameters nil
432 "Alist with parameter names, derived from the `$' line.
433 This variable is initialized with `org-table-analyze'.")
435 (defvar org-table-named-field-locations nil
436 "Alist with locations of named fields.
437 Associations follow the pattern (NAME LINE COLUMN) where
438 NAME is the name of the field as a string,
439 LINE is the number of lines from the beginning of the table,
440 COLUMN is the column of the field, as an integer.
441 This variable is initialized with `org-table-analyze'.")
443 (defvar org-table-current-line-types nil
444 "Table row types in current table.
445 This variable is initialized with `org-table-analyze'.")
447 (defvar org-table-current-begin-pos nil
448 "Current table begin position, as a marker.
449 This variable is initialized with `org-table-analyze'.")
451 (defvar org-table-current-ncol nil
452 "Number of columns in current table.
453 This variable is initialized with `org-table-analyze'.")
455 (defvar org-table-dlines nil
456 "Vector of data line line numbers in the current table.
457 Line numbers are counted from the beginning of the table. This
458 variable is initialized with `org-table-analyze'.")
460 (defvar org-table-hlines nil
461 "Vector of hline line numbers in the current table.
462 Line numbers are counted from the beginning of the table. This
463 variable is initialized with `org-table-analyze'.")
465 (defconst org-table-range-regexp
466 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
467 ;; 1 2 3 4 5
468 "Regular expression for matching ranges in formulas.")
470 (defconst org-table-range-regexp2
471 (concat
472 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
473 "\\.\\."
474 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
475 "Match a range for reference display.")
477 (defconst org-table-translate-regexp
478 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
479 "Match a reference that needs translation, for reference display.")
481 (defmacro org-table-save-field (&rest body)
482 "Save current field; execute BODY; restore field.
483 Field is restored even in case of abnormal exit."
484 (declare (debug (body)))
485 (org-with-gensyms (line column)
486 `(let ((,line (copy-marker (line-beginning-position)))
487 (,column (org-table-current-column)))
488 (unwind-protect
489 (progn ,@body)
490 (goto-char ,line)
491 (org-table-goto-column ,column)
492 (set-marker ,line nil)))))
494 ;;;###autoload
495 (defun org-table-create-with-table.el ()
496 "Use the table.el package to insert a new table.
497 If there is already a table at point, convert between Org-mode tables
498 and table.el tables."
499 (interactive)
500 (require 'table)
501 (cond
502 ((org-at-table.el-p)
503 (if (y-or-n-p "Convert table to Org-mode table? ")
504 (org-table-convert)))
505 ((org-at-table-p)
506 (when (y-or-n-p "Convert table to table.el table? ")
507 (org-table-align)
508 (org-table-convert)))
509 (t (call-interactively 'table-insert))))
511 ;;;###autoload
512 (defun org-table-create-or-convert-from-region (arg)
513 "Convert region to table, or create an empty table.
514 If there is an active region, convert it to a table, using the function
515 `org-table-convert-region'. See the documentation of that function
516 to learn how the prefix argument is interpreted to determine the field
517 separator.
518 If there is no such region, create an empty table with `org-table-create'."
519 (interactive "P")
520 (if (org-region-active-p)
521 (org-table-convert-region (region-beginning) (region-end) arg)
522 (org-table-create arg)))
524 ;;;###autoload
525 (defun org-table-create (&optional size)
526 "Query for a size and insert a table skeleton.
527 SIZE is a string Columns x Rows like for example \"3x2\"."
528 (interactive "P")
529 (unless size
530 (setq size (read-string
531 (concat "Table size Columns x Rows [e.g. "
532 org-table-default-size "]: ")
533 "" nil org-table-default-size)))
535 (let* ((pos (point))
536 (indent (make-string (current-column) ?\ ))
537 (split (org-split-string size " *x *"))
538 (rows (string-to-number (nth 1 split)))
539 (columns (string-to-number (car split)))
540 (line (concat (apply 'concat indent "|" (make-list columns " |"))
541 "\n")))
542 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
543 (point-at-bol) (point)))
544 (beginning-of-line 1)
545 (newline))
546 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
547 (dotimes (i rows) (insert line))
548 (goto-char pos)
549 (if (> rows 1)
550 ;; Insert a hline after the first row.
551 (progn
552 (end-of-line 1)
553 (insert "\n|-")
554 (goto-char pos)))
555 (org-table-align)))
557 ;;;###autoload
558 (defun org-table-convert-region (beg0 end0 &optional separator)
559 "Convert region to a table.
560 The region goes from BEG0 to END0, but these borders will be moved
561 slightly, to make sure a beginning of line in the first line is included.
563 SEPARATOR specifies the field separator in the lines. It can have the
564 following values:
566 (4) Use the comma as a field separator
567 (16) Use a TAB as field separator
568 (64) Prompt for a regular expression as field separator
569 integer When a number, use that many spaces as field separator
570 regexp When a regular expression, use it to match the separator
571 nil When nil, the command tries to be smart and figure out the
572 separator in the following way:
573 - when each line contains a TAB, assume TAB-separated material
574 - when each line contains a comma, assume CSV material
575 - else, assume one or more SPACE characters as separator."
576 (interactive "r\nP")
577 (let* ((beg (min beg0 end0))
578 (end (max beg0 end0))
580 (if (> (count-lines beg end) org-table-convert-region-max-lines)
581 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
582 org-table-convert-region-max-lines)
583 (if (equal separator '(64))
584 (setq separator (read-regexp "Regexp for field separator")))
585 (goto-char beg)
586 (beginning-of-line 1)
587 (setq beg (point-marker))
588 (goto-char end)
589 (if (bolp) (backward-char 1) (end-of-line 1))
590 (setq end (point-marker))
591 ;; Get the right field separator
592 (unless separator
593 (goto-char beg)
594 (setq separator
595 (cond
596 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
597 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
598 (t 1))))
599 (goto-char beg)
600 (if (equal separator '(4))
601 (while (< (point) end)
602 ;; parse the csv stuff
603 (cond
604 ((looking-at "^") (insert "| "))
605 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
606 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
607 (replace-match "\\1")
608 (if (looking-at "\"") (insert "\"")))
609 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
610 ((looking-at "[ \t]*,") (replace-match " | "))
611 (t (beginning-of-line 2))))
612 (setq re (cond
613 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
614 ((equal separator '(16)) "^\\|\t")
615 ((integerp separator)
616 (if (< separator 1)
617 (user-error "Number of spaces in separator must be >= 1")
618 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
619 ((stringp separator)
620 (format "^ *\\|%s" separator))
621 (t (error "This should not happen"))))
622 (while (re-search-forward re end t)
623 (replace-match "| " t t)))
624 (goto-char beg)
625 (org-table-align))))
627 ;;;###autoload
628 (defun org-table-import (file arg)
629 "Import FILE as a table.
630 The file is assumed to be tab-separated. Such files can be produced by most
631 spreadsheet and database applications. If no tabs (at least one per line)
632 are found, lines will be split on whitespace into fields."
633 (interactive "f\nP")
634 (or (bolp) (newline))
635 (let ((beg (point))
636 (pm (point-max)))
637 (insert-file-contents file)
638 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
641 ;;;###autoload
642 (defun org-table-export (&optional file format)
643 "Export table to a file, with configurable format.
644 Such a file can be imported into usual spreadsheet programs.
646 FILE can be the output file name. If not given, it will be taken
647 from a TABLE_EXPORT_FILE property in the current entry or higher
648 up in the hierarchy, or the user will be prompted for a file
649 name. FORMAT can be an export format, of the same kind as it
650 used when `orgtbl-mode' sends a table in a different format.
652 The command suggests a format depending on TABLE_EXPORT_FORMAT,
653 whether it is set locally or up in the hierarchy, then on the
654 extension of the given file name, and finally on the variable
655 `org-table-export-default-format'."
656 (interactive)
657 (unless (org-at-table-p) (user-error "No table at point"))
658 (org-table-align) ; Make sure we have everything we need.
659 (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
660 (unless file
661 (setq file (read-file-name "Export table to: "))
662 (unless (or (not (file-exists-p file))
663 (y-or-n-p (format "Overwrite file %s? " file)))
664 (user-error "File not written")))
665 (when (file-directory-p file)
666 (user-error "This is a directory path, not a file"))
667 (when (and (buffer-file-name (buffer-base-buffer))
668 (org-file-equal-p
669 (file-truename file)
670 (file-truename (buffer-file-name (buffer-base-buffer)))))
671 (user-error "Please specify a file name that is different from current"))
672 (let ((fileext (concat (file-name-extension file) "$"))
673 (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
674 (unless format
675 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
676 "orgtbl-to-html" "orgtbl-to-generic"
677 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
678 "orgtbl-to-unicode"))
679 (deffmt-readable
680 (replace-regexp-in-string
681 "\t" "\\t"
682 (replace-regexp-in-string
683 "\n" "\\n"
684 (or (car (delq nil
685 (mapcar
686 (lambda (f)
687 (and (org-string-match-p fileext f) f))
688 formats)))
689 org-table-export-default-format)
690 t t) t t)))
691 (setq format
692 (org-completing-read
693 "Format: " formats nil nil deffmt-readable))))
694 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
695 (let ((transform (intern (match-string 1 format)))
696 (params (and (match-end 2)
697 (read (concat "(" (match-string 2 format) ")"))))
698 (table (org-table-to-lisp
699 (buffer-substring-no-properties
700 (org-table-begin) (org-table-end)))))
701 (unless (fboundp transform)
702 (user-error "No such transformation function %s" transform))
703 (let (buf)
704 (with-current-buffer (find-file-noselect file)
705 (setq buf (current-buffer))
706 (erase-buffer)
707 (fundamental-mode)
708 (insert (funcall transform table params) "\n")
709 (save-buffer))
710 (kill-buffer buf))
711 (message "Export done."))
712 (user-error "TABLE_EXPORT_FORMAT invalid")))))
714 (defvar org-table-aligned-begin-marker (make-marker)
715 "Marker at the beginning of the table last aligned.
716 Used to check if cursor still is in that table, to minimize realignment.")
717 (defvar org-table-aligned-end-marker (make-marker)
718 "Marker at the end of the table last aligned.
719 Used to check if cursor still is in that table, to minimize realignment.")
720 (defvar org-table-last-alignment nil
721 "List of flags for flushright alignment, from the last re-alignment.
722 This is being used to correctly align a single field after TAB or RET.")
723 (defvar org-table-last-column-widths nil
724 "List of max width of fields in each column.
725 This is being used to correctly align a single field after TAB or RET.")
726 (defvar org-table-formula-debug nil
727 "Non-nil means debug table formulas.
728 When nil, simply write \"#ERROR\" in corrupted fields.")
729 (make-variable-buffer-local 'org-table-formula-debug)
730 (defvar org-table-overlay-coordinates nil
731 "Overlay coordinates after each align of a table.")
732 (make-variable-buffer-local 'org-table-overlay-coordinates)
734 (defvar org-last-recalc-line nil)
735 (defvar org-table-do-narrow t) ; for dynamic scoping
736 (defconst org-narrow-column-arrow "=>"
737 "Used as display property in narrowed table columns.")
739 ;;;###autoload
740 (defun org-table-align ()
741 "Align the table at point by aligning all vertical bars."
742 (interactive)
743 (let* ((beg (org-table-begin))
744 (end (copy-marker (org-table-end))))
745 (org-table-save-field
746 ;; Make sure invisible characters in the table are at the right
747 ;; place since column widths take them into account.
748 (font-lock-fontify-region beg end)
749 (move-marker org-table-aligned-begin-marker beg)
750 (move-marker org-table-aligned-end-marker end)
751 (goto-char beg)
752 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
753 ;; Table's rows. Separators are replaced by nil. Trailing
754 ;; spaces are also removed.
755 (lines (mapcar (lambda (l)
756 (and (not (org-string-match-p "\\`[ \t]*|-" l))
757 (let ((l (org-trim l)))
758 (remove-text-properties
759 0 (length l) '(display t org-cwidth t) l)
760 l)))
761 (org-split-string (buffer-substring beg end) "\n")))
762 ;; Get the data fields by splitting the lines.
763 (fields (mapcar (lambda (l) (org-split-string l " *| *"))
764 (remq nil lines)))
765 ;; Compute number of fields in the longest line. If the
766 ;; table contains no field, create a default table.
767 (maxfields (if fields (apply #'max (mapcar #'length fields))
768 (kill-region beg end)
769 (org-table-create org-table-default-size)
770 (user-error "Empty table - created default table")))
771 ;; A list of empty strings to fill any short rows on output.
772 (emptycells (make-list maxfields ""))
773 lengths typenums)
774 ;; Check for special formatting.
775 (dotimes (i maxfields)
776 (let ((column (mapcar (lambda (x) (or (nth i x) "")) fields))
777 fmax falign)
778 ;; Look for an explicit width or alignment.
779 (when (save-excursion
780 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t)
781 (and org-table-do-narrow
782 (re-search-forward
783 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t))))
784 (catch :exit
785 (dolist (cell column)
786 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell)
787 (when (match-end 1) (setq falign (match-string 1 cell)))
788 (when (and org-table-do-narrow (match-end 2))
789 (setq fmax (string-to-number (match-string 2 cell))))
790 (when (or falign fmax) (throw :exit nil)))))
791 ;; Find fields that are wider than FMAX, and shorten them.
792 (when fmax
793 (dolist (x column)
794 (when (> (org-string-width x) fmax)
795 (org-add-props x nil
796 'help-echo
797 (concat
798 (substitute-command-keys
799 "Clipped table field, use \\[org-table-edit-field] to \
800 edit. Full value is:\n")
801 (substring-no-properties x)))
802 (let ((l (length x))
803 (f1 (min fmax
804 (or (string-match org-bracket-link-regexp x)
805 fmax)))
806 (f2 1))
807 (unless (> f1 1)
808 (user-error
809 "Cannot narrow field starting with wide link \"%s\""
810 (match-string 0 x)))
811 (if (= (org-string-width x) l) (setq f2 f1)
812 (setq f2 1)
813 (while (< (org-string-width (substring x 0 f2)) f1)
814 (incf f2)))
815 (add-text-properties f2 l (list 'org-cwidth t) x)
816 (add-text-properties
817 (if (>= (string-width (substring x (1- f2) f2)) 2) (1- f2)
818 (- f2 2))
820 (list 'display org-narrow-column-arrow)
821 x))))))
822 ;; Get the maximum width for each column
823 (push (apply #'max (or fmax 1) 1 (mapcar #'org-string-width column))
824 lengths)
825 ;; Get the fraction of numbers among non-empty cells to
826 ;; decide about alignment of the column.
827 (if falign (push (equal (downcase falign) "r") typenums)
828 (let ((cnt 0)
829 (frac 0.0))
830 (dolist (x column)
831 (unless (equal x "")
832 (setq frac
833 (/ (+ (* frac cnt)
834 (if (org-string-match-p org-table-number-regexp x)
837 (incf cnt)))))
838 (push (>= frac org-table-number-fraction) typenums)))))
839 (setq lengths (nreverse lengths))
840 (setq typenums (nreverse typenums))
841 ;; Store alignment of this table, for later editing of single
842 ;; fields.
843 (setq org-table-last-alignment typenums)
844 (setq org-table-last-column-widths lengths)
845 ;; With invisible characters, `format' does not get the field
846 ;; width right So we need to make these fields wide by hand.
847 ;; Invisible characters may be introduced by fontified links,
848 ;; emphasis, macros or sub/superscripts.
849 (when (or (text-property-any beg end 'invisible 'org-link)
850 (text-property-any beg end 'invisible t))
851 (dotimes (i maxfields)
852 (let ((len (nth i lengths)))
853 (dotimes (j (length fields))
854 (let* ((c (nthcdr i (nth j fields)))
855 (cell (car c)))
856 (when (and
857 (stringp cell)
858 (let ((l (length cell)))
859 (or (text-property-any 0 l 'invisible 'org-link cell)
860 (text-property-any beg end 'invisible t)))
861 (< (org-string-width cell) len))
862 (let ((s (make-string (- len (org-string-width cell)) ?\s)))
863 (setcar c (if (nth i typenums) (concat s cell)
864 (concat cell s))))))))))
866 ;; Compute the formats needed for output of the table.
867 (let ((hfmt (concat indent "|"))
868 (rfmt (concat indent "|"))
869 (rfmt1 " %%%s%ds |")
870 (hfmt1 "-%s-+"))
871 (dolist (l lengths (setq hfmt (concat (substring hfmt 0 -1) "|")))
872 (let ((ty (if (pop typenums) "" "-"))) ; Flush numbers right.
873 (setq rfmt (concat rfmt (format rfmt1 ty l)))
874 (setq hfmt (concat hfmt (format hfmt1 (make-string l ?-))))))
875 ;; Replace modified lines only. Check not only contents, but
876 ;; also columns' width.
877 (dolist (l lines)
878 (let ((line
879 (if l (apply #'format rfmt (append (pop fields) emptycells))
880 hfmt))
881 (previous (buffer-substring (point) (line-end-position))))
882 (if (and (equal previous line)
883 (let ((a 0)
884 (b 0))
885 (while (and (progn
886 (setq a (next-single-property-change
887 a 'org-cwidth previous))
888 (setq b (next-single-property-change
889 b 'org-cwidth line)))
890 (eq a b)))
891 (eq a b)))
892 (forward-line)
893 (insert line "\n")
894 (delete-region (point) (line-beginning-position 2))))))
895 (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
896 (goto-char org-table-aligned-begin-marker)
897 (while (org-hide-wide-columns org-table-aligned-end-marker)))
898 (set-marker end nil)
899 (when org-table-overlay-coordinates (org-table-overlay-coordinates))
900 (setq org-table-may-need-update nil)))))
902 ;;;###autoload
903 (defun org-table-begin (&optional table-type)
904 "Find the beginning of the table and return its position.
905 With a non-nil optional argument TABLE-TYPE, return the beginning
906 of a table.el-type table. This function assumes point is on
907 a table."
908 (cond (table-type
909 (org-element-property :post-affiliated (org-element-at-point)))
910 ((save-excursion
911 (and (re-search-backward org-table-border-regexp nil t)
912 (line-beginning-position 2))))
913 (t (point-min))))
915 ;;;###autoload
916 (defun org-table-end (&optional table-type)
917 "Find the end of the table and return its position.
918 With a non-nil optional argument TABLE-TYPE, return the end of
919 a table.el-type table. This function assumes point is on
920 a table."
921 (save-excursion
922 (cond (table-type
923 (goto-char (org-element-property :end (org-element-at-point)))
924 (skip-chars-backward " \t\n")
925 (line-beginning-position 2))
926 ((re-search-forward org-table-border-regexp nil t)
927 (match-beginning 0))
928 ;; When the line right after the table is the last line in
929 ;; the buffer with trailing spaces but no final newline
930 ;; character, be sure to catch the correct ending at its
931 ;; beginning. In any other case, ending is expected to be
932 ;; at point max.
933 (t (goto-char (point-max))
934 (skip-chars-backward " \t")
935 (if (bolp) (point) (line-end-position))))))
937 ;;;###autoload
938 (defun org-table-justify-field-maybe (&optional new)
939 "Justify the current field, text to left, number to right.
940 Optional argument NEW may specify text to replace the current field content."
941 (cond
942 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
943 ((org-at-table-hline-p))
944 ((and (not new)
945 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
946 (current-buffer)))
947 (< (point) org-table-aligned-begin-marker)
948 (>= (point) org-table-aligned-end-marker)))
949 ;; This is not the same table, force a full re-align
950 (setq org-table-may-need-update t))
951 (t ;; realign the current field, based on previous full realign
952 (let* ((pos (point)) s
953 (col (org-table-current-column))
954 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
955 l f n o e)
956 (when (> col 0)
957 (skip-chars-backward "^|\n")
958 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
959 (progn
960 (setq s (match-string 1)
961 o (match-string 0)
962 l (max 1
963 (- (org-string-width
964 (buffer-substring-no-properties
965 (match-end 0) (match-beginning 0))) 3))
966 e (not (= (match-beginning 2) (match-end 2))))
967 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
968 l (if e "|" (setq org-table-may-need-update t) ""))
969 n (format f s))
970 (if new
971 (if (<= (org-string-width new) l)
972 (setq n (format f new))
973 (setq n (concat new "|") org-table-may-need-update t)))
974 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
975 (or (equal n o)
976 (let (org-table-may-need-update)
977 (replace-match n t t))))
978 (setq org-table-may-need-update t))
979 (goto-char pos))))))
981 ;;;###autoload
982 (defun org-table-next-field ()
983 "Go to the next field in the current table, creating new lines as needed.
984 Before doing so, re-align the table if necessary."
985 (interactive)
986 (org-table-maybe-eval-formula)
987 (org-table-maybe-recalculate-line)
988 (if (and org-table-automatic-realign
989 org-table-may-need-update)
990 (org-table-align))
991 (let ((end (org-table-end)))
992 (if (org-at-table-hline-p)
993 (end-of-line 1))
994 (condition-case nil
995 (progn
996 (re-search-forward "|" end)
997 (if (looking-at "[ \t]*$")
998 (re-search-forward "|" end))
999 (if (and (looking-at "-")
1000 org-table-tab-jumps-over-hlines
1001 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
1002 (goto-char (match-beginning 1)))
1003 (if (looking-at "-")
1004 (progn
1005 (beginning-of-line 0)
1006 (org-table-insert-row 'below))
1007 (if (looking-at " ") (forward-char 1))))
1008 (error
1009 (org-table-insert-row 'below)))))
1011 ;;;###autoload
1012 (defun org-table-previous-field ()
1013 "Go to the previous field in the table.
1014 Before doing so, re-align the table if necessary."
1015 (interactive)
1016 (org-table-justify-field-maybe)
1017 (org-table-maybe-recalculate-line)
1018 (if (and org-table-automatic-realign
1019 org-table-may-need-update)
1020 (org-table-align))
1021 (if (org-at-table-hline-p)
1022 (end-of-line 1))
1023 (condition-case nil
1024 (progn
1025 (re-search-backward "|" (org-table-begin))
1026 (re-search-backward "|" (org-table-begin)))
1027 (error (user-error "Cannot move to previous table field")))
1028 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1029 (re-search-backward "|" (org-table-begin)))
1030 (if (looking-at "| ?")
1031 (goto-char (match-end 0))))
1033 (defun org-table-beginning-of-field (&optional n)
1034 "Move to the beginning of the current table field.
1035 If already at or before the beginning, move to the beginning of the
1036 previous field.
1037 With numeric argument N, move N-1 fields backward first."
1038 (interactive "p")
1039 (let ((pos (point)))
1040 (while (> n 1)
1041 (setq n (1- n))
1042 (org-table-previous-field))
1043 (if (not (re-search-backward "|" (point-at-bol 0) t))
1044 (user-error "No more table fields before the current")
1045 (goto-char (match-end 0))
1046 (and (looking-at " ") (forward-char 1)))
1047 (if (>= (point) pos) (org-table-beginning-of-field 2))))
1049 (defun org-table-end-of-field (&optional n)
1050 "Move to the end of the current table field.
1051 If already at or after the end, move to the end of the next table field.
1052 With numeric argument N, move N-1 fields forward first."
1053 (interactive "p")
1054 (let ((pos (point)))
1055 (while (> n 1)
1056 (setq n (1- n))
1057 (org-table-next-field))
1058 (when (re-search-forward "|" (point-at-eol 1) t)
1059 (backward-char 1)
1060 (skip-chars-backward " ")
1061 (if (and (equal (char-before (point)) ?|) (looking-at " "))
1062 (forward-char 1)))
1063 (if (<= (point) pos) (org-table-end-of-field 2))))
1065 ;;;###autoload
1066 (defun org-table-next-row ()
1067 "Go to the next row (same column) in the current table.
1068 Before doing so, re-align the table if necessary."
1069 (interactive)
1070 (org-table-maybe-eval-formula)
1071 (org-table-maybe-recalculate-line)
1072 (if (or (looking-at "[ \t]*$")
1073 (save-excursion (skip-chars-backward " \t") (bolp)))
1074 (newline)
1075 (if (and org-table-automatic-realign
1076 org-table-may-need-update)
1077 (org-table-align))
1078 (let ((col (org-table-current-column)))
1079 (beginning-of-line 2)
1080 (if (or (not (org-at-table-p))
1081 (org-at-table-hline-p))
1082 (progn
1083 (beginning-of-line 0)
1084 (org-table-insert-row 'below)))
1085 (org-table-goto-column col)
1086 (skip-chars-backward "^|\n\r")
1087 (if (looking-at " ") (forward-char 1)))))
1089 ;;;###autoload
1090 (defun org-table-copy-down (n)
1091 "Copy the value of the current field one row below.
1093 If the field at the cursor is empty, copy the content of the
1094 nearest non-empty field above. With argument N, use the Nth
1095 non-empty field.
1097 If the current field is not empty, it is copied down to the next
1098 row, and the cursor is moved with it. Therefore, repeating this
1099 command causes the column to be filled row-by-row.
1101 If the variable `org-table-copy-increment' is non-nil and the
1102 field is an integer or a timestamp, it will be incremented while
1103 copying. By default, increment by the difference between the
1104 value in the current field and the one in the field above. To
1105 increment using a fixed integer, set `org-table-copy-increment'
1106 to a number. In the case of a timestamp, increment by days."
1107 (interactive "p")
1108 (let* ((colpos (org-table-current-column))
1109 (col (current-column))
1110 (field (save-excursion (org-table-get-field)))
1111 (field-up (or (save-excursion
1112 (org-table-get (1- (org-table-current-line))
1113 (org-table-current-column))) ""))
1114 (non-empty (string-match "[^ \t]" field))
1115 (non-empty-up (string-match "[^ \t]" field-up))
1116 (beg (org-table-begin))
1117 (orig-n n)
1118 txt txt-up inc)
1119 (org-table-check-inside-data-field)
1120 (if (not non-empty)
1121 (save-excursion
1122 (setq txt
1123 (catch 'exit
1124 (while (progn (beginning-of-line 1)
1125 (re-search-backward org-table-dataline-regexp
1126 beg t))
1127 (org-table-goto-column colpos t)
1128 (if (and (looking-at
1129 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1130 (<= (setq n (1- n)) 0))
1131 (throw 'exit (match-string 1))))))
1132 (setq field-up
1133 (catch 'exit
1134 (while (progn (beginning-of-line 1)
1135 (re-search-backward org-table-dataline-regexp
1136 beg t))
1137 (org-table-goto-column colpos t)
1138 (if (and (looking-at
1139 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1140 (<= (setq n (1- n)) 0))
1141 (throw 'exit (match-string 1))))))
1142 (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
1143 ;; Above field was not empty, go down to the next row
1144 (setq txt (org-trim field))
1145 (org-table-next-row)
1146 (org-table-blank-field))
1147 (if non-empty-up (setq txt-up (org-trim field-up)))
1148 (setq inc (cond
1149 ((numberp org-table-copy-increment) org-table-copy-increment)
1150 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
1151 (string-match org-ts-regexp3 txt))
1152 (- (org-time-string-to-absolute txt)
1153 (org-time-string-to-absolute txt-up)))
1154 ((string-match org-ts-regexp3 txt) 1)
1155 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up)
1156 (- (string-to-number txt)
1157 (string-to-number (match-string 0 txt-up))))
1158 (t 1)))
1159 (t 1)))
1160 (if (not txt)
1161 (user-error "No non-empty field found")
1162 (if (and org-table-copy-increment
1163 (not (equal orig-n 0))
1164 (string-match "^[-+^/*0-9eE.]+$" txt)
1165 (< (string-to-number txt) 100000000))
1166 (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
1167 (insert txt)
1168 (org-move-to-column col)
1169 (if (and org-table-copy-increment (org-at-timestamp-p t))
1170 (org-timestamp-up-day inc)
1171 (org-table-maybe-recalculate-line))
1172 (org-table-align)
1173 (org-move-to-column col))))
1175 (defun org-table-check-inside-data-field (&optional noerror)
1176 "Is point inside a table data field?
1177 I.e. not on a hline or before the first or after the last column?
1178 This actually throws an error, so it aborts the current command."
1179 (cond ((and (org-at-table-p)
1180 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1181 (not (org-at-table-hline-p))
1182 (not (looking-at "[ \t]*$"))))
1183 (noerror nil)
1184 (t (user-error "Not in table data field"))))
1186 (defvar org-table-clip nil
1187 "Clipboard for table regions.")
1189 (defun org-table-get (line column)
1190 "Get the field in table line LINE, column COLUMN.
1191 If LINE is larger than the number of data lines in the table, the function
1192 returns nil. However, if COLUMN is too large, we will simply return an
1193 empty string.
1194 If LINE is nil, use the current line.
1195 If COLUMN is nil, use the current column."
1196 (setq column (or column (org-table-current-column)))
1197 (save-excursion
1198 (and (or (not line) (org-table-goto-line line))
1199 (org-trim (org-table-get-field column)))))
1201 (defun org-table-put (line column value &optional align)
1202 "Put VALUE into line LINE, column COLUMN.
1203 When ALIGN is set, also realign the table."
1204 (setq column (or column (org-table-current-column)))
1205 (prog1 (save-excursion
1206 (and (or (not line) (org-table-goto-line line))
1207 (progn (org-table-goto-column column nil 'force) t)
1208 (org-table-get-field column value)))
1209 (and align (org-table-align))))
1211 (defun org-table-current-line ()
1212 "Return the index of the current data line."
1213 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1214 (save-excursion
1215 (goto-char (org-table-begin))
1216 (while (and (re-search-forward org-table-dataline-regexp end t)
1217 (setq cnt (1+ cnt))
1218 (< (point-at-eol) pos))))
1219 cnt))
1221 (defun org-table-goto-line (N)
1222 "Go to the Nth data line in the current table.
1223 Return t when the line exists, nil if it does not exist."
1224 (goto-char (org-table-begin))
1225 (let ((end (org-table-end)) (cnt 0))
1226 (while (and (re-search-forward org-table-dataline-regexp end t)
1227 (< (setq cnt (1+ cnt)) N)))
1228 (= cnt N)))
1230 ;;;###autoload
1231 (defun org-table-blank-field ()
1232 "Blank the current table field or active region."
1233 (interactive)
1234 (org-table-check-inside-data-field)
1235 (if (and (org-called-interactively-p 'any) (org-region-active-p))
1236 (let (org-table-clip)
1237 (org-table-cut-region (region-beginning) (region-end)))
1238 (skip-chars-backward "^|")
1239 (backward-char 1)
1240 (if (looking-at "|[^|\n]+")
1241 (let* ((pos (match-beginning 0))
1242 (match (match-string 0))
1243 (len (org-string-width match)))
1244 (replace-match (concat "|" (make-string (1- len) ?\ )))
1245 (goto-char (+ 2 pos))
1246 (substring match 1)))))
1248 (defun org-table-get-field (&optional n replace)
1249 "Return the value of the field in column N of current row.
1250 N defaults to current field.
1251 If REPLACE is a string, replace field with this value. The return value
1252 is always the old value."
1253 (and n (org-table-goto-column n))
1254 (skip-chars-backward "^|\n")
1255 (backward-char 1)
1256 (if (looking-at "|[^|\r\n]*")
1257 (let* ((pos (match-beginning 0))
1258 (val (buffer-substring (1+ pos) (match-end 0))))
1259 (if replace
1260 (replace-match (concat "|" (if (equal replace "") " " replace))
1261 t t))
1262 (goto-char (min (point-at-eol) (+ 2 pos)))
1263 val)
1264 (forward-char 1) ""))
1266 ;;;###autoload
1267 (defun org-table-field-info (arg)
1268 "Show info about the current field, and highlight any reference at point."
1269 (interactive "P")
1270 (unless (org-at-table-p) (user-error "Not at a table"))
1271 (org-table-analyze)
1272 (save-excursion
1273 (let* ((pos (point))
1274 (col (org-table-current-column))
1275 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1276 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1277 (line-beginning-position))
1278 col)
1279 org-table-named-field-locations)))
1280 (eql (org-table-expand-lhs-ranges
1281 (mapcar
1282 (lambda (e)
1283 (cons (org-table-formula-handle-first/last-rc (car e))
1284 (cdr e)))
1285 (org-table-get-stored-formulas))))
1286 (dline (org-table-current-dline))
1287 (ref (format "@%d$%d" dline col))
1288 (ref1 (org-table-convert-refs-to-an ref))
1289 ;; Prioritize field formulas over column formulas.
1290 (fequation (or (assoc name eql) (assoc ref eql)))
1291 (cequation (assoc (format "$%d" col) eql))
1292 (eqn (or fequation cequation)))
1293 (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
1294 (when p (setq eqn p)))
1295 (goto-char pos)
1296 (ignore-errors (org-table-show-reference 'local))
1297 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1298 dline col
1299 (if cname (concat " or $" cname) "")
1300 dline col ref1
1301 (if name (concat " or $" name) "")
1302 ;; FIXME: formula info not correct if special table line
1303 (if eqn
1304 (concat ", formula: "
1305 (org-table-formula-to-user
1306 (concat
1307 (if (string-match "^[$@]"(car eqn)) "" "$")
1308 (car eqn) "=" (cdr eqn))))
1309 "")))))
1311 (defun org-table-current-column ()
1312 "Find out which column we are in."
1313 (interactive)
1314 (when (org-called-interactively-p 'any) (org-table-check-inside-data-field))
1315 (save-excursion
1316 (let ((column 0) (pos (point)))
1317 (beginning-of-line)
1318 (while (search-forward "|" pos t) (incf column))
1319 (when (org-called-interactively-p 'interactive)
1320 (message "In table column %d" column))
1321 column)))
1323 ;;;###autoload
1324 (defun org-table-current-dline ()
1325 "Find out what table data line we are in.
1326 Only data lines count for this."
1327 (interactive)
1328 (when (org-called-interactively-p 'any)
1329 (org-table-check-inside-data-field))
1330 (save-excursion
1331 (let ((c 0)
1332 (pos (point)))
1333 (goto-char (org-table-begin))
1334 (while (<= (point) pos)
1335 (when (looking-at org-table-dataline-regexp) (incf c))
1336 (forward-line))
1337 (when (org-called-interactively-p 'any)
1338 (message "This is table line %d" c))
1339 c)))
1341 ;;;###autoload
1342 (defun org-table-goto-column (n &optional on-delim force)
1343 "Move the cursor to the Nth column in the current table line.
1344 With optional argument ON-DELIM, stop with point before the left delimiter
1345 of the field.
1346 If there are less than N fields, just go to after the last delimiter.
1347 However, when FORCE is non-nil, create new columns if necessary."
1348 (interactive "p")
1349 (beginning-of-line 1)
1350 (when (> n 0)
1351 (while (and (> (setq n (1- n)) -1)
1352 (or (search-forward "|" (point-at-eol) t)
1353 (and force
1354 (progn (end-of-line 1)
1355 (skip-chars-backward "^|")
1356 (insert " | ")
1357 t)))))
1358 (when (and force (not (looking-at ".*|")))
1359 (save-excursion (end-of-line 1) (insert " | ")))
1360 (if on-delim
1361 (backward-char 1)
1362 (if (looking-at " ") (forward-char 1)))))
1364 ;;;###autoload
1365 (defun org-table-insert-column ()
1366 "Insert a new column into the table."
1367 (interactive)
1368 (unless (org-at-table-p) (user-error "Not at a table"))
1369 (org-table-find-dataline)
1370 (let* ((col (max 1 (org-table-current-column)))
1371 (beg (org-table-begin))
1372 (end (copy-marker (org-table-end))))
1373 (org-table-save-field
1374 (goto-char beg)
1375 (while (< (point) end)
1376 (unless (org-at-table-hline-p)
1377 (org-table-goto-column col t)
1378 (insert "| "))
1379 (forward-line)))
1380 (set-marker end nil)
1381 (org-table-align)
1382 (when (or (not org-table-fix-formulas-confirm)
1383 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1384 (org-table-fix-formulas "$" nil (1- col) 1)
1385 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1387 (defun org-table-find-dataline ()
1388 "Find a data line in the current table, which is needed for column commands."
1389 (if (and (org-at-table-p)
1390 (not (org-at-table-hline-p)))
1392 (let ((col (current-column))
1393 (end (org-table-end)))
1394 (org-move-to-column col)
1395 (while (and (< (point) end)
1396 (or (not (= (current-column) col))
1397 (org-at-table-hline-p)))
1398 (beginning-of-line 2)
1399 (org-move-to-column col))
1400 (if (and (org-at-table-p)
1401 (not (org-at-table-hline-p)))
1403 (user-error
1404 "Please position cursor in a data line for column operations")))))
1406 (defun org-table-line-to-dline (line &optional above)
1407 "Turn a buffer line number into a data line number.
1409 If there is no data line in this line, return nil.
1411 If there is no matching dline (most likely the reference was
1412 a hline), the first dline below it is used. When ABOVE is
1413 non-nil, the one above is used."
1414 (let ((min 1)
1415 (max (1- (length org-table-dlines))))
1416 (cond ((or (> (aref org-table-dlines min) line)
1417 (< (aref org-table-dlines max) line))
1418 nil)
1419 ((= (aref org-table-dlines max) line) max)
1420 (t (catch 'exit
1421 (while (> (- max min) 1)
1422 (let* ((mean (/ (+ max min) 2))
1423 (v (aref org-table-dlines mean)))
1424 (cond ((= v line) (throw 'exit mean))
1425 ((> v line) (setq max mean))
1426 (t (setq min mean)))))
1427 (if above min max))))))
1429 ;;;###autoload
1430 (defun org-table-delete-column ()
1431 "Delete a column from the table."
1432 (interactive)
1433 (unless (org-at-table-p) (user-error "Not at a table"))
1434 (org-table-find-dataline)
1435 (org-table-check-inside-data-field)
1436 (let ((col (org-table-current-column))
1437 (beg (org-table-begin))
1438 (end (copy-marker (org-table-end))))
1439 (org-table-save-field
1440 (goto-char beg)
1441 (while (< (point) end)
1442 (if (org-at-table-hline-p)
1444 (org-table-goto-column col t)
1445 (and (looking-at "|[^|\n]+|")
1446 (replace-match "|")))
1447 (forward-line)))
1448 (set-marker end nil)
1449 (org-table-goto-column (max 1 (1- col)))
1450 (org-table-align)
1451 (when (or (not org-table-fix-formulas-confirm)
1452 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1453 (org-table-fix-formulas
1454 "$" (list (cons (number-to-string col) "INVALID")) col -1 col)
1455 (org-table-fix-formulas
1456 "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col))))
1458 ;;;###autoload
1459 (defun org-table-move-column-right ()
1460 "Move column to the right."
1461 (interactive)
1462 (org-table-move-column nil))
1463 ;;;###autoload
1464 (defun org-table-move-column-left ()
1465 "Move column to the left."
1466 (interactive)
1467 (org-table-move-column 'left))
1469 ;;;###autoload
1470 (defun org-table-move-column (&optional left)
1471 "Move the current column to the right. With arg LEFT, move to the left."
1472 (interactive "P")
1473 (unless (org-at-table-p) (user-error "Not at a table"))
1474 (org-table-find-dataline)
1475 (org-table-check-inside-data-field)
1476 (let* ((col (org-table-current-column))
1477 (col1 (if left (1- col) col))
1478 (colpos (if left (1- col) (1+ col)))
1479 (beg (org-table-begin))
1480 (end (copy-marker (org-table-end))))
1481 (when (and left (= col 1))
1482 (user-error "Cannot move column further left"))
1483 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1484 (user-error "Cannot move column further right"))
1485 (org-table-save-field
1486 (goto-char beg)
1487 (while (< (point) end)
1488 (unless (org-at-table-hline-p)
1489 (org-table-goto-column col1 t)
1490 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1491 (replace-match "|\\2|\\1|")))
1492 (forward-line)))
1493 (set-marker end nil)
1494 (org-table-goto-column colpos)
1495 (org-table-align)
1496 (when (or (not org-table-fix-formulas-confirm)
1497 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1498 (org-table-fix-formulas
1499 "$" (list (cons (number-to-string col) (number-to-string colpos))
1500 (cons (number-to-string colpos) (number-to-string col))))
1501 (org-table-fix-formulas
1502 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1503 (cons (number-to-string colpos) (number-to-string col)))))))
1505 ;;;###autoload
1506 (defun org-table-move-row-down ()
1507 "Move table row down."
1508 (interactive)
1509 (org-table-move-row nil))
1510 ;;;###autoload
1511 (defun org-table-move-row-up ()
1512 "Move table row up."
1513 (interactive)
1514 (org-table-move-row 'up))
1516 ;;;###autoload
1517 (defun org-table-move-row (&optional up)
1518 "Move the current table line down. With arg UP, move it up."
1519 (interactive "P")
1520 (let* ((col (current-column))
1521 (pos (point))
1522 (hline1p (save-excursion (beginning-of-line 1)
1523 (looking-at org-table-hline-regexp)))
1524 (dline1 (org-table-current-dline))
1525 (dline2 (+ dline1 (if up -1 1)))
1526 (tonew (if up 0 2))
1527 txt hline2p)
1528 (beginning-of-line tonew)
1529 (unless (org-at-table-p)
1530 (goto-char pos)
1531 (user-error "Cannot move row further"))
1532 (setq hline2p (looking-at org-table-hline-regexp))
1533 (goto-char pos)
1534 (beginning-of-line 1)
1535 (setq pos (point))
1536 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1537 (delete-region (point) (1+ (point-at-eol)))
1538 (beginning-of-line tonew)
1539 (insert txt)
1540 (beginning-of-line 0)
1541 (org-move-to-column col)
1542 (unless (or hline1p hline2p
1543 (not (or (not org-table-fix-formulas-confirm)
1544 (funcall org-table-fix-formulas-confirm
1545 "Fix formulas? "))))
1546 (org-table-fix-formulas
1547 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1548 (cons (number-to-string dline2) (number-to-string dline1)))))))
1550 ;;;###autoload
1551 (defun org-table-insert-row (&optional arg)
1552 "Insert a new row above the current line into the table.
1553 With prefix ARG, insert below the current line."
1554 (interactive "P")
1555 (if (not (org-at-table-p))
1556 (user-error "Not at a table"))
1557 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1558 (new (org-table-clean-line line)))
1559 ;; Fix the first field if necessary
1560 (if (string-match "^[ \t]*| *[#$] *|" line)
1561 (setq new (replace-match (match-string 0 line) t t new)))
1562 (beginning-of-line (if arg 2 1))
1563 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1564 (beginning-of-line 0)
1565 (re-search-forward "| ?" (point-at-eol) t)
1566 (and (or org-table-may-need-update org-table-overlay-coordinates)
1567 (org-table-align))
1568 (when (or (not org-table-fix-formulas-confirm)
1569 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1570 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1572 ;;;###autoload
1573 (defun org-table-insert-hline (&optional above)
1574 "Insert a horizontal-line below the current line into the table.
1575 With prefix ABOVE, insert above the current line."
1576 (interactive "P")
1577 (if (not (org-at-table-p))
1578 (user-error "Not at a table"))
1579 (when (eobp) (insert "\n") (backward-char 1))
1580 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1581 (org-table-align))
1582 (let ((line (org-table-clean-line
1583 (buffer-substring (point-at-bol) (point-at-eol))))
1584 (col (current-column)))
1585 (while (string-match "|\\( +\\)|" line)
1586 (setq line (replace-match
1587 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1588 ?-) "|") t t line)))
1589 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1590 (beginning-of-line (if above 1 2))
1591 (insert line "\n")
1592 (beginning-of-line (if above 1 -1))
1593 (org-move-to-column col)
1594 (and org-table-overlay-coordinates (org-table-align))))
1596 ;;;###autoload
1597 (defun org-table-hline-and-move (&optional same-column)
1598 "Insert a hline and move to the row below that line."
1599 (interactive "P")
1600 (let ((col (org-table-current-column)))
1601 (org-table-maybe-eval-formula)
1602 (org-table-maybe-recalculate-line)
1603 (org-table-insert-hline)
1604 (end-of-line 2)
1605 (if (looking-at "\n[ \t]*|-")
1606 (progn (insert "\n|") (org-table-align))
1607 (org-table-next-field))
1608 (if same-column (org-table-goto-column col))))
1610 (defun org-table-clean-line (s)
1611 "Convert a table line S into a string with only \"|\" and space.
1612 In particular, this does handle wide and invisible characters."
1613 (if (string-match "^[ \t]*|-" s)
1614 ;; It's a hline, just map the characters
1615 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1616 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1617 (setq s (replace-match
1618 (concat "|" (make-string (org-string-width (match-string 1 s))
1619 ?\ ) "|")
1620 t t s)))
1623 ;;;###autoload
1624 (defun org-table-kill-row ()
1625 "Delete the current row or horizontal line from the table."
1626 (interactive)
1627 (if (not (org-at-table-p))
1628 (user-error "Not at a table"))
1629 (let ((col (current-column))
1630 (dline (org-table-current-dline)))
1631 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1632 (if (not (org-at-table-p)) (beginning-of-line 0))
1633 (org-move-to-column col)
1634 (when (or (not org-table-fix-formulas-confirm)
1635 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1636 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1637 dline -1 dline))))
1639 ;;;###autoload
1640 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func)
1641 "Sort table lines according to the column at point.
1643 The position of point indicates the column to be used for
1644 sorting, and the range of lines is the range between the nearest
1645 horizontal separator lines, or the entire table of no such lines
1646 exist. If point is before the first column, you will be prompted
1647 for the sorting column. If there is an active region, the mark
1648 specifies the first line and the sorting column, while point
1649 should be in the last line to be included into the sorting.
1651 The command then prompts for the sorting type which can be
1652 alphabetically, numerically, or by time (as given in a time stamp
1653 in the field, or as a HH:MM value). Sorting in reverse order is
1654 also possible.
1656 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1658 If SORTING-TYPE is specified when this function is called from a Lisp
1659 program, no prompting will take place. SORTING-TYPE must be a character,
1660 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1661 sorting should be done in reverse order.
1663 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1664 a function to be called to extract the key. It must return either
1665 a string or a number that should serve as the sorting key for that
1666 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1667 is specified interactively, the comparison will be either a string or
1668 numeric compare based on the type of the first key in the table."
1669 (interactive "P")
1670 (when (org-region-active-p) (goto-char (region-beginning)))
1671 ;; Point must be either within a field or before a data line.
1672 (save-excursion
1673 (skip-chars-backward " \t")
1674 (when (bolp) (search-forward "|" (line-end-position) t))
1675 (org-table-check-inside-data-field))
1676 ;; Set appropriate case sensitivity and column used for sorting.
1677 (let ((column (let ((c (org-table-current-column)))
1678 (cond ((> c 0) c)
1679 ((org-called-interactively-p 'any)
1680 (read-number "Use column N for sorting: "))
1681 (t 1))))
1682 (sorting-type
1683 (or sorting-type
1684 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1685 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1686 (save-restriction
1687 ;; Narrow buffer to appropriate sorting area.
1688 (if (org-region-active-p)
1689 (progn (goto-char (region-beginning))
1690 (narrow-to-region
1691 (point)
1692 (save-excursion (goto-char (region-end))
1693 (line-beginning-position 2))))
1694 (let ((start (org-table-begin))
1695 (end (org-table-end)))
1696 (narrow-to-region
1697 (save-excursion
1698 (if (re-search-backward org-table-hline-regexp start t)
1699 (line-beginning-position 2)
1700 start))
1701 (if (save-excursion (re-search-forward org-table-hline-regexp end t))
1702 (match-beginning 0)
1703 end))))
1704 ;; Determine arguments for `sort-subr'. Also record original
1705 ;; position. `org-table-save-field' cannot help here since
1706 ;; sorting is too much destructive.
1707 (let* ((sort-fold-case (not with-case))
1708 (coordinates
1709 (cons (count-lines (point-min) (line-beginning-position))
1710 (current-column)))
1711 (extract-key-from-field
1712 ;; Function to be called on the contents of the field
1713 ;; used for sorting in the current row.
1714 (case sorting-type
1715 ((?n ?N) #'string-to-number)
1716 ((?a ?A) #'org-sort-remove-invisible)
1717 ((?t ?T)
1718 (lambda (f)
1719 (cond ((string-match org-ts-regexp-both f)
1720 (org-float-time
1721 (org-time-string-to-time (match-string 0 f))))
1722 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" f)
1723 (org-hh:mm-string-to-minutes f))
1724 (t 0))))
1725 ((?f ?F)
1726 (or getkey-func
1727 (and (org-called-interactively-p 'any)
1728 (intern
1729 (completing-read "Sort using function: "
1730 obarray #'fboundp t)))
1731 (error "Missing key extractor to sort rows")))
1732 (t (user-error "Invalid sorting type `%c'" sorting-type))))
1733 (predicate
1734 (case sorting-type
1735 ((?n ?N ?t ?T) #'<)
1736 ((?a ?A) #'string<)
1737 ((?f ?F) compare-func))))
1738 (goto-char (point-min))
1739 (sort-subr (memq sorting-type '(?A ?N ?T ?F))
1740 (lambda ()
1741 (forward-line)
1742 (while (and (not (eobp))
1743 (not (looking-at org-table-dataline-regexp)))
1744 (forward-line)))
1745 #'end-of-line
1746 (lambda ()
1747 (funcall extract-key-from-field
1748 (org-trim (org-table-get-field column))))
1750 predicate)
1751 ;; Move back to initial field.
1752 (forward-line (car coordinates))
1753 (move-to-column (cdr coordinates))))))
1755 ;;;###autoload
1756 (defun org-table-cut-region (beg end)
1757 "Copy region in table to the clipboard and blank all relevant fields.
1758 If there is no active region, use just the field at point."
1759 (interactive (list
1760 (if (org-region-active-p) (region-beginning) (point))
1761 (if (org-region-active-p) (region-end) (point))))
1762 (org-table-copy-region beg end 'cut))
1764 ;;;###autoload
1765 (defun org-table-copy-region (beg end &optional cut)
1766 "Copy rectangular region in table to clipboard.
1767 A special clipboard is used which can only be accessed
1768 with `org-table-paste-rectangle'."
1769 (interactive (list
1770 (if (org-region-active-p) (region-beginning) (point))
1771 (if (org-region-active-p) (region-end) (point))
1772 current-prefix-arg))
1773 (goto-char (min beg end))
1774 (org-table-check-inside-data-field)
1775 (let ((beg (line-beginning-position))
1776 (c01 (org-table-current-column))
1777 region)
1778 (goto-char (max beg end))
1779 (org-table-check-inside-data-field)
1780 (let* ((end (copy-marker (line-end-position)))
1781 (c02 (org-table-current-column))
1782 (column-start (min c01 c02))
1783 (column-end (max c01 c02))
1784 (column-number (1+ (- column-end column-start)))
1785 (rpl (and cut " ")))
1786 (goto-char beg)
1787 (while (< (point) end)
1788 (unless (org-at-table-hline-p)
1789 ;; Collect every cell between COLUMN-START and COLUMN-END.
1790 (let (cols)
1791 (dotimes (c column-number)
1792 (push (org-table-get-field (+ c column-start) rpl) cols))
1793 (push (nreverse cols) region)))
1794 (forward-line))
1795 (set-marker end nil))
1796 (when cut (org-table-align))
1797 (setq org-table-clip (nreverse region))))
1799 ;;;###autoload
1800 (defun org-table-paste-rectangle ()
1801 "Paste a rectangular region into a table.
1802 The upper right corner ends up in the current field. All involved fields
1803 will be overwritten. If the rectangle does not fit into the present table,
1804 the table is enlarged as needed. The process ignores horizontal separator
1805 lines."
1806 (interactive)
1807 (unless (consp org-table-clip)
1808 (user-error "First cut/copy a region to paste!"))
1809 (org-table-check-inside-data-field)
1810 (let* ((column (org-table-current-column))
1811 (org-enable-table-editor t)
1812 (org-table-automatic-realign nil))
1813 (org-table-save-field
1814 (dolist (row org-table-clip)
1815 (while (org-at-table-hline-p) (forward-line))
1816 ;; If we left the table, create a new row.
1817 (when (and (bolp) (not (looking-at "[ \t]*|")))
1818 (end-of-line 0)
1819 (org-table-next-field))
1820 (let ((c column))
1821 (dolist (field row)
1822 (org-table-goto-column c nil 'force)
1823 (org-table-get-field nil field)
1824 (incf c)))
1825 (forward-line)))
1826 (org-table-align)))
1828 ;;;###autoload
1829 (defun org-table-convert ()
1830 "Convert from `org-mode' table to table.el and back.
1831 Obviously, this only works within limits. When an Org-mode table is
1832 converted to table.el, all horizontal separator lines get lost, because
1833 table.el uses these as cell boundaries and has no notion of horizontal lines.
1834 A table.el table can be converted to an Org-mode table only if it does not
1835 do row or column spanning. Multiline cells will become multiple cells.
1836 Beware, Org-mode does not test if the table can be successfully converted - it
1837 blindly applies a recipe that works for simple tables."
1838 (interactive)
1839 (require 'table)
1840 (if (org-at-table.el-p)
1841 ;; convert to Org-mode table
1842 (let ((beg (copy-marker (org-table-begin t)))
1843 (end (copy-marker (org-table-end t))))
1844 (table-unrecognize-region beg end)
1845 (goto-char beg)
1846 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1847 (replace-match ""))
1848 (goto-char beg))
1849 (if (org-at-table-p)
1850 ;; convert to table.el table
1851 (let ((beg (copy-marker (org-table-begin)))
1852 (end (copy-marker (org-table-end))))
1853 ;; first, get rid of all horizontal lines
1854 (goto-char beg)
1855 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1856 (replace-match ""))
1857 ;; insert a hline before first
1858 (goto-char beg)
1859 (org-table-insert-hline 'above)
1860 (beginning-of-line -1)
1861 ;; insert a hline after each line
1862 (while (progn (beginning-of-line 3) (< (point) end))
1863 (org-table-insert-hline))
1864 (goto-char beg)
1865 (setq end (move-marker end (org-table-end)))
1866 ;; replace "+" at beginning and ending of hlines
1867 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1868 (replace-match "\\1+-"))
1869 (goto-char beg)
1870 (while (re-search-forward "-|[ \t]*$" end t)
1871 (replace-match "-+"))
1872 (goto-char beg)))))
1874 (defun org-table-transpose-table-at-point ()
1875 "Transpose Org table at point and eliminate hlines.
1876 So a table like
1878 | 1 | 2 | 4 | 5 |
1879 |---+---+---+---|
1880 | a | b | c | d |
1881 | e | f | g | h |
1883 will be transposed as
1885 | 1 | a | e |
1886 | 2 | b | f |
1887 | 4 | c | g |
1888 | 5 | d | h |
1890 Note that horizontal lines disappear."
1891 (interactive)
1892 (let* ((table (delete 'hline (org-table-to-lisp)))
1893 (dline_old (org-table-current-line))
1894 (col_old (org-table-current-column))
1895 (contents (mapcar (lambda (p)
1896 (let ((tp table))
1897 (mapcar
1898 (lambda (rown)
1899 (prog1
1900 (pop (car tp))
1901 (setq tp (cdr tp))))
1902 table)))
1903 (car table))))
1904 (goto-char (org-table-begin))
1905 (re-search-forward "|")
1906 (backward-char)
1907 (delete-region (point) (org-table-end))
1908 (insert (mapconcat
1909 (lambda(x)
1910 (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1911 contents ""))
1912 (org-table-goto-line col_old)
1913 (org-table-goto-column dline_old))
1914 (org-table-align))
1916 ;;;###autoload
1917 (defun org-table-wrap-region (arg)
1918 "Wrap several fields in a column like a paragraph.
1919 This is useful if you'd like to spread the contents of a field over several
1920 lines, in order to keep the table compact.
1922 If there is an active region, and both point and mark are in the same column,
1923 the text in the column is wrapped to minimum width for the given number of
1924 lines. Generally, this makes the table more compact. A prefix ARG may be
1925 used to change the number of desired lines. For example, \
1926 `C-2 \\[org-table-wrap-region]'
1927 formats the selected text to two lines. If the region was longer than two
1928 lines, the remaining lines remain empty. A negative prefix argument reduces
1929 the current number of lines by that amount. The wrapped text is pasted back
1930 into the table. If you formatted it to more lines than it was before, fields
1931 further down in the table get overwritten - so you might need to make space in
1932 the table first.
1934 If there is no region, the current field is split at the cursor position and
1935 the text fragment to the right of the cursor is prepended to the field one
1936 line down.
1938 If there is no region, but you specify a prefix ARG, the current field gets
1939 blank, and the content is appended to the field above."
1940 (interactive "P")
1941 (org-table-check-inside-data-field)
1942 (if (org-region-active-p)
1943 ;; There is a region: fill as a paragraph.
1944 (let ((start (region-beginning)))
1945 (org-table-cut-region (region-beginning) (region-end))
1946 (when (> (length (car org-table-clip)) 1)
1947 (user-error "Region must be limited to single column"))
1948 (let ((nlines (cond ((not arg) (length org-table-clip))
1949 ((< arg 1) (+ (length org-table-clip) arg))
1950 (t arg))))
1951 (setq org-table-clip
1952 (mapcar #'list
1953 (org-wrap (mapconcat #'car org-table-clip " ")
1955 nlines))))
1956 (goto-char start)
1957 (org-table-paste-rectangle))
1958 ;; No region, split the current field at point.
1959 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1960 (skip-chars-forward "^\r\n|"))
1961 (cond
1962 (arg ; Combine with field above.
1963 (let ((s (org-table-blank-field))
1964 (col (org-table-current-column)))
1965 (forward-line -1)
1966 (while (org-at-table-hline-p) (forward-line -1))
1967 (org-table-goto-column col)
1968 (skip-chars-forward "^|")
1969 (skip-chars-backward " ")
1970 (insert " " (org-trim s))
1971 (org-table-align)))
1972 ((looking-at "\\([^|]+\\)+|") ; Split field.
1973 (let ((s (match-string 1)))
1974 (replace-match " |")
1975 (goto-char (match-beginning 0))
1976 (org-table-next-row)
1977 (insert (org-trim s) " ")
1978 (org-table-align)))
1979 (t (org-table-next-row)))))
1981 (defvar org-field-marker nil)
1983 ;;;###autoload
1984 (defun org-table-edit-field (arg)
1985 "Edit table field in a different window.
1986 This is mainly useful for fields that contain hidden parts.
1987 When called with a \\[universal-argument] prefix, just make the full field visible so that
1988 it can be edited in place."
1989 (interactive "P")
1990 (cond
1991 ((equal arg '(16))
1992 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1993 (arg
1994 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1995 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1996 (remove-text-properties b e '(org-cwidth t invisible t
1997 display t intangible t))
1998 (if (and (boundp 'font-lock-mode) font-lock-mode)
1999 (font-lock-fontify-block))))
2001 (let ((pos (point-marker))
2002 (coord
2003 (if (eq org-table-use-standard-references t)
2004 (concat (org-number-to-letters (org-table-current-column))
2005 (int-to-string (org-table-current-dline)))
2006 (concat "@" (int-to-string (org-table-current-dline))
2007 "$" (int-to-string (org-table-current-column)))))
2008 (field (org-table-get-field))
2009 (cw (current-window-configuration))
2011 (goto-char pos)
2012 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2013 (when (and (local-variable-p 'org-field-marker)
2014 (markerp org-field-marker))
2015 (move-marker org-field-marker nil))
2016 (erase-buffer)
2017 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
2018 (let ((org-inhibit-startup t)) (org-mode))
2019 (auto-fill-mode -1)
2020 (setq truncate-lines nil)
2021 (setq word-wrap t)
2022 (goto-char (setq p (point-max)))
2023 (insert (org-trim field))
2024 (remove-text-properties p (point-max)
2025 '(invisible t org-cwidth t display t
2026 intangible t))
2027 (goto-char p)
2028 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
2029 (org-set-local 'org-window-configuration cw)
2030 (org-set-local 'org-field-marker pos)
2031 (message "Edit and finish with C-c C-c")))))
2033 (defun org-table-finish-edit-field ()
2034 "Finish editing a table data field.
2035 Remove all newline characters, insert the result into the table, realign
2036 the table and kill the editing buffer."
2037 (let ((pos org-field-marker)
2038 (cw org-window-configuration)
2039 (cb (current-buffer))
2040 text)
2041 (goto-char (point-min))
2042 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
2043 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
2044 (replace-match " "))
2045 (setq text (org-trim (buffer-string)))
2046 (set-window-configuration cw)
2047 (kill-buffer cb)
2048 (select-window (get-buffer-window (marker-buffer pos)))
2049 (goto-char pos)
2050 (move-marker pos nil)
2051 (org-table-check-inside-data-field)
2052 (org-table-get-field nil text)
2053 (org-table-align)
2054 (message "New field value inserted")))
2056 (define-minor-mode org-table-follow-field-mode
2057 "Minor mode to make the table field editor window follow the cursor.
2058 When this mode is active, the field editor window will always show the
2059 current field. The mode exits automatically when the cursor leaves the
2060 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2061 nil " TblFollow" nil
2062 (if org-table-follow-field-mode
2063 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
2064 'append 'local)
2065 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
2066 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2067 (win (and buf (get-buffer-window buf))))
2068 (when win (delete-window win))
2069 (when buf
2070 (with-current-buffer buf
2071 (move-marker org-field-marker nil))
2072 (kill-buffer buf)))))
2074 (defun org-table-follow-fields-with-editor ()
2075 (if (and org-table-exit-follow-field-mode-when-leaving-table
2076 (not (org-at-table-p)))
2077 ;; We have left the table, exit the follow mode
2078 (org-table-follow-field-mode -1)
2079 (when (org-table-check-inside-data-field 'noerror)
2080 (let ((win (selected-window)))
2081 (org-table-edit-field nil)
2082 (org-fit-window-to-buffer)
2083 (select-window win)))))
2085 (defvar org-timecnt) ; dynamically scoped parameter
2087 ;;;###autoload
2088 (defun org-table-sum (&optional beg end nlast)
2089 "Sum numbers in region of current table column.
2090 The result will be displayed in the echo area, and will be available
2091 as kill to be inserted with \\[yank].
2093 If there is an active region, it is interpreted as a rectangle and all
2094 numbers in that rectangle will be summed. If there is no active
2095 region and point is located in a table column, sum all numbers in that
2096 column.
2098 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2099 numbers are assumed to be times as well (in decimal hours) and the
2100 numbers are added as such.
2102 If NLAST is a number, only the NLAST fields will actually be summed."
2103 (interactive)
2104 (save-excursion
2105 (let (col (org-timecnt 0) diff h m s org-table-clip)
2106 (cond
2107 ((and beg end)) ; beg and end given explicitly
2108 ((org-region-active-p)
2109 (setq beg (region-beginning) end (region-end)))
2111 (setq col (org-table-current-column))
2112 (goto-char (org-table-begin))
2113 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2114 (user-error "No table data"))
2115 (org-table-goto-column col)
2116 (setq beg (point))
2117 (goto-char (org-table-end))
2118 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2119 (user-error "No table data"))
2120 (org-table-goto-column col)
2121 (setq end (point))))
2122 (let* ((items (apply 'append (org-table-copy-region beg end)))
2123 (items1 (cond ((not nlast) items)
2124 ((>= nlast (length items)) items)
2125 (t (setq items (reverse items))
2126 (setcdr (nthcdr (1- nlast) items) nil)
2127 (nreverse items))))
2128 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2129 items1)))
2130 (res (apply '+ numbers))
2131 (sres (if (= org-timecnt 0)
2132 (number-to-string res)
2133 (setq diff (* 3600 res)
2134 h (floor (/ diff 3600)) diff (mod diff 3600)
2135 m (floor (/ diff 60)) diff (mod diff 60)
2136 s diff)
2137 (format "%.0f:%02.0f:%02.0f" h m s))))
2138 (kill-new sres)
2139 (if (org-called-interactively-p 'interactive)
2140 (message "%s"
2141 (substitute-command-keys
2142 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2143 (length numbers) sres))))
2144 sres))))
2146 (defun org-table-get-number-for-summing (s)
2147 (let (n)
2148 (if (string-match "^ *|? *" s)
2149 (setq s (replace-match "" nil nil s)))
2150 (if (string-match " *|? *$" s)
2151 (setq s (replace-match "" nil nil s)))
2152 (setq n (string-to-number s))
2153 (cond
2154 ((and (string-match "0" s)
2155 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2156 ((string-match "\\`[ \t]+\\'" s) nil)
2157 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2158 (let ((h (string-to-number (or (match-string 1 s) "0")))
2159 (m (string-to-number (or (match-string 2 s) "0")))
2160 (s (string-to-number (or (match-string 4 s) "0"))))
2161 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2162 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2163 ((equal n 0) nil)
2164 (t n))))
2166 (defun org-table-current-field-formula (&optional key noerror)
2167 "Return the formula active for the current field.
2169 Assumes that table is already analyzed. If KEY is given, return
2170 the key to this formula. Otherwise return the formula preceded
2171 with \"=\" or \":=\"."
2172 (let* ((line (count-lines org-table-current-begin-pos
2173 (line-beginning-position)))
2174 (row (org-table-line-to-dline line)))
2175 (cond
2176 (row
2177 (let* ((col (org-table-current-column))
2178 (name (car (rassoc (list line col)
2179 org-table-named-field-locations)))
2180 (scol (format "$%d" col))
2181 (ref (format "@%d$%d" (org-table-current-dline) col))
2182 (stored-list (org-table-get-stored-formulas noerror))
2183 (ass (or (assoc name stored-list)
2184 (assoc ref stored-list)
2185 (assoc scol stored-list))))
2186 (cond (key (car ass))
2187 (ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2188 (cdr ass))))))
2189 (noerror nil)
2190 (t (error "No formula active for the current field")))))
2192 (defun org-table-get-formula (&optional equation named)
2193 "Read a formula from the minibuffer, offer stored formula as default.
2194 When NAMED is non-nil, look for a named equation."
2195 (let* ((stored-list (org-table-get-stored-formulas))
2196 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2197 (line-beginning-position))
2198 (org-table-current-column))
2199 org-table-named-field-locations)))
2200 (ref (format "@%d$%d"
2201 (org-table-current-dline)
2202 (org-table-current-column)))
2203 (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
3601 (substitute-command-keys "\\<org-mode-map>\
3602 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3603 See menu for more commands.")))))
3605 (defun org-table-fedit-post-command ()
3606 (when (not (memq this-command '(lisp-complete-symbol)))
3607 (let ((win (selected-window)))
3608 (save-excursion
3609 (ignore-errors (org-table-show-reference))
3610 (select-window win)))))
3612 (defun org-table-formula-to-user (s)
3613 "Convert a formula from internal to user representation."
3614 (if (eq org-table-use-standard-references t)
3615 (org-table-convert-refs-to-an s)
3618 (defun org-table-formula-from-user (s)
3619 "Convert a formula from user to internal representation."
3620 (if org-table-use-standard-references
3621 (org-table-convert-refs-to-rc s)
3624 (defun org-table-convert-refs-to-rc (s)
3625 "Convert spreadsheet references from A7 to @7$28.
3626 Works for single references, but also for entire formulas and even the
3627 full TBLFM line."
3628 (let ((start 0))
3629 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3630 (cond
3631 ((match-end 3)
3632 ;; format match, just advance
3633 (setq start (match-end 0)))
3634 ((and (> (match-beginning 0) 0)
3635 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3636 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3637 ;; 3.e5 or something like this.
3638 (setq start (match-end 0)))
3639 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3640 ;; (member (match-string 1 s)
3641 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3643 ;; function name, just advance
3644 (setq start (match-end 0)))
3646 (setq start (match-beginning 0)
3647 s (replace-match
3648 (if (equal (match-string 2 s) "&")
3649 (format "$%d" (org-letters-to-number (match-string 1 s)))
3650 (format "@%d$%d"
3651 (string-to-number (match-string 2 s))
3652 (org-letters-to-number (match-string 1 s))))
3653 t t s)))))
3656 (defun org-table-convert-refs-to-an (s)
3657 "Convert spreadsheet references from to @7$28 to AB7.
3658 Works for single references, but also for entire formulas and even the
3659 full TBLFM line."
3660 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3661 (setq s (replace-match
3662 (format "%s%d"
3663 (org-number-to-letters
3664 (string-to-number (match-string 2 s)))
3665 (string-to-number (match-string 1 s)))
3666 t t s)))
3667 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3668 (setq s (replace-match (concat "\\1"
3669 (org-number-to-letters
3670 (string-to-number (match-string 2 s))) "&")
3671 t nil s)))
3674 (defun org-letters-to-number (s)
3675 "Convert a base 26 number represented by letters into an integer.
3676 For example: AB -> 28."
3677 (let ((n 0))
3678 (setq s (upcase s))
3679 (while (> (length s) 0)
3680 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3681 s (substring s 1)))
3684 (defun org-number-to-letters (n)
3685 "Convert an integer into a base 26 number represented by letters.
3686 For example: 28 -> AB."
3687 (let ((s ""))
3688 (while (> n 0)
3689 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3690 n (/ (1- n) 26)))
3693 (defun org-table-time-string-to-seconds (s)
3694 "Convert a time string into numerical duration in seconds.
3695 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3696 If S is a string representing a number, keep this number."
3697 (if (equal s "")
3699 (let (hour minus min sec res)
3700 (cond
3701 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3702 (setq minus (< 0 (length (match-string 1 s)))
3703 hour (string-to-number (match-string 2 s))
3704 min (string-to-number (match-string 3 s))
3705 sec (string-to-number (match-string 4 s)))
3706 (if minus
3707 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3708 (setq res (+ (* hour 3600) (* min 60) sec))))
3709 ((and (not (string-match org-ts-regexp-both s))
3710 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3711 (setq minus (< 0 (length (match-string 1 s)))
3712 hour (string-to-number (match-string 2 s))
3713 min (string-to-number (match-string 3 s)))
3714 (if minus
3715 (setq res (- (+ (* hour 3600) (* min 60))))
3716 (setq res (+ (* hour 3600) (* min 60)))))
3717 (t (setq res (string-to-number s))))
3718 (number-to-string res))))
3720 (defun org-table-time-seconds-to-string (secs &optional output-format)
3721 "Convert a number of seconds to a time string.
3722 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3723 minutes or seconds."
3724 (let* ((secs0 (abs secs))
3725 (res
3726 (cond ((eq output-format 'days)
3727 (format "%.3f" (/ (float secs0) 86400)))
3728 ((eq output-format 'hours)
3729 (format "%.2f" (/ (float secs0) 3600)))
3730 ((eq output-format 'minutes)
3731 (format "%.1f" (/ (float secs0) 60)))
3732 ((eq output-format 'seconds)
3733 (format "%d" secs0))
3734 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3735 (if (< secs 0) (concat "-" res) res)))
3737 (defun org-table-fedit-convert-buffer (function)
3738 "Convert all references in this buffer, using FUNCTION."
3739 (let ((origin (copy-marker (line-beginning-position))))
3740 (goto-char (point-min))
3741 (while (not (eobp))
3742 (insert (funcall function (buffer-substring (point) (line-end-position))))
3743 (delete-region (point) (line-end-position))
3744 (forward-line))
3745 (goto-char origin)
3746 (set-marker origin nil)))
3748 (defun org-table-fedit-toggle-ref-type ()
3749 "Convert all references in the buffer from B3 to @3$2 and back."
3750 (interactive)
3751 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3752 (org-table-fedit-convert-buffer
3753 (if org-table-buffer-is-an
3754 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3755 (message "Reference type switched to %s"
3756 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3758 (defun org-table-fedit-ref-up ()
3759 "Shift the reference at point one row/hline up."
3760 (interactive)
3761 (org-table-fedit-shift-reference 'up))
3762 (defun org-table-fedit-ref-down ()
3763 "Shift the reference at point one row/hline down."
3764 (interactive)
3765 (org-table-fedit-shift-reference 'down))
3766 (defun org-table-fedit-ref-left ()
3767 "Shift the reference at point one field to the left."
3768 (interactive)
3769 (org-table-fedit-shift-reference 'left))
3770 (defun org-table-fedit-ref-right ()
3771 "Shift the reference at point one field to the right."
3772 (interactive)
3773 (org-table-fedit-shift-reference 'right))
3775 (defun org-table-fedit-shift-reference (dir)
3776 (cond
3777 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3778 (if (memq dir '(left right))
3779 (org-rematch-and-replace 1 (eq dir 'left))
3780 (user-error "Cannot shift reference in this direction")))
3781 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3782 ;; A B3-like reference
3783 (if (memq dir '(up down))
3784 (org-rematch-and-replace 2 (eq dir 'up))
3785 (org-rematch-and-replace 1 (eq dir 'left))))
3786 ((org-in-regexp
3787 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3788 ;; An internal reference
3789 (if (memq dir '(up down))
3790 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3791 (org-rematch-and-replace 5 (eq dir 'left))))))
3793 (defun org-rematch-and-replace (n &optional decr hline)
3794 "Re-match the group N, and replace it with the shifted reference."
3795 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3796 (goto-char (match-beginning n))
3797 (and (looking-at (regexp-quote (match-string n)))
3798 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3799 t t)))
3801 (defun org-table-shift-refpart (ref &optional decr hline)
3802 "Shift a reference part REF.
3803 If DECR is set, decrease the references row/column, else increase.
3804 If HLINE is set, this may be a hline reference, it certainly is not
3805 a translation reference."
3806 (save-match-data
3807 (let* ((sign (string-match "^[-+]" ref)) n)
3809 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3810 (cond
3811 ((and hline (string-match "^I+" ref))
3812 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3813 (setq n (+ n (if decr -1 1)))
3814 (if (= n 0) (setq n (+ n (if decr -1 1))))
3815 (if sign
3816 (setq sign (if (< n 0) "-" "+") n (abs n))
3817 (setq n (max 1 n)))
3818 (concat sign (make-string n ?I)))
3820 ((string-match "^[0-9]+" ref)
3821 (setq n (string-to-number (concat sign ref)))
3822 (setq n (+ n (if decr -1 1)))
3823 (if sign
3824 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3825 (number-to-string (max 1 n))))
3827 ((string-match "^[a-zA-Z]+" ref)
3828 (org-number-to-letters
3829 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3831 (t (user-error "Cannot shift reference"))))))
3833 (defun org-table-fedit-toggle-coordinates ()
3834 "Toggle the display of coordinates in the referenced table."
3835 (interactive)
3836 (let ((pos (marker-position org-pos)))
3837 (with-current-buffer (marker-buffer org-pos)
3838 (save-excursion
3839 (goto-char pos)
3840 (org-table-toggle-coordinate-overlays)))))
3842 (defun org-table-fedit-finish (&optional arg)
3843 "Parse the buffer for formula definitions and install them.
3844 With prefix ARG, apply the new formulas to the table."
3845 (interactive "P")
3846 (org-table-remove-rectangle-highlight)
3847 (when org-table-use-standard-references
3848 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3849 (setq org-table-buffer-is-an nil))
3850 (let ((pos org-pos)
3851 (sel-win org-selected-window)
3852 (source org-table--fedit-source)
3853 eql)
3854 (goto-char (point-min))
3855 (while (re-search-forward
3856 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3857 nil t)
3858 (let ((var (match-string 1))
3859 (form (org-trim (match-string 3))))
3860 (unless (equal form "")
3861 (while (string-match "[ \t]*\n[ \t]*" form)
3862 (setq form (replace-match " " t t form)))
3863 (when (assoc var eql)
3864 (user-error "Double formulas for %s" var))
3865 (push (cons var form) eql))))
3866 (set-window-configuration org-window-configuration)
3867 (select-window sel-win)
3868 (goto-char source)
3869 (org-table-store-formulas eql)
3870 (set-marker pos nil)
3871 (set-marker source nil)
3872 (kill-buffer "*Edit Formulas*")
3873 (if arg
3874 (org-table-recalculate 'all)
3875 (message "New formulas installed - press C-u C-c C-c to apply."))))
3877 (defun org-table-fedit-abort ()
3878 "Abort editing formulas, without installing the changes."
3879 (interactive)
3880 (org-table-remove-rectangle-highlight)
3881 (let ((pos org-pos) (sel-win org-selected-window))
3882 (set-window-configuration org-window-configuration)
3883 (select-window sel-win)
3884 (goto-char pos)
3885 (move-marker pos nil)
3886 (message "Formula editing aborted without installing changes")))
3888 (defun org-table-fedit-lisp-indent ()
3889 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3890 (interactive)
3891 (let ((pos (point)) beg end ind)
3892 (beginning-of-line 1)
3893 (cond
3894 ((looking-at "[ \t]")
3895 (goto-char pos)
3896 (call-interactively 'lisp-indent-line))
3897 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3898 ((not (fboundp 'pp-buffer))
3899 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3900 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3901 (goto-char (- (match-end 0) 2))
3902 (setq beg (point))
3903 (setq ind (make-string (current-column) ?\ ))
3904 (condition-case nil (forward-sexp 1)
3905 (error
3906 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3907 (setq end (point))
3908 (save-restriction
3909 (narrow-to-region beg end)
3910 (if (eq last-command this-command)
3911 (progn
3912 (goto-char (point-min))
3913 (setq this-command nil)
3914 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3915 (replace-match " ")))
3916 (pp-buffer)
3917 (untabify (point-min) (point-max))
3918 (goto-char (1+ (point-min)))
3919 (while (re-search-forward "^." nil t)
3920 (beginning-of-line 1)
3921 (insert ind))
3922 (goto-char (point-max))
3923 (org-delete-backward-char 1)))
3924 (goto-char beg))
3925 (t nil))))
3927 (defvar org-show-positions nil)
3929 (defun org-table-show-reference (&optional local)
3930 "Show the location/value of the $ expression at point.
3931 When LOCAL is non-nil, show references for the table at point."
3932 (interactive)
3933 (org-table-remove-rectangle-highlight)
3934 (when local (org-table-analyze))
3935 (catch 'exit
3936 (let ((pos (if local (point) org-pos))
3937 (face2 'highlight)
3938 (org-inhibit-highlight-removal t)
3939 (win (selected-window))
3940 (org-show-positions nil)
3941 var name e what match dest)
3942 (setq what (cond
3943 ((org-in-regexp "^@[0-9]+[ \t=]")
3944 (setq match (concat (substring (match-string 0) 0 -1)
3945 "$1.."
3946 (substring (match-string 0) 0 -1)
3947 "$100"))
3948 'range)
3949 ((or (org-in-regexp org-table-range-regexp2)
3950 (org-in-regexp org-table-translate-regexp)
3951 (org-in-regexp org-table-range-regexp))
3952 (setq match
3953 (save-match-data
3954 (org-table-convert-refs-to-rc (match-string 0))))
3955 'range)
3956 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3957 ((org-in-regexp "\\$[0-9]+") 'column)
3958 ((not local) nil)
3959 (t (user-error "No reference at point")))
3960 match (and what (or match (match-string 0))))
3961 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3962 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3963 'secondary-selection))
3964 (org-add-hook 'before-change-functions
3965 #'org-table-remove-rectangle-highlight)
3966 (when (eq what 'name) (setq var (substring match 1)))
3967 (when (eq what 'range)
3968 (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
3969 (setq match (org-table-formula-substitute-names match)))
3970 (unless local
3971 (save-excursion
3972 (end-of-line)
3973 (re-search-backward "^\\S-" nil t)
3974 (beginning-of-line)
3975 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3976 \\([0-9]+\\|&\\)\\) *=")
3977 (setq dest
3978 (save-match-data
3979 (org-table-convert-refs-to-rc (match-string 1))))
3980 (org-table-add-rectangle-overlay
3981 (match-beginning 1) (match-end 1) face2))))
3982 (if (and (markerp pos) (marker-buffer pos))
3983 (if (get-buffer-window (marker-buffer pos))
3984 (select-window (get-buffer-window (marker-buffer pos)))
3985 (org-switch-to-buffer-other-window (get-buffer-window
3986 (marker-buffer pos)))))
3987 (goto-char pos)
3988 (org-table-force-dataline)
3989 (let ((table-start
3990 (if local org-table-current-begin-pos (org-table-begin))))
3991 (when dest
3992 (setq name (substring dest 1))
3993 (cond
3994 ((org-string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3995 (org-table-goto-field dest))
3996 ((org-string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
3997 dest)
3998 (org-table-goto-field dest))
3999 (t (org-table-goto-column (string-to-number name))))
4000 (move-marker pos (point))
4001 (org-table-highlight-rectangle nil nil face2))
4002 (cond
4003 ((equal dest match))
4004 ((not match))
4005 ((eq what 'range)
4006 (ignore-errors (org-table-get-range match table-start nil 'highlight)))
4007 ((setq e (assoc var org-table-named-field-locations))
4008 (org-table-goto-field var)
4009 (org-table-highlight-rectangle)
4010 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
4011 ((setq e (assoc var org-table-column-names))
4012 (org-table-goto-column (string-to-number (cdr e)))
4013 (org-table-highlight-rectangle)
4014 (goto-char table-start)
4015 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
4016 (org-table-end) t)
4017 (progn
4018 (goto-char (match-beginning 1))
4019 (org-table-highlight-rectangle)
4020 (message "Named column (column %s)" (cdr e)))
4021 (user-error "Column name not found")))
4022 ((eq what 'column)
4023 ;; Column number.
4024 (org-table-goto-column (string-to-number (substring match 1)))
4025 (org-table-highlight-rectangle)
4026 (message "Column %s" (substring match 1)))
4027 ((setq e (assoc var org-table-local-parameters))
4028 (goto-char table-start)
4029 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
4030 (progn
4031 (goto-char (match-beginning 1))
4032 (org-table-highlight-rectangle)
4033 (message "Local parameter."))
4034 (user-error "Parameter not found")))
4035 ((not var) (user-error "No reference at point"))
4036 ((setq e (assoc var org-table-formula-constants-local))
4037 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4038 var (cdr e)))
4039 ((setq e (assoc var org-table-formula-constants))
4040 (message "Constant: $%s=%s in `org-table-formula-constants'."
4041 var (cdr e)))
4042 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4043 (message "Constant: $%s=%s, from `constants.el'%s."
4044 var e (format " (%s units)" constants-unit-system)))
4045 (t (user-error "Undefined name $%s" var)))
4046 (goto-char pos)
4047 (when (and org-show-positions
4048 (not (memq this-command '(org-table-fedit-scroll
4049 org-table-fedit-scroll-down))))
4050 (push pos org-show-positions)
4051 (push table-start org-show-positions)
4052 (let ((min (apply 'min org-show-positions))
4053 (max (apply 'max org-show-positions)))
4054 (set-window-start (selected-window) min)
4055 (goto-char max)
4056 (or (pos-visible-in-window-p max)
4057 (set-window-start (selected-window) max)))))
4058 (select-window win))))
4060 (defun org-table-force-dataline ()
4061 "Make sure the cursor is in a dataline in a table."
4062 (unless (save-excursion
4063 (beginning-of-line 1)
4064 (looking-at org-table-dataline-regexp))
4065 (let* ((re org-table-dataline-regexp)
4066 (p1 (save-excursion (re-search-forward re nil 'move)))
4067 (p2 (save-excursion (re-search-backward re nil 'move))))
4068 (cond ((and p1 p2)
4069 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4070 p1 p2)))
4071 ((or p1 p2) (goto-char (or p1 p2)))
4072 (t (user-error "No table dataline around here"))))))
4074 (defun org-table-fedit-line-up ()
4075 "Move cursor one line up in the window showing the table."
4076 (interactive)
4077 (org-table-fedit-move 'previous-line))
4079 (defun org-table-fedit-line-down ()
4080 "Move cursor one line down in the window showing the table."
4081 (interactive)
4082 (org-table-fedit-move 'next-line))
4084 (defun org-table-fedit-move (command)
4085 "Move the cursor in the window showing the table.
4086 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4087 (let ((org-table-allow-automatic-line-recalculation nil)
4088 (pos org-pos) (win (selected-window)) p)
4089 (select-window (get-buffer-window (marker-buffer org-pos)))
4090 (setq p (point))
4091 (call-interactively command)
4092 (while (and (org-at-table-p)
4093 (org-at-table-hline-p))
4094 (call-interactively command))
4095 (or (org-at-table-p) (goto-char p))
4096 (move-marker pos (point))
4097 (select-window win)))
4099 (defun org-table-fedit-scroll (N)
4100 (interactive "p")
4101 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4102 (scroll-other-window N)))
4104 (defun org-table-fedit-scroll-down (N)
4105 (interactive "p")
4106 (org-table-fedit-scroll (- N)))
4108 (defvar org-table-rectangle-overlays nil)
4110 (defun org-table-add-rectangle-overlay (beg end &optional face)
4111 "Add a new overlay."
4112 (let ((ov (make-overlay beg end)))
4113 (overlay-put ov 'face (or face 'secondary-selection))
4114 (push ov org-table-rectangle-overlays)))
4116 (defun org-table-highlight-rectangle (&optional beg end face)
4117 "Highlight rectangular region in a table.
4118 When buffer positions BEG and END are provided, use them to
4119 delimit the region to highlight. Otherwise, refer to point. Use
4120 FACE, when non-nil, for the highlight."
4121 (let* ((beg (or beg (point)))
4122 (end (or end (point)))
4123 (b (min beg end))
4124 (e (max beg end))
4125 (start-coordinates
4126 (save-excursion
4127 (goto-char b)
4128 (cons (line-beginning-position) (org-table-current-column))))
4129 (end-coordinates
4130 (save-excursion
4131 (goto-char e)
4132 (cons (line-beginning-position) (org-table-current-column)))))
4133 (when (boundp 'org-show-positions)
4134 (setq org-show-positions (cons b (cons e org-show-positions))))
4135 (goto-char (car start-coordinates))
4136 (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
4137 (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
4138 (last-row (car end-coordinates)))
4139 (while (<= (point) last-row)
4140 (when (looking-at org-table-dataline-regexp)
4141 (org-table-goto-column column-start)
4142 (skip-chars-backward "^|\n")
4143 (let ((p (point)))
4144 (org-table-goto-column column-end)
4145 (skip-chars-forward "^|\n")
4146 (org-table-add-rectangle-overlay p (point) face)))
4147 (forward-line)))
4148 (goto-char (car start-coordinates)))
4149 (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
4151 (defun org-table-remove-rectangle-highlight (&rest ignore)
4152 "Remove the rectangle overlays."
4153 (unless org-inhibit-highlight-removal
4154 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4155 (mapc 'delete-overlay org-table-rectangle-overlays)
4156 (setq org-table-rectangle-overlays nil)))
4158 (defvar org-table-coordinate-overlays nil
4159 "Collects the coordinate grid overlays, so that they can be removed.")
4160 (make-variable-buffer-local 'org-table-coordinate-overlays)
4162 (defun org-table-overlay-coordinates ()
4163 "Add overlays to the table at point, to show row/column coordinates."
4164 (interactive)
4165 (mapc 'delete-overlay org-table-coordinate-overlays)
4166 (setq org-table-coordinate-overlays nil)
4167 (save-excursion
4168 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4169 (goto-char (org-table-begin))
4170 (while (org-at-table-p)
4171 (setq eol (point-at-eol))
4172 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4173 (push ov org-table-coordinate-overlays)
4174 (setq hline (looking-at org-table-hline-regexp))
4175 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4176 (format "%4d" (setq id (1+ id)))))
4177 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4178 (when hline
4179 (setq ic 0)
4180 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4181 (setq beg (1+ (match-beginning 0))
4182 ic (1+ ic)
4183 s1 (concat "$" (int-to-string ic))
4184 s2 (org-number-to-letters ic)
4185 str (if (eq org-table-use-standard-references t) s2 s1))
4186 (setq ov (make-overlay beg (+ beg (length str))))
4187 (push ov org-table-coordinate-overlays)
4188 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4189 (beginning-of-line 2)))))
4191 ;;;###autoload
4192 (defun org-table-toggle-coordinate-overlays ()
4193 "Toggle the display of Row/Column numbers in tables."
4194 (interactive)
4195 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4196 (message "Tables Row/Column numbers display turned %s"
4197 (if org-table-overlay-coordinates "on" "off"))
4198 (if (and (org-at-table-p) org-table-overlay-coordinates)
4199 (org-table-align))
4200 (unless org-table-overlay-coordinates
4201 (mapc 'delete-overlay org-table-coordinate-overlays)
4202 (setq org-table-coordinate-overlays nil)))
4204 ;;;###autoload
4205 (defun org-table-toggle-formula-debugger ()
4206 "Toggle the formula debugger in tables."
4207 (interactive)
4208 (setq org-table-formula-debug (not org-table-formula-debug))
4209 (message "Formula debugging has been turned %s"
4210 (if org-table-formula-debug "on" "off")))
4212 ;;; The orgtbl minor mode
4214 ;; Define a minor mode which can be used in other modes in order to
4215 ;; integrate the org-mode table editor.
4217 ;; This is really a hack, because the org-mode table editor uses several
4218 ;; keys which normally belong to the major mode, for example the TAB and
4219 ;; RET keys. Here is how it works: The minor mode defines all the keys
4220 ;; necessary to operate the table editor, but wraps the commands into a
4221 ;; function which tests if the cursor is currently inside a table. If that
4222 ;; is the case, the table editor command is executed. However, when any of
4223 ;; those keys is used outside a table, the function uses `key-binding' to
4224 ;; look up if the key has an associated command in another currently active
4225 ;; keymap (minor modes, major mode, global), and executes that command.
4226 ;; There might be problems if any of the keys used by the table editor is
4227 ;; otherwise used as a prefix key.
4229 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4230 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4231 ;; addresses this by checking explicitly for both bindings.
4233 ;; The optimized version (see variable `orgtbl-optimized') takes over
4234 ;; all keys which are bound to `self-insert-command' in the *global map*.
4235 ;; Some modes bind other commands to simple characters, for example
4236 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4237 ;; active, this binding is ignored inside tables and replaced with a
4238 ;; modified self-insert.
4241 (defvar orgtbl-mode-map (make-keymap)
4242 "Keymap for `orgtbl-mode'.")
4244 (defvar org-old-auto-fill-inhibit-regexp nil
4245 "Local variable used by `orgtbl-mode'.")
4247 (defconst orgtbl-line-start-regexp
4248 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4249 "Matches a line belonging to an orgtbl.")
4251 (defconst orgtbl-extra-font-lock-keywords
4252 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4253 0 (quote 'org-table) 'prepend))
4254 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4256 ;; Install it as a minor mode.
4257 (put 'orgtbl-mode :included t)
4258 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4260 ;;;###autoload
4261 (define-minor-mode orgtbl-mode
4262 "The `org-mode' table editor as a minor mode for use in other modes."
4263 :lighter " OrgTbl" :keymap orgtbl-mode-map
4264 (org-load-modules-maybe)
4265 (cond
4266 ((derived-mode-p 'org-mode)
4267 ;; Exit without error, in case some hook functions calls this
4268 ;; by accident in org-mode.
4269 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4270 (orgtbl-mode
4271 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4272 ;; Make sure we are first in minor-mode-map-alist
4273 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4274 ;; FIXME: maybe it should use emulation-mode-map-alists?
4275 (and c (setq minor-mode-map-alist
4276 (cons c (delq c minor-mode-map-alist)))))
4277 (org-set-local (quote org-table-may-need-update) t)
4278 (org-add-hook 'before-change-functions 'org-before-change-function
4279 nil 'local)
4280 (org-set-local 'org-old-auto-fill-inhibit-regexp
4281 auto-fill-inhibit-regexp)
4282 (org-set-local 'auto-fill-inhibit-regexp
4283 (if auto-fill-inhibit-regexp
4284 (concat orgtbl-line-start-regexp "\\|"
4285 auto-fill-inhibit-regexp)
4286 orgtbl-line-start-regexp))
4287 (add-to-invisibility-spec '(org-cwidth))
4288 (when (fboundp 'font-lock-add-keywords)
4289 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4290 (org-restart-font-lock))
4291 (easy-menu-add orgtbl-mode-menu))
4293 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4294 (org-table-cleanup-narrow-column-properties)
4295 (org-remove-from-invisibility-spec '(org-cwidth))
4296 (remove-hook 'before-change-functions 'org-before-change-function t)
4297 (when (fboundp 'font-lock-remove-keywords)
4298 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4299 (org-restart-font-lock))
4300 (easy-menu-remove orgtbl-mode-menu)
4301 (force-mode-line-update 'all))))
4303 (defun org-table-cleanup-narrow-column-properties ()
4304 "Remove all properties related to narrow-column invisibility."
4305 (let ((s (point-min)))
4306 (while (setq s (text-property-any s (point-max)
4307 'display org-narrow-column-arrow))
4308 (remove-text-properties s (1+ s) '(display t)))
4309 (setq s (point-min))
4310 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4311 (remove-text-properties s (1+ s) '(org-cwidth t)))
4312 (setq s (point-min))
4313 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4314 (remove-text-properties s (1+ s) '(invisible t)))))
4316 (defun orgtbl-make-binding (fun n &rest keys)
4317 "Create a function for binding in the table minor mode.
4318 FUN is the command to call inside a table. N is used to create a unique
4319 command name. KEYS are keys that should be checked in for a command
4320 to execute outside of tables."
4321 (eval
4322 (list 'defun
4323 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4324 '(arg)
4325 (concat "In tables, run `" (symbol-name fun) "'.\n"
4326 "Outside of tables, run the binding of `"
4327 (mapconcat #'key-description keys "' or `")
4328 "'.")
4329 '(interactive "p")
4330 (list 'if
4331 '(org-at-table-p)
4332 (list 'call-interactively (list 'quote fun))
4333 (list 'let '(orgtbl-mode)
4334 (list 'call-interactively
4335 (append '(or)
4336 (mapcar (lambda (k)
4337 (list 'key-binding k))
4338 keys)
4339 '('orgtbl-error))))))))
4341 (defun orgtbl-error ()
4342 "Error when there is no default binding for a table key."
4343 (interactive)
4344 (user-error "This key has no function outside tables"))
4346 (defun orgtbl-setup ()
4347 "Setup orgtbl keymaps."
4348 (let ((nfunc 0)
4349 (bindings
4350 '(([(meta shift left)] org-table-delete-column)
4351 ([(meta left)] org-table-move-column-left)
4352 ([(meta right)] org-table-move-column-right)
4353 ([(meta shift right)] org-table-insert-column)
4354 ([(meta shift up)] org-table-kill-row)
4355 ([(meta shift down)] org-table-insert-row)
4356 ([(meta up)] org-table-move-row-up)
4357 ([(meta down)] org-table-move-row-down)
4358 ("\C-c\C-w" org-table-cut-region)
4359 ("\C-c\M-w" org-table-copy-region)
4360 ("\C-c\C-y" org-table-paste-rectangle)
4361 ("\C-c\C-w" org-table-wrap-region)
4362 ("\C-c-" org-table-insert-hline)
4363 ("\C-c}" org-table-toggle-coordinate-overlays)
4364 ("\C-c{" org-table-toggle-formula-debugger)
4365 ("\C-m" org-table-next-row)
4366 ([(shift return)] org-table-copy-down)
4367 ("\C-c?" org-table-field-info)
4368 ("\C-c " org-table-blank-field)
4369 ("\C-c+" org-table-sum)
4370 ("\C-c=" org-table-eval-formula)
4371 ("\C-c'" org-table-edit-formulas)
4372 ("\C-c`" org-table-edit-field)
4373 ("\C-c*" org-table-recalculate)
4374 ("\C-c^" org-table-sort-lines)
4375 ("\M-a" org-table-beginning-of-field)
4376 ("\M-e" org-table-end-of-field)
4377 ([(control ?#)] org-table-rotate-recalc-marks)))
4378 elt key fun cmd)
4379 (while (setq elt (pop bindings))
4380 (setq nfunc (1+ nfunc))
4381 (setq key (org-key (car elt))
4382 fun (nth 1 elt)
4383 cmd (orgtbl-make-binding fun nfunc key))
4384 (org-defkey orgtbl-mode-map key cmd))
4386 ;; Special treatment needed for TAB and RET
4387 (org-defkey orgtbl-mode-map [(return)]
4388 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4389 (org-defkey orgtbl-mode-map "\C-m"
4390 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4392 (org-defkey orgtbl-mode-map [(tab)]
4393 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4394 (org-defkey orgtbl-mode-map "\C-i"
4395 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4397 (org-defkey orgtbl-mode-map [(shift tab)]
4398 (orgtbl-make-binding 'org-table-previous-field 104
4399 [(shift tab)] [(tab)] "\C-i"))
4402 (unless (featurep 'xemacs)
4403 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4404 (orgtbl-make-binding 'org-table-previous-field 107
4405 [S-iso-lefttab] [backtab] [(shift tab)]
4406 [(tab)] "\C-i")))
4408 (org-defkey orgtbl-mode-map [backtab]
4409 (orgtbl-make-binding 'org-table-previous-field 108
4410 [backtab] [S-iso-lefttab] [(shift tab)]
4411 [(tab)] "\C-i"))
4413 (org-defkey orgtbl-mode-map "\M-\C-m"
4414 (orgtbl-make-binding 'org-table-wrap-region 105
4415 "\M-\C-m" [(meta return)]))
4416 (org-defkey orgtbl-mode-map [(meta return)]
4417 (orgtbl-make-binding 'org-table-wrap-region 106
4418 [(meta return)] "\M-\C-m"))
4420 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4421 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4423 (when orgtbl-optimized
4424 ;; If the user wants maximum table support, we need to hijack
4425 ;; some standard editing functions
4426 (org-remap orgtbl-mode-map
4427 'self-insert-command 'orgtbl-self-insert-command
4428 'delete-char 'org-delete-char
4429 'delete-backward-char 'org-delete-backward-char)
4430 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4431 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4432 '("OrgTbl"
4433 ["Create or convert" org-table-create-or-convert-from-region
4434 :active (not (org-at-table-p)) :keys "C-c |" ]
4435 "--"
4436 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4437 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4438 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4439 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4440 "--"
4441 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4442 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4443 ["Copy Field from Above"
4444 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4445 "--"
4446 ("Column"
4447 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4448 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4449 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4450 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4451 ("Row"
4452 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4453 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4454 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4455 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4456 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4457 "--"
4458 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4459 ("Rectangle"
4460 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4461 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4462 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4463 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4464 "--"
4465 ("Radio tables"
4466 ["Insert table template" orgtbl-insert-radio-table
4467 (assq major-mode orgtbl-radio-table-templates)]
4468 ["Comment/uncomment table" orgtbl-toggle-comment t])
4469 "--"
4470 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4471 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4472 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4473 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4474 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4475 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4476 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4477 ["Sum Column/Rectangle" org-table-sum
4478 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4479 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4480 ["Debug Formulas"
4481 org-table-toggle-formula-debugger :active (org-at-table-p)
4482 :keys "C-c {"
4483 :style toggle :selected org-table-formula-debug]
4484 ["Show Col/Row Numbers"
4485 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4486 :keys "C-c }"
4487 :style toggle :selected org-table-overlay-coordinates]
4488 "--"
4489 ("Plot"
4490 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4491 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4494 (defun orgtbl-ctrl-c-ctrl-c (arg)
4495 "If the cursor is inside a table, realign the table.
4496 If it is a table to be sent away to a receiver, do it.
4497 With prefix arg, also recompute table."
4498 (interactive "P")
4499 (let ((case-fold-search t) (pos (point)) action)
4500 (save-excursion
4501 (beginning-of-line 1)
4502 (setq action (cond
4503 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4504 ((looking-at "[ \t]*|") pos)
4505 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4506 (cond
4507 ((integerp action)
4508 (goto-char action)
4509 (org-table-maybe-eval-formula)
4510 (if arg
4511 (call-interactively 'org-table-recalculate)
4512 (org-table-maybe-recalculate-line))
4513 (call-interactively 'org-table-align)
4514 (when (orgtbl-send-table 'maybe)
4515 (run-hooks 'orgtbl-after-send-table-hook)))
4516 ((eq action 'recalc)
4517 (save-excursion
4518 (beginning-of-line 1)
4519 (skip-chars-backward " \r\n\t")
4520 (if (org-at-table-p)
4521 (org-call-with-arg 'org-table-recalculate t))))
4522 (t (let (orgtbl-mode)
4523 (call-interactively (key-binding "\C-c\C-c")))))))
4525 (defun orgtbl-create-or-convert-from-region (arg)
4526 "Create table or convert region to table, if no conflicting binding.
4527 This installs the table binding `C-c |', but only if there is no
4528 conflicting binding to this key outside orgtbl-mode."
4529 (interactive "P")
4530 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4531 (if cmd
4532 (call-interactively cmd)
4533 (call-interactively 'org-table-create-or-convert-from-region))))
4535 (defun orgtbl-tab (arg)
4536 "Justification and field motion for `orgtbl-mode'."
4537 (interactive "P")
4538 (if arg (org-table-edit-field t)
4539 (org-table-justify-field-maybe)
4540 (org-table-next-field)))
4542 (defun orgtbl-ret ()
4543 "Justification and field motion for `orgtbl-mode'."
4544 (interactive)
4545 (if (bobp)
4546 (newline)
4547 (org-table-justify-field-maybe)
4548 (org-table-next-row)))
4550 (defun orgtbl-self-insert-command (N)
4551 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4552 If the cursor is in a table looking at whitespace, the whitespace is
4553 overwritten, and the table is not marked as requiring realignment."
4554 (interactive "p")
4555 (if (and (org-at-table-p)
4557 (and org-table-auto-blank-field
4558 (member last-command
4559 '(orgtbl-hijacker-command-100
4560 orgtbl-hijacker-command-101
4561 orgtbl-hijacker-command-102
4562 orgtbl-hijacker-command-103
4563 orgtbl-hijacker-command-104
4564 orgtbl-hijacker-command-105
4565 yas/expand))
4566 (org-table-blank-field))
4568 (eq N 1)
4569 (looking-at "[^|\n]* +|"))
4570 (let (org-table-may-need-update)
4571 (goto-char (1- (match-end 0)))
4572 (org-delete-backward-char 1)
4573 (goto-char (match-beginning 0))
4574 (self-insert-command N))
4575 (setq org-table-may-need-update t)
4576 (let* (orgtbl-mode
4578 (cmd (or (key-binding
4579 (or (and (listp function-key-map)
4580 (setq a (assoc last-input-event function-key-map))
4581 (cdr a))
4582 (vector last-input-event)))
4583 'self-insert-command)))
4584 (call-interactively cmd)
4585 (if (and org-self-insert-cluster-for-undo
4586 (eq cmd 'self-insert-command))
4587 (if (not (eq last-command 'orgtbl-self-insert-command))
4588 (setq org-self-insert-command-undo-counter 1)
4589 (if (>= org-self-insert-command-undo-counter 20)
4590 (setq org-self-insert-command-undo-counter 1)
4591 (and (> org-self-insert-command-undo-counter 0)
4592 buffer-undo-list
4593 (not (cadr buffer-undo-list)) ; remove nil entry
4594 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4595 (setq org-self-insert-command-undo-counter
4596 (1+ org-self-insert-command-undo-counter))))))))
4598 ;;;###autoload
4599 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4600 "Regular expression matching exponentials as produced by calc.")
4602 (defun orgtbl-gather-send-defs ()
4603 "Gather a plist of :name, :transform, :params for each destination before
4604 a radio table."
4605 (save-excursion
4606 (goto-char (org-table-begin))
4607 (let (rtn)
4608 (beginning-of-line 0)
4609 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4610 (let ((name (org-no-properties (match-string 1)))
4611 (transform (intern (match-string 2)))
4612 (params (if (match-end 3)
4613 (read (concat "(" (match-string 3) ")")))))
4614 (push (list :name name :transform transform :params params)
4615 rtn)
4616 (beginning-of-line 0)))
4617 rtn)))
4619 (defun orgtbl-send-replace-tbl (name txt)
4620 "Find and replace table NAME with TXT."
4621 (save-excursion
4622 (goto-char (point-min))
4623 (unless (re-search-forward
4624 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4625 (user-error "Don't know where to insert translated table"))
4626 (let ((beg (line-beginning-position 2)))
4627 (unless (re-search-forward
4628 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4629 (user-error "Cannot find end of insertion region"))
4630 (beginning-of-line)
4631 (delete-region beg (point)))
4632 (insert txt "\n")))
4634 ;;;###autoload
4635 (defun org-table-to-lisp (&optional txt)
4636 "Convert the table at point to a Lisp structure.
4637 The structure will be a list. Each item is either the symbol `hline'
4638 for a horizontal separator line, or a list of field values as strings.
4639 The table is taken from the parameter TXT, or from the buffer at point."
4640 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4641 (let ((txt (or txt
4642 (buffer-substring-no-properties (org-table-begin)
4643 (org-table-end)))))
4644 (mapcar (lambda (x)
4645 (if (string-match org-table-hline-regexp x) 'hline
4646 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4647 (org-split-string txt "[ \t]*\n[ \t]*"))))
4649 (defun orgtbl-send-table (&optional maybe)
4650 "Send a transformed version of table at point to the receiver position.
4651 With argument MAYBE, fail quietly if no transformation is defined
4652 for this table."
4653 (interactive)
4654 (catch 'exit
4655 (unless (org-at-table-p) (user-error "Not at a table"))
4656 ;; when non-interactive, we assume align has just happened.
4657 (when (org-called-interactively-p 'any) (org-table-align))
4658 (let ((dests (orgtbl-gather-send-defs))
4659 (table (org-table-to-lisp
4660 (buffer-substring-no-properties (org-table-begin)
4661 (org-table-end))))
4662 (ntbl 0))
4663 (unless dests
4664 (if maybe (throw 'exit nil)
4665 (user-error "Don't know how to transform this table")))
4666 (dolist (dest dests)
4667 (let ((name (plist-get dest :name))
4668 (transform (plist-get dest :transform))
4669 (params (plist-get dest :params)))
4670 (unless (fboundp transform)
4671 (user-error "No such transformation function %s" transform))
4672 (orgtbl-send-replace-tbl name (funcall transform table params)))
4673 (incf ntbl))
4674 (message "Table converted and installed at %d receiver location%s"
4675 ntbl (if (> ntbl 1) "s" ""))
4676 (and (> ntbl 0) ntbl))))
4678 (defun org-remove-by-index (list indices &optional i0)
4679 "Remove the elements in LIST with indices in INDICES.
4680 First element has index 0, or I0 if given."
4681 (if (not indices)
4682 list
4683 (if (integerp indices) (setq indices (list indices)))
4684 (setq i0 (1- (or i0 0)))
4685 (delq :rm (mapcar (lambda (x)
4686 (setq i0 (1+ i0))
4687 (if (memq i0 indices) :rm x))
4688 list))))
4690 (defun orgtbl-toggle-comment ()
4691 "Comment or uncomment the orgtbl at point."
4692 (interactive)
4693 (let* ((case-fold-search t)
4694 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4695 (re2 (concat "^" orgtbl-line-start-regexp))
4696 (commented (save-excursion (beginning-of-line 1)
4697 (cond ((looking-at re1) t)
4698 ((looking-at re2) nil)
4699 (t (user-error "Not at an org table")))))
4700 (re (if commented re1 re2))
4701 beg end)
4702 (save-excursion
4703 (beginning-of-line 1)
4704 (while (looking-at re) (beginning-of-line 0))
4705 (beginning-of-line 2)
4706 (setq beg (point))
4707 (while (looking-at re) (beginning-of-line 2))
4708 (setq end (point)))
4709 (comment-region beg end (if commented '(4) nil))))
4711 (defun orgtbl-insert-radio-table ()
4712 "Insert a radio table template appropriate for this major mode."
4713 (interactive)
4714 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4715 (txt (nth 1 e))
4716 name pos)
4717 (unless e (user-error "No radio table setup defined for %s" major-mode))
4718 (setq name (read-string "Table name: "))
4719 (while (string-match "%n" txt)
4720 (setq txt (replace-match name t t txt)))
4721 (or (bolp) (insert "\n"))
4722 (setq pos (point))
4723 (insert txt)
4724 (goto-char pos)))
4726 ;;;###autoload
4727 (defun orgtbl-to-generic (table params)
4728 "Convert the orgtbl-mode TABLE to some other format.
4730 This generic routine can be used for many standard cases.
4732 TABLE is a list, each entry either the symbol `hline' for
4733 a horizontal separator line, or a list of fields for that
4734 line. PARAMS is a property list of parameters that can
4735 influence the conversion.
4737 Valid parameters are:
4739 :backend, :raw
4741 Export back-end used as a basis to transcode elements of the
4742 table, when no specific parameter applies to it. It is also
4743 used to translate cells contents. You can prevent this by
4744 setting :raw property to a non-nil value.
4746 :splice
4748 When non-nil, only convert rows, not the table itself. This is
4749 equivalent to setting to the empty string both :tstart
4750 and :tend, which see.
4752 :skip
4754 When set to an integer N, skip the first N lines of the table.
4755 Horizontal separation lines do count for this parameter!
4757 :skipcols
4759 List of columns that should be skipped. If the table has
4760 a column with calculation marks, that column is automatically
4761 discarded beforehand.
4763 :hline
4765 String to be inserted on horizontal separation lines. May be
4766 nil to ignore these lines altogether.
4768 :sep
4770 Separator between two fields, as a string.
4772 Each in the following group may be either a string or a function
4773 of no arguments returning a string:
4775 :tstart, :tend
4777 Strings to start and end the table. Ignored when :splice is t.
4779 :lstart, :lend
4781 Strings to start and end a new table line.
4783 :llstart, :llend
4785 Strings to start and end the last table line. Default,
4786 respectively, to :lstart and :lend.
4788 Each in the following group may be a string or a function of one
4789 argument (either the cells in the current row, as a list of
4790 strings, or the current cell) returning a string:
4792 :lfmt
4794 Format string for an entire row, with enough %s to capture all
4795 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4797 :llfmt
4799 Format for the entire last line, defaults to :lfmt.
4801 :fmt
4803 A format to be used to wrap the field, should contain %s for
4804 the original field value. For example, to wrap everything in
4805 dollars, you could use :fmt \"$%s$\". This may also be
4806 a property list with column numbers and format strings, or
4807 functions, e.g.,
4809 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4811 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4813 Same as above, specific for the header lines in the table.
4814 All lines before the first hline are treated as header. If
4815 any of these is not present, the data line value is used.
4817 This may be either a string or a function of two arguments:
4819 :efmt
4821 Use this format to print numbers with exponential. The format
4822 should have %s twice for inserting mantissa and exponent, for
4823 example \"%s\\\\times10^{%s}\". This may also be a property
4824 list with column numbers and format strings or functions.
4825 :fmt will still be applied after :efmt."
4826 ;; Make sure `org-export-create-backend' is available.
4827 (require 'ox)
4828 (let* ((backend (plist-get params :backend))
4829 (custom-backend
4830 ;; Build a custom back-end according to PARAMS. Before
4831 ;; defining a translator, check if there is anything to do.
4832 ;; When there isn't, let BACKEND handle the element.
4833 (org-export-create-backend
4834 :parent (or backend 'org)
4835 :transcoders
4836 `((table . ,(org-table--to-generic-table params))
4837 (table-row . ,(org-table--to-generic-row params))
4838 (table-cell . ,(org-table--to-generic-cell params))
4839 ;; Macros are not going to be expanded. However, no
4840 ;; regular back-end has a transcoder for them. We
4841 ;; provide one so they are not ignored, but displayed
4842 ;; as-is instead.
4843 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4844 data info)
4845 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4846 ;; Initialize communication channel in INFO.
4847 (with-temp-buffer
4848 (let ((org-inhibit-startup t)) (org-mode))
4849 (let ((standard-output (current-buffer)))
4850 (dolist (e table)
4851 (cond ((eq e 'hline) (princ "|--\n"))
4852 ((consp e)
4853 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4854 (princ "\n")))))
4855 (setq data
4856 (org-element-map (org-element-parse-buffer) 'table
4857 #'identity nil t))
4858 (setq info (org-export-get-environment backend nil params)))
4859 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4860 (user-error "Unknown :backend value"))
4861 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4862 ;; Handle :skip parameter.
4863 (let ((skip (plist-get info :skip)))
4864 (when skip
4865 (unless (wholenump skip) (user-error "Wrong :skip value"))
4866 (let ((n 0))
4867 (org-element-map data 'table-row
4868 (lambda (row)
4869 (if (>= n skip) t
4870 (org-element-extract-element row)
4871 (incf n)
4872 nil))
4873 nil t))))
4874 ;; Handle :skipcols parameter.
4875 (let ((skipcols (plist-get info :skipcols)))
4876 (when skipcols
4877 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4878 (org-element-map data 'table
4879 (lambda (table)
4880 (let ((specialp (org-export-table-has-special-column-p table)))
4881 (dolist (row (org-element-contents table))
4882 (when (eq (org-element-property :type row) 'standard)
4883 (let ((c 1))
4884 (dolist (cell (nthcdr (if specialp 1 0)
4885 (org-element-contents row)))
4886 (when (memq c skipcols)
4887 (org-element-extract-element cell))
4888 (incf c))))))))))
4889 ;; Since we are going to export using a low-level mechanism,
4890 ;; ignore special column and special rows manually.
4891 (let ((special? (org-export-table-has-special-column-p data))
4892 ignore)
4893 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4894 (lambda (datum)
4895 (when (if (eq (org-element-type datum) 'table-row)
4896 (org-export-table-row-is-special-p datum nil)
4897 (org-export-first-sibling-p datum nil))
4898 (push datum ignore))))
4899 (setq info (plist-put info :ignore-list ignore)))
4900 ;; We use a low-level mechanism to export DATA so as to skip all
4901 ;; usual pre-processing and post-processing, i.e., hooks, filters,
4902 ;; Babel code evaluation, include keywords and macro expansion,
4903 ;; and filters.
4904 (let ((output (org-export-data-with-backend data custom-backend info)))
4905 ;; Remove final newline.
4906 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4908 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4909 (cond ((null value) nil)
4910 ((functionp value) `(funcall ',value ,@args))
4911 ((stringp value)
4912 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4913 (args `(format ,value ,@args))
4914 (t value)))
4915 ((and with-cons (consp value))
4916 `(let ((val (cadr (memq column ',value))))
4917 (cond ((null val) contents)
4918 ((stringp val) (format val ,@args))
4919 ((functionp val) (funcall val ,@args))
4920 (t (user-error "Wrong %s value" ,name)))))
4921 (t (user-error "Wrong %s value" name))))
4923 (defun org-table--to-generic-table (params)
4924 "Return custom table transcoder according to PARAMS.
4925 PARAMS is a plist. See `orgtbl-to-generic' for more
4926 information."
4927 (let ((backend (plist-get params :backend))
4928 (splice (plist-get params :splice))
4929 (tstart (plist-get params :tstart))
4930 (tend (plist-get params :tend)))
4931 `(lambda (table contents info)
4932 (concat
4933 ,(and tstart (not splice)
4934 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4935 ,(if (or (not backend) tstart tend splice) 'contents
4936 `(org-export-with-backend ',backend table contents info))
4937 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4939 (defun org-table--to-generic-row (params)
4940 "Return custom table row transcoder according to PARAMS.
4941 PARAMS is a plist. See `orgtbl-to-generic' for more
4942 information."
4943 (let* ((backend (plist-get params :backend))
4944 (lstart (plist-get params :lstart))
4945 (llstart (plist-get params :llstart))
4946 (hlstart (plist-get params :hlstart))
4947 (hllstart (plist-get params :hllstart))
4948 (lend (plist-get params :lend))
4949 (llend (plist-get params :llend))
4950 (hlend (plist-get params :hlend))
4951 (hllend (plist-get params :hllend))
4952 (lfmt (plist-get params :lfmt))
4953 (llfmt (plist-get params :llfmt))
4954 (hlfmt (plist-get params :hlfmt))
4955 (hllfmt (plist-get params :hllfmt)))
4956 `(lambda (row contents info)
4957 (if (eq (org-element-property :type row) 'rule)
4958 ,(cond
4959 ((plist-member params :hline)
4960 (org-table--generic-apply (plist-get params :hline) ":hline"))
4961 (backend `(org-export-with-backend ',backend row nil info)))
4962 (let ((headerp (org-export-table-row-in-header-p row info))
4963 (lastp (not (org-export-get-next-element row info)))
4964 (last-header-p (org-export-table-row-ends-header-p row info)))
4965 (when contents
4966 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4967 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4968 ;; `:lstart', `:lend' and their relatives.
4969 ,(let ((cells
4970 '(org-element-map row 'table-cell
4971 (lambda (cell)
4972 ;; Export all cells, without separators.
4974 ;; Use `org-export-data-with-backend'
4975 ;; instead of `org-export-data' to eschew
4976 ;; cached values, which
4977 ;; ignore :orgtbl-ignore-sep parameter.
4978 (org-export-data-with-backend
4979 cell
4980 (plist-get info :back-end)
4981 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4982 info)))
4983 `(cond
4984 ,(and hllfmt
4985 `(last-header-p ,(org-table--generic-apply
4986 hllfmt ":hllfmt" nil cells)))
4987 ,(and hlfmt
4988 `(headerp ,(org-table--generic-apply
4989 hlfmt ":hlfmt" nil cells)))
4990 ,(and llfmt
4991 `(lastp ,(org-table--generic-apply
4992 llfmt ":llfmt" nil cells)))
4994 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4995 `(concat
4996 (cond
4997 ,(and
4998 (or hllstart hllend)
4999 `(last-header-p
5000 (concat
5001 ,(org-table--generic-apply hllstart ":hllstart")
5002 contents
5003 ,(org-table--generic-apply hllend ":hllend"))))
5004 ,(and
5005 (or hlstart hlend)
5006 `(headerp
5007 (concat
5008 ,(org-table--generic-apply hlstart ":hlstart")
5009 contents
5010 ,(org-table--generic-apply hlend ":hlend"))))
5011 ,(and
5012 (or llstart llend)
5013 `(lastp
5014 (concat
5015 ,(org-table--generic-apply llstart ":llstart")
5016 contents
5017 ,(org-table--generic-apply llend ":llend"))))
5019 ,(cond
5020 ((or lstart lend)
5021 `(concat
5022 ,(org-table--generic-apply lstart ":lstart")
5023 contents
5024 ,(org-table--generic-apply lend ":lend")))
5025 (backend
5026 `(org-export-with-backend
5027 ',backend row contents info))
5028 (t 'contents)))))))))))))))
5030 (defun org-table--to-generic-cell (params)
5031 "Return custom table cell transcoder according to PARAMS.
5032 PARAMS is a plist. See `orgtbl-to-generic' for more
5033 information."
5034 (let* ((backend (plist-get params :backend))
5035 (efmt (plist-get params :efmt))
5036 (fmt (plist-get params :fmt))
5037 (hfmt (plist-get params :hfmt))
5038 (sep (plist-get params :sep))
5039 (hsep (plist-get params :hsep)))
5040 `(lambda (cell contents info)
5041 (let ((headerp (org-export-table-row-in-header-p
5042 (org-export-get-parent-element cell) info))
5043 (column (1+ (cdr (org-export-table-cell-address cell info)))))
5044 ;; Make sure that contents are exported as Org data when :raw
5045 ;; parameter is non-nil.
5046 ,(when (and backend (plist-get params :raw))
5047 `(setq contents
5048 ;; Since we don't know what are the pseudo object
5049 ;; types defined in backend, we cannot pass them to
5050 ;; `org-element-interpret-data'. As a consequence,
5051 ;; they will be treated as pseudo elements, and
5052 ;; will have newlines appended instead of spaces.
5053 ;; Therefore, we must make sure :post-blank value
5054 ;; is really turned into spaces.
5055 (replace-regexp-in-string
5056 "\n" " "
5057 (org-trim
5058 (org-element-interpret-data
5059 (org-element-contents cell))))))
5060 (when contents
5061 ;; Check if we can apply `:efmt' on CONTENTS.
5062 ,(when efmt
5063 `(when (string-match orgtbl-exp-regexp contents)
5064 (let ((mantissa (match-string 1 contents))
5065 (exponent (match-string 2 contents)))
5066 (setq contents ,(org-table--generic-apply
5067 efmt ":efmt" t 'mantissa 'exponent)))))
5068 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5069 (cond
5070 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5071 hfmt ":hfmt" t 'contents))))
5072 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5073 fmt ":fmt" t 'contents))))))
5074 ;; If a separator is provided, use it instead of BACKEND's.
5075 ;; Separators are ignored when LFMT (or equivalent) is
5076 ;; provided.
5077 ,(cond
5078 ((or hsep sep)
5079 `(if (or ,(and (not sep) '(not headerp))
5080 (plist-get info :orgtbl-ignore-sep)
5081 (not (org-export-get-next-element cell info)))
5082 ,(if (not backend) 'contents
5083 `(org-export-with-backend ',backend cell contents info))
5084 (concat contents
5085 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5086 (or hsep sep)))))
5087 (backend `(org-export-with-backend ',backend cell contents info))
5088 (t 'contents))))))
5090 ;;;###autoload
5091 (defun orgtbl-to-tsv (table params)
5092 "Convert the orgtbl-mode table to TAB separated material."
5093 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5095 ;;;###autoload
5096 (defun orgtbl-to-csv (table params)
5097 "Convert the orgtbl-mode table to CSV material.
5098 This does take care of the proper quoting of fields with comma or quotes."
5099 (orgtbl-to-generic table
5100 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5101 params)))
5103 ;;;###autoload
5104 (defun orgtbl-to-latex (table params)
5105 "Convert the orgtbl-mode TABLE to LaTeX.
5107 TABLE is a list, each entry either the symbol `hline' for
5108 a horizontal separator line, or a list of fields for that line.
5109 PARAMS is a property list of parameters that can influence the
5110 conversion. All parameters from `orgtbl-to-generic' are
5111 supported. It is also possible to use the following ones:
5113 :booktabs
5115 When non-nil, use formal \"booktabs\" style.
5117 :environment
5119 Specify environment to use, as a string. If you use
5120 \"longtable\", you may also want to specify :language property,
5121 as a string, to get proper continuation strings."
5122 (require 'ox-latex)
5123 (orgtbl-to-generic
5124 table
5125 (org-combine-plists
5126 ;; Provide sane default values.
5127 (list :backend 'latex
5128 :latex-default-table-mode 'table
5129 :latex-tables-centered nil
5130 :latex-tables-booktabs (plist-get params :booktabs)
5131 :latex-table-scientific-notation nil
5132 :latex-default-table-environment
5133 (or (plist-get params :environment) "tabular"))
5134 params)))
5136 ;;;###autoload
5137 (defun orgtbl-to-html (table params)
5138 "Convert the orgtbl-mode TABLE to HTML.
5140 TABLE is a list, each entry either the symbol `hline' for
5141 a horizontal separator line, or a list of fields for that line.
5142 PARAMS is a property list of parameters that can influence the
5143 conversion. All parameters from `orgtbl-to-generic' are
5144 supported. It is also possible to use the following one:
5146 :attributes
5148 Attributes and values, as a plist, which will be used in
5149 <table> tag."
5150 (require 'ox-html)
5151 (orgtbl-to-generic
5152 table
5153 (org-combine-plists
5154 ;; Provide sane default values.
5155 (list :backend 'html
5156 :html-table-data-tags '("<td%s>" . "</td>")
5157 :html-table-use-header-tags-for-first-column nil
5158 :html-table-align-individual-fields t
5159 :html-table-row-tags '("<tr>" . "</tr>")
5160 :html-table-attributes
5161 (if (plist-member params :attributes)
5162 (plist-get params :attributes)
5163 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5164 :frame "hsides")))
5165 params)))
5167 ;;;###autoload
5168 (defun orgtbl-to-texinfo (table params)
5169 "Convert the orgtbl-mode TABLE to Texinfo.
5171 TABLE is a list, each entry either the symbol `hline' for
5172 a horizontal separator line, or a list of fields for that line.
5173 PARAMS is a property list of parameters that can influence the
5174 conversion. All parameters from `orgtbl-to-generic' are
5175 supported. It is also possible to use the following one:
5177 :columns
5179 Column widths, as a string. When providing column fractions,
5180 \"@columnfractions\" command can be omitted."
5181 (require 'ox-texinfo)
5182 (let ((output
5183 (orgtbl-to-generic
5184 table
5185 (org-combine-plists
5186 (list :backend 'texinfo
5187 :texinfo-tables-verbatim nil
5188 :texinfo-table-scientific-notation nil)
5189 params)))
5190 (columns (let ((w (plist-get params :columns)))
5191 (cond ((not w) nil)
5192 ((org-string-match-p "{\\|@columnfractions " w) w)
5193 (t (concat "@columnfractions " w))))))
5194 (if (not columns) output
5195 (replace-regexp-in-string
5196 "@multitable \\(.*\\)" columns output t nil 1))))
5198 ;;;###autoload
5199 (defun orgtbl-to-orgtbl (table params)
5200 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5202 TABLE is a list, each entry either the symbol `hline' for
5203 a horizontal separator line, or a list of fields for that line.
5204 PARAMS is a property list of parameters that can influence the
5205 conversion. All parameters from `orgtbl-to-generic' are
5206 supported.
5208 Useful when slicing one table into many. The :hline, :sep,
5209 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5210 be set to provide ORGTBL directives for the generated table."
5211 (require 'ox-org)
5212 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5214 (defun orgtbl-to-table.el (table params)
5215 "Convert the orgtbl-mode TABLE into a table.el table.
5216 TABLE is a list, each entry either the symbol `hline' for
5217 a horizontal separator line, or a list of fields for that line.
5218 PARAMS is a property list of parameters that can influence the
5219 conversion. All parameters from `orgtbl-to-generic' are
5220 supported."
5221 (with-temp-buffer
5222 (insert (orgtbl-to-orgtbl table params))
5223 (org-table-align)
5224 (replace-regexp-in-string
5225 "-|" "-+"
5226 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5228 (defun orgtbl-to-unicode (table params)
5229 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5231 TABLE is a list, each entry either the symbol `hline' for
5232 a horizontal separator line, or a list of fields for that line.
5233 PARAMS is a property list of parameters that can influence the
5234 conversion. All parameters from `orgtbl-to-generic' are
5235 supported. It is also possible to use the following ones:
5237 :ascii-art
5239 When non-nil, use \"ascii-art-to-unicode\" package to translate
5240 the table. You can download it here:
5241 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5243 :narrow
5245 When non-nil, narrow columns width than provided width cookie,
5246 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5247 (require 'ox-ascii)
5248 (orgtbl-to-generic
5249 table
5250 (org-combine-plists
5251 (list :backend 'ascii
5252 :ascii-charset 'utf-8
5253 :ascii-table-widen-columns (not (plist-get params :narrow))
5254 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5255 params)))
5257 ;; Put the cursor in a column containing numerical values
5258 ;; of an Org-Mode table,
5259 ;; type C-c " a
5260 ;; A new column is added with a bar plot.
5261 ;; When the table is refreshed (C-u C-c *),
5262 ;; the plot is updated to reflect the new values.
5264 (defun orgtbl-ascii-draw (value min max &optional width characters)
5265 "Draw an ascii bar in a table.
5266 VALUE is a the value to plot, the width of the bar to draw. A
5267 value equal to MIN will be displayed as empty (zero width bar).
5268 A value equal to MAX will draw a bar filling all the WIDTH.
5269 WIDTH is the expected width in characters of the column.
5270 CHARACTERS is a string that will compose the bar, with shades of
5271 grey from pure white to pure black. It defaults to a 10
5272 characters string of regular ascii characters."
5273 (let* ((characters (or characters " .:;c!lhVHW"))
5274 (width (or width 12))
5275 (value (if (numberp value) value (string-to-number value)))
5276 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5277 (cond
5278 ((< value 0) "too small")
5279 ((> value width) "too large")
5281 (let ((len (1- (length characters))))
5282 (concat
5283 (make-string (floor value) (elt characters len))
5284 (string (elt characters
5285 (floor (* (- value (floor value)) len))))))))))
5287 ;;;###autoload
5288 (defun orgtbl-ascii-plot (&optional ask)
5289 "Draw an ascii bar plot in a column.
5290 With cursor in a column containing numerical values, this
5291 function will draw a plot in a new column.
5292 ASK, if given, is a numeric prefix to override the default 12
5293 characters width of the plot. ASK may also be the
5294 \\[universal-argument] prefix, which will prompt for the width."
5295 (interactive "P")
5296 (let ((col (org-table-current-column))
5297 (min 1e999) ; 1e999 will be converted to infinity
5298 (max -1e999) ; which is the desired result
5299 (table (org-table-to-lisp))
5300 (length
5301 (cond ((consp ask)
5302 (read-number "Length of column " 12))
5303 ((numberp ask) ask)
5304 (t 12))))
5305 ;; Skip any hline a the top of table.
5306 (while (eq (car table) 'hline) (setq table (cdr table)))
5307 ;; Skip table header if any.
5308 (dolist (x (or (cdr (memq 'hline table)) table))
5309 (when (consp x)
5310 (setq x (nth (1- col) x))
5311 (when (string-match
5312 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5314 (setq x (string-to-number x))
5315 (when (> min x) (setq min x))
5316 (when (< max x) (setq max x)))))
5317 (org-table-insert-column)
5318 (org-table-move-column-right)
5319 (org-table-store-formulas
5320 (cons
5321 (cons
5322 (concat "$" (number-to-string (1+ col)))
5323 (format "'(%s $%s %s %s %s)"
5324 "orgtbl-ascii-draw" col min max length))
5325 (org-table-get-stored-formulas)))
5326 (org-table-recalculate t)))
5328 ;; Example of extension: unicode characters
5329 ;; Here are two examples of different styles.
5331 ;; Unicode block characters are used to give a smooth effect.
5332 ;; See http://en.wikipedia.org/wiki/Block_Elements
5333 ;; Use one of those drawing functions
5334 ;; - orgtbl-ascii-draw (the default ascii)
5335 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5336 ;; - orgtbl-uc-draw-cont (smooth unicode)
5338 ;; This is best viewed with the "DejaVu Sans Mono" font
5339 ;; (use M-x set-default-font).
5341 (defun orgtbl-uc-draw-grid (value min max &optional width)
5342 "Draw a bar in a table using block unicode characters.
5343 It is a variant of orgtbl-ascii-draw with Unicode block
5344 characters, for a smooth display. Bars appear as grids (to the
5345 extent the font allows)."
5346 ;; http://en.wikipedia.org/wiki/Block_Elements
5347 ;; best viewed with the "DejaVu Sans Mono" font.
5348 (orgtbl-ascii-draw value min max width
5349 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5351 (defun orgtbl-uc-draw-cont (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 are solid (to the extent
5355 the font allows)."
5356 (orgtbl-ascii-draw value min max width
5357 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5359 (defun org-table-get-remote-range (name-or-id form)
5360 "Get a field value or a list of values in a range from table at ID.
5362 NAME-OR-ID may be the name of a table in the current file as set
5363 by a \"#+NAME:\" directive. The first table following this line
5364 will then be used. Alternatively, it may be an ID referring to
5365 any entry, also in a different file. In this case, the first
5366 table in that entry will be referenced.
5367 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5368 \"@I$2..@II$2\". All the references must be absolute, not relative.
5370 The return value is either a single string for a single field, or a
5371 list of the fields in the rectangle."
5372 (save-match-data
5373 (let ((case-fold-search t) (id-loc nil)
5374 ;; Protect a bunch of variables from being overwritten by
5375 ;; the context of the remote table.
5376 org-table-column-names org-table-column-name-regexp
5377 org-table-local-parameters org-table-named-field-locations
5378 org-table-current-line-types
5379 org-table-current-begin-pos org-table-dlines
5380 org-table-current-ncol
5381 org-table-hlines org-table-last-alignment
5382 org-table-last-column-widths org-table-last-alignment
5383 org-table-last-column-widths
5384 buffer loc)
5385 (setq form (org-table-convert-refs-to-rc form))
5386 (org-with-wide-buffer
5387 (goto-char (point-min))
5388 (if (re-search-forward
5389 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5390 (regexp-quote name-or-id) "[ \t]*$")
5391 nil t)
5392 (setq buffer (current-buffer) loc (match-beginning 0))
5393 (setq id-loc (org-id-find name-or-id 'marker))
5394 (unless (and id-loc (markerp id-loc))
5395 (user-error "Can't find remote table \"%s\"" name-or-id))
5396 (setq buffer (marker-buffer id-loc)
5397 loc (marker-position id-loc))
5398 (move-marker id-loc nil))
5399 (with-current-buffer buffer
5400 (org-with-wide-buffer
5401 (goto-char loc)
5402 (forward-char 1)
5403 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5404 (not (match-beginning 1)))
5405 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5406 (org-table-analyze)
5407 (setq form (org-table-formula-substitute-names
5408 (org-table-formula-handle-first/last-rc form)))
5409 (if (and (string-match org-table-range-regexp form)
5410 (> (length (match-string 0 form)) 1))
5411 (org-table-get-range
5412 (match-string 0 form) org-table-current-begin-pos 1)
5413 form)))))))
5415 (defun org-table-remote-reference-indirection (form)
5416 "Return formula with table remote references substituted by indirection.
5417 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5418 This indirection works only with the format @ROW$COLUMN. The
5419 format \"B3\" is not supported because it can not be
5420 distinguished from a plain table name or ID."
5421 (let ((regexp
5422 ;; Same as in `org-table-eval-formula'.
5423 (concat "\\<remote([ \t]*\\("
5424 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5425 "[@$][^ \t,]+"
5426 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5427 (replace-regexp-in-string
5428 regexp
5429 (lambda (m)
5430 (save-match-data
5431 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5432 (org-table-get-range
5433 (if (org-string-match-p "\\`\\$[0-9]+\\'" eq)
5434 (concat "@0" eq)
5435 eq)))))
5436 form t t 1)))
5438 (defmacro org-define-lookup-function (mode)
5439 (let ((mode-str (symbol-name mode))
5440 (first-p (equal mode 'first))
5441 (all-p (equal mode 'all)))
5442 (let ((plural-str (if all-p "s" "")))
5443 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5444 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5445 If R-LIST is nil, return matching element%s of S-LIST.
5446 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5447 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5448 This function is generated by a call to the macro `org-define-lookup-function'."
5449 mode-str plural-str plural-str plural-str)
5450 (let ,(let ((lvars '((p (or predicate 'equal))
5451 (sl s-list)
5452 (rl (or r-list s-list))
5453 (ret nil))))
5454 (if first-p (add-to-list 'lvars '(match-p nil)))
5455 lvars)
5456 (while ,(if first-p '(and (not match-p) sl) 'sl)
5457 (progn
5458 (if (funcall p val (car sl))
5459 (progn
5460 ,(if first-p '(setq match-p t))
5461 (let ((rval (car rl)))
5462 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5463 (setq sl (cdr sl) rl (cdr rl))))
5464 ret)))))
5466 (org-define-lookup-function first)
5467 (org-define-lookup-function last)
5468 (org-define-lookup-function all)
5470 (provide 'org-table)
5472 ;; Local variables:
5473 ;; generated-autoload-file: "org-loaddefs.el"
5474 ;; End:
5476 ;;; org-table.el ends here