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