Merge branch 'maint'
[org-mode.git] / lisp / org-table.el
blob832371d9023a79a7d255f3051f1da91587274412
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2013 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-table-clean-before-export "org-exp"
42 (lines &optional maybe-quoted))
43 (declare-function org-format-org-table-html "org-html" (lines &optional splice))
44 (declare-function aa2u "ext:ascii-art-to-unicode" ())
45 (defvar orgtbl-mode) ; defined below
46 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
47 (defvar org-export-html-table-tag) ; defined in org-exp.el
48 (defvar constants-unit-system)
49 (defvar org-table-follow-field-mode)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, otherwise, if table is not sent, the functions
55 are not run.")
57 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
58 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
59 In the optimized version, the table editor takes over all simple keys that
60 normally just insert a character. In tables, the characters are inserted
61 in a way to minimize disturbing the table structure (i.e. in overwrite mode
62 for empty fields). Outside tables, the correct binding of the keys is
63 restored.
65 The default for this option is t if the optimized version is also used in
66 Org-mode. See the variable `org-enable-table-editor' for details. Changing
67 this variable requires a restart of Emacs to become effective."
68 :group 'org-table
69 :type 'boolean)
71 (defcustom orgtbl-radio-table-templates
72 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
73 % END RECEIVE ORGTBL %n
74 \\begin{comment}
75 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
76 | | |
77 \\end{comment}\n")
78 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
79 @c END RECEIVE ORGTBL %n
80 @ignore
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 | | |
83 @end ignore\n")
84 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
85 <!-- END RECEIVE ORGTBL %n -->
86 <!--
87 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
88 | | |
89 -->\n")
90 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
91 #+ END RECEIVE ORGTBL %n
93 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
94 | | |
95 "))
96 "Templates for radio tables in different major modes.
97 All occurrences of %n in a template will be replaced with the name of the
98 table, obtained by prompting the user."
99 :group 'org-table
100 :type '(repeat
101 (list (symbol :tag "Major mode")
102 (string :tag "Format"))))
104 (defgroup org-table-settings nil
105 "Settings for tables in Org-mode."
106 :tag "Org Table Settings"
107 :group 'org-table)
109 (defcustom org-table-default-size "5x2"
110 "The default size for newly created tables, Columns x Rows."
111 :group 'org-table-settings
112 :type 'string)
114 (defcustom org-table-number-regexp
115 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
116 "Regular expression for recognizing numbers in table columns.
117 If a table column contains mostly numbers, it will be aligned to the
118 right. If not, it will be aligned to the left.
120 The default value of this option is a regular expression which allows
121 anything which looks remotely like a number as used in scientific
122 context. For example, all of the following will be considered a
123 number:
124 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
126 Other options offered by the customize interface are more restrictive."
127 :group 'org-table-settings
128 :type '(choice
129 (const :tag "Positive Integers"
130 "^[0-9]+$")
131 (const :tag "Integers"
132 "^[-+]?[0-9]+$")
133 (const :tag "Floating Point Numbers"
134 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
135 (const :tag "Floating Point Number or Integer"
136 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
137 (const :tag "Exponential, Floating point, Integer"
138 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
139 (const :tag "Very General Number-Like, including hex and Calc radix"
140 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
141 (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
142 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
143 (string :tag "Regexp:")))
145 (defcustom org-table-number-fraction 0.5
146 "Fraction of numbers in a column required to make the column align right.
147 In a column all non-white fields are considered. If at least
148 this fraction of fields is matched by `org-table-number-regexp',
149 alignment to the right border applies."
150 :group 'org-table-settings
151 :type 'number)
153 (defgroup org-table-editing nil
154 "Behavior of tables during editing in Org-mode."
155 :tag "Org Table Editing"
156 :group 'org-table)
158 (defcustom org-table-automatic-realign t
159 "Non-nil means automatically re-align table when pressing TAB or RETURN.
160 When nil, aligning is only done with \\[org-table-align], or after column
161 removal/insertion."
162 :group 'org-table-editing
163 :type 'boolean)
165 (defcustom org-table-auto-blank-field t
166 "Non-nil means automatically blank table field when starting to type into it.
167 This only happens when typing immediately after a field motion
168 command (TAB, S-TAB or RET).
169 Only relevant when `org-enable-table-editor' is equal to `optimized'."
170 :group 'org-table-editing
171 :type 'boolean)
173 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
174 "Non-nil means automatically exit the follow mode.
175 When nil, the follow mode will stay on and be active in any table
176 the cursor enters. Since the table follow filed mode messes with the
177 window configuration, it is not recommended to set this variable to nil,
178 except maybe locally in a special file that has mostly tables with long
179 fields."
180 :group 'org-table
181 :version "24.1"
182 :type 'boolean)
184 (defcustom org-table-fix-formulas-confirm nil
185 "Whether the user should confirm when Org fixes formulas."
186 :group 'org-table-editing
187 :version "24.1"
188 :type '(choice
189 (const :tag "with yes-or-no" yes-or-no-p)
190 (const :tag "with y-or-n" y-or-n-p)
191 (const :tag "no confirmation" nil)))
192 (put 'org-table-fix-formulas-confirm
193 'safe-local-variable
194 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
196 (defcustom org-table-tab-jumps-over-hlines t
197 "Non-nil means tab in the last column of a table with jump over a hline.
198 If a horizontal separator line is following the current line,
199 `org-table-next-field' can either create a new row before that line, or jump
200 over the line. When this option is nil, a new line will be created before
201 this line."
202 :group 'org-table-editing
203 :type 'boolean)
205 (defgroup org-table-calculation nil
206 "Options concerning tables in Org-mode."
207 :tag "Org Table Calculation"
208 :group 'org-table)
210 (defcustom org-table-use-standard-references 'from
211 "Should org-mode work with table references like B3 instead of @3$2?
212 Possible values are:
213 nil never use them
214 from accept as input, do not present for editing
215 t accept as input and present for editing"
216 :group 'org-table-calculation
217 :type '(choice
218 (const :tag "Never, don't even check user input for them" nil)
219 (const :tag "Always, both as user input, and when editing" t)
220 (const :tag "Convert user input, don't offer during editing" from)))
222 (defcustom org-table-copy-increment t
223 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
224 :group 'org-table-calculation
225 :type 'boolean)
227 (defcustom org-calc-default-modes
228 '(calc-internal-prec 12
229 calc-float-format (float 8)
230 calc-angle-mode deg
231 calc-prefer-frac nil
232 calc-symbolic-mode nil
233 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
234 calc-display-working-message t
236 "List with Calc mode settings for use in `calc-eval' for table formulas.
237 The list must contain alternating symbols (Calc modes variables and values).
238 Don't remove any of the default settings, just change the values. Org-mode
239 relies on the variables to be present in the list."
240 :group 'org-table-calculation
241 :type 'plist)
243 (defcustom org-table-duration-custom-format 'hours
244 "Format for the output of calc computations like $1+$2;t.
245 The default value is 'hours, and will output the results as a
246 number of hours. Other allowed values are 'seconds, 'minutes and
247 'days, and the output will be a fraction of seconds, minutes or
248 days."
249 :group 'org-table-calculation
250 :version "24.1"
251 :type '(choice (symbol :tag "Seconds" 'seconds)
252 (symbol :tag "Minutes" 'minutes)
253 (symbol :tag "Hours " 'hours)
254 (symbol :tag "Days " 'days)))
256 (defcustom org-table-formula-field-format "%s"
257 "Format for fields which contain the result of a formula.
258 For example, using \"~%s~\" will display the result within tilde
259 characters. Beware that modifying the display can prevent the
260 field from being used in another formula."
261 :group 'org-table-settings
262 :version "24.1"
263 :type 'string)
265 (defcustom org-table-formula-evaluate-inline t
266 "Non-nil means TAB and RET evaluate a formula in current table field.
267 If the current field starts with an equal sign, it is assumed to be a formula
268 which should be evaluated as described in the manual and in the documentation
269 string of the command `org-table-eval-formula'. This feature requires the
270 Emacs calc package.
271 When this variable is nil, formula calculation is only available through
272 the command \\[org-table-eval-formula]."
273 :group 'org-table-calculation
274 :type 'boolean)
276 (defcustom org-table-formula-use-constants t
277 "Non-nil means interpret constants in formulas in tables.
278 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
279 by the value given in `org-table-formula-constants', or by a value obtained
280 from the `constants.el' package."
281 :group 'org-table-calculation
282 :type 'boolean)
284 (defcustom org-table-formula-constants nil
285 "Alist with constant names and values, for use in table formulas.
286 The car of each element is a name of a constant, without the `$' before it.
287 The cdr is the value as a string. For example, if you'd like to use the
288 speed of light in a formula, you would configure
290 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
292 and then use it in an equation like `$1*$c'.
294 Constants can also be defined on a per-file basis using a line like
296 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
297 :group 'org-table-calculation
298 :type '(repeat
299 (cons (string :tag "name")
300 (string :tag "value"))))
302 (defcustom org-table-allow-automatic-line-recalculation t
303 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
304 Automatically means when TAB or RET or C-c C-c are pressed in the line."
305 :group 'org-table-calculation
306 :type 'boolean)
308 (defcustom org-table-error-on-row-ref-crossing-hline t
309 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
310 :group 'org-table
311 :type 'boolean)
313 (defcustom org-table-relative-ref-may-cross-hline t
314 "Non-nil means relative formula references may cross hlines.
315 Here are the allowed values:
317 nil Relative references may not cross hlines. They will reference the
318 field next to the hline instead. Coming from below, the reference
319 will be to the field below the hline. Coming from above, it will be
320 to the field above.
321 t Relative references may cross hlines.
322 error An attempt to cross a hline will throw an error.
324 It is probably good to never set this variable to nil, for the sake of
325 portability of tables."
326 :group 'org-table-calculation
327 :type '(choice
328 (const :tag "Allow to cross" t)
329 (const :tag "Stick to hline" nil)
330 (const :tag "Error on attempt to cross" error)))
332 (defgroup org-table-import-export nil
333 "Options concerning table import and export in Org-mode."
334 :tag "Org Table Import Export"
335 :group 'org-table)
337 (defcustom org-table-export-default-format "orgtbl-to-tsv"
338 "Default export parameters for `org-table-export'.
339 These can be overridden for a specific table by setting the
340 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
341 radio tables for the different export transformations and
342 available parameters."
343 :group 'org-table-import-export
344 :type 'string)
346 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
347 "Detects a table line marked for automatic recalculation.")
348 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
349 "Detects a table line marked for automatic recalculation.")
350 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
351 "Detects a table line marked for automatic recalculation.")
352 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
353 "Searching from within a table (any type) this finds the first line outside the table.")
354 (defvar org-table-last-highlighted-reference nil)
355 (defvar org-table-formula-history nil)
357 (defvar org-table-column-names nil
358 "Alist with column names, derived from the `!' line.")
359 (defvar org-table-column-name-regexp nil
360 "Regular expression matching the current column names.")
361 (defvar org-table-local-parameters nil
362 "Alist with parameter names, derived from the `$' line.")
363 (defvar org-table-named-field-locations nil
364 "Alist with locations of named fields.")
366 (defvar org-table-current-line-types nil
367 "Table row types, non-nil only for the duration of a command.")
368 (defvar org-table-current-begin-line nil
369 "Table begin line, non-nil only for the duration of a command.")
370 (defvar org-table-current-begin-pos nil
371 "Table begin position, non-nil only for the duration of a command.")
372 (defvar org-table-current-ncol nil
373 "Number of columns in table, non-nil only for the duration of a command.")
374 (defvar org-table-dlines nil
375 "Vector of data line line numbers in the current table.")
376 (defvar org-table-hlines nil
377 "Vector of hline line numbers in the current table.")
379 (defconst org-table-range-regexp
380 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
381 ;; 1 2 3 4 5
382 "Regular expression for matching ranges in formulas.")
384 (defconst org-table-range-regexp2
385 (concat
386 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
387 "\\.\\."
388 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
389 "Match a range for reference display.")
391 (defun org-table-colgroup-line-p (line)
392 "Is this a table line colgroup information?"
393 (save-match-data
394 (and (string-match "[<>]\\|&[lg]t;" line)
395 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
396 line)
397 (not (delq
399 (mapcar
400 (lambda (s)
401 (not (member s '("" "<" ">" "<>" "&lt;" "&gt;" "&lt;&gt;"))))
402 (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
404 (defun org-table-cookie-line-p (line)
405 "Is this a table line with only alignment/width cookies?"
406 (save-match-data
407 (and (string-match "[<>]\\|&[lg]t;" line)
408 (or (string-match
409 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line)
410 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line))
411 (not (delq nil (mapcar
412 (lambda (s)
413 (not (or (equal s "")
414 (string-match
415 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s)
416 (string-match
417 "\\`&lt;\\([lrc]?[0-9]+\\|[lrc]\\)&gt;\\'"
418 s))))
419 (org-split-string (match-string 1 line)
420 "[ \t]*|[ \t]*")))))))
422 (defconst org-table-translate-regexp
423 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
424 "Match a reference that needs translation, for reference display.")
426 ;;;###autoload
427 (defun org-table-create-with-table.el ()
428 "Use the table.el package to insert a new table.
429 If there is already a table at point, convert between Org-mode tables
430 and table.el tables."
431 (interactive)
432 (require 'table)
433 (cond
434 ((org-at-table.el-p)
435 (if (y-or-n-p "Convert table to Org-mode table? ")
436 (org-table-convert)))
437 ((org-at-table-p)
438 (when (y-or-n-p "Convert table to table.el table? ")
439 (org-table-align)
440 (org-table-convert)))
441 (t (call-interactively 'table-insert))))
443 ;;;###autoload
444 (defun org-table-create-or-convert-from-region (arg)
445 "Convert region to table, or create an empty table.
446 If there is an active region, convert it to a table, using the function
447 `org-table-convert-region'. See the documentation of that function
448 to learn how the prefix argument is interpreted to determine the field
449 separator.
450 If there is no such region, create an empty table with `org-table-create'."
451 (interactive "P")
452 (if (org-region-active-p)
453 (org-table-convert-region (region-beginning) (region-end) arg)
454 (org-table-create arg)))
456 ;;;###autoload
457 (defun org-table-create (&optional size)
458 "Query for a size and insert a table skeleton.
459 SIZE is a string Columns x Rows like for example \"3x2\"."
460 (interactive "P")
461 (unless size
462 (setq size (read-string
463 (concat "Table size Columns x Rows [e.g. "
464 org-table-default-size "]: ")
465 "" nil org-table-default-size)))
467 (let* ((pos (point))
468 (indent (make-string (current-column) ?\ ))
469 (split (org-split-string size " *x *"))
470 (rows (string-to-number (nth 1 split)))
471 (columns (string-to-number (car split)))
472 (line (concat (apply 'concat indent "|" (make-list columns " |"))
473 "\n")))
474 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
475 (point-at-bol) (point)))
476 (beginning-of-line 1)
477 (newline))
478 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
479 (dotimes (i rows) (insert line))
480 (goto-char pos)
481 (if (> rows 1)
482 ;; Insert a hline after the first row.
483 (progn
484 (end-of-line 1)
485 (insert "\n|-")
486 (goto-char pos)))
487 (org-table-align)))
489 ;;;###autoload
490 (defun org-table-convert-region (beg0 end0 &optional separator)
491 "Convert region to a table.
492 The region goes from BEG0 to END0, but these borders will be moved
493 slightly, to make sure a beginning of line in the first line is included.
495 SEPARATOR specifies the field separator in the lines. It can have the
496 following values:
498 '(4) Use the comma as a field separator
499 '(16) Use a TAB as field separator
500 integer When a number, use that many spaces as field separator
501 nil When nil, the command tries to be smart and figure out the
502 separator in the following way:
503 - when each line contains a TAB, assume TAB-separated material
504 - when each line contains a comma, assume CSV material
505 - else, assume one or more SPACE characters as separator."
506 (interactive "rP")
507 (let* ((beg (min beg0 end0))
508 (end (max beg0 end0))
510 (goto-char beg)
511 (beginning-of-line 1)
512 (setq beg (point-marker))
513 (goto-char end)
514 (if (bolp) (backward-char 1) (end-of-line 1))
515 (setq end (point-marker))
516 ;; Get the right field separator
517 (unless separator
518 (goto-char beg)
519 (setq separator
520 (cond
521 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
522 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
523 (t 1))))
524 (goto-char beg)
525 (if (equal separator '(4))
526 (while (< (point) end)
527 ;; parse the csv stuff
528 (cond
529 ((looking-at "^") (insert "| "))
530 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
531 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
532 (replace-match "\\1")
533 (if (looking-at "\"") (insert "\"")))
534 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
535 ((looking-at "[ \t]*,") (replace-match " | "))
536 (t (beginning-of-line 2))))
537 (setq re (cond
538 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
539 ((equal separator '(16)) "^\\|\t")
540 ((integerp separator)
541 (if (< separator 1)
542 (error "Number of spaces in separator must be >= 1")
543 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
544 (t (error "This should not happen"))))
545 (while (re-search-forward re end t)
546 (replace-match "| " t t)))
547 (goto-char beg)
548 (org-table-align)))
550 ;;;###autoload
551 (defun org-table-import (file arg)
552 "Import FILE as a table.
553 The file is assumed to be tab-separated. Such files can be produced by most
554 spreadsheet and database applications. If no tabs (at least one per line)
555 are found, lines will be split on whitespace into fields."
556 (interactive "f\nP")
557 (or (bolp) (newline))
558 (let ((beg (point))
559 (pm (point-max)))
560 (insert-file-contents file)
561 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
564 (defvar org-table-last-alignment)
565 (defvar org-table-last-column-widths)
566 ;;;###autoload
567 (defun org-table-export (&optional file format)
568 "Export table to a file, with configurable format.
569 Such a file can be imported into usual spreadsheet programs.
571 FILE can be the output file name. If not given, it will be taken
572 from a TABLE_EXPORT_FILE property in the current entry or higher
573 up in the hierarchy, or the user will be prompted for a file
574 name. FORMAT can be an export format, of the same kind as it
575 used when `orgtbl-mode' sends a table in a different format.
577 The command suggests a format depending on TABLE_EXPORT_FORMAT,
578 whether it is set locally or up in the hierarchy, then on the
579 extension of the given file name, and finally on the variable
580 `org-table-export-default-format'."
581 (interactive)
582 (unless (org-at-table-p)
583 (error "No table at point"))
584 (require 'org-exp)
585 (org-table-align) ;; make sure we have everything we need
586 (let* ((beg (org-table-begin))
587 (end (org-table-end))
588 (txt (buffer-substring-no-properties beg end))
589 (file (or file (org-entry-get beg "TABLE_EXPORT_FILE" t)))
590 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
591 "orgtbl-to-latex" "orgtbl-to-html"
592 "orgtbl-to-generic" "orgtbl-to-texinfo"
593 "orgtbl-to-orgtbl"))
594 (format (or format
595 (org-entry-get beg "TABLE_EXPORT_FORMAT" t)))
596 buf deffmt-readable fileext)
597 (unless file
598 (setq file (read-file-name "Export table to: "))
599 (unless (or (not (file-exists-p file))
600 (y-or-n-p (format "Overwrite file %s? " file)))
601 (error "Abort")))
602 (if (file-directory-p file)
603 (error "This is a directory path, not a file"))
604 (if (and (buffer-file-name)
605 (equal (file-truename file)
606 (file-truename (buffer-file-name))))
607 (error "Please specify a file name that is different from current"))
608 (setq fileext (concat (file-name-extension file) "$"))
609 (unless format
610 (setq deffmt-readable
611 (or (car (delq nil (mapcar (lambda(f) (if (string-match fileext f) f)) formats)))
612 org-table-export-default-format))
613 (while (string-match "\t" deffmt-readable)
614 (setq deffmt-readable (replace-match "\\t" t t deffmt-readable)))
615 (while (string-match "\n" deffmt-readable)
616 (setq deffmt-readable (replace-match "\\n" t t deffmt-readable)))
617 (setq format (org-completing-read "Format: " formats nil nil deffmt-readable)))
618 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
619 (let* ((transform (intern (match-string 1 format)))
620 (params (if (match-end 2)
621 (read (concat "(" (match-string 2 format) ")"))))
622 (skip (plist-get params :skip))
623 (skipcols (plist-get params :skipcols))
624 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
625 (lines (org-table-clean-before-export lines))
626 (i0 (if org-table-clean-did-remove-column 2 1))
627 (table (mapcar
628 (lambda (x)
629 (if (string-match org-table-hline-regexp x)
630 'hline
631 (org-remove-by-index
632 (org-split-string (org-trim x) "\\s-*|\\s-*")
633 skipcols i0)))
634 lines))
635 (fun (if (= i0 2) 'cdr 'identity))
636 (org-table-last-alignment
637 (org-remove-by-index (funcall fun org-table-last-alignment)
638 skipcols i0))
639 (org-table-last-column-widths
640 (org-remove-by-index (funcall fun org-table-last-column-widths)
641 skipcols i0)))
643 (unless (fboundp transform)
644 (error "No such transformation function %s" transform))
645 (setq txt (funcall transform table params))
647 (with-current-buffer (find-file-noselect file)
648 (setq buf (current-buffer))
649 (erase-buffer)
650 (fundamental-mode)
651 (insert txt "\n")
652 (save-buffer))
653 (kill-buffer buf)
654 (message "Export done."))
655 (error "TABLE_EXPORT_FORMAT invalid"))))
657 (defvar org-table-aligned-begin-marker (make-marker)
658 "Marker at the beginning of the table last aligned.
659 Used to check if cursor still is in that table, to minimize realignment.")
660 (defvar org-table-aligned-end-marker (make-marker)
661 "Marker at the end of the table last aligned.
662 Used to check if cursor still is in that table, to minimize realignment.")
663 (defvar org-table-last-alignment nil
664 "List of flags for flushright alignment, from the last re-alignment.
665 This is being used to correctly align a single field after TAB or RET.")
666 (defvar org-table-last-column-widths nil
667 "List of max width of fields in each column.
668 This is being used to correctly align a single field after TAB or RET.")
669 (defvar org-table-formula-debug nil
670 "Non-nil means debug table formulas.
671 When nil, simply write \"#ERROR\" in corrupted fields.")
672 (make-variable-buffer-local 'org-table-formula-debug)
673 (defvar org-table-overlay-coordinates nil
674 "Overlay coordinates after each align of a table.")
675 (make-variable-buffer-local 'org-table-overlay-coordinates)
677 (defvar org-last-recalc-line nil)
678 (defvar org-table-do-narrow t) ; for dynamic scoping
679 (defconst org-narrow-column-arrow "=>"
680 "Used as display property in narrowed table columns.")
682 ;;;###autoload
683 (defun org-table-align ()
684 "Align the table at point by aligning all vertical bars."
685 (interactive)
686 (let* (
687 ;; Limits of table
688 (beg (org-table-begin))
689 (end (org-table-end))
690 ;; Current cursor position
691 (linepos (org-current-line))
692 (colpos (org-table-current-column))
693 (winstart (window-start))
694 (winstartline (org-current-line (min winstart (1- (point-max)))))
695 lines (new "") lengths l typenums ty fields maxfields i
696 column
697 (indent "") cnt frac
698 rfmt hfmt
699 (spaces '(1 . 1))
700 (sp1 (car spaces))
701 (sp2 (cdr spaces))
702 (rfmt1 (concat
703 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
704 (hfmt1 (concat
705 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
706 emptystrings links dates emph raise narrow
707 falign falign1 fmax f1 len c e space)
708 (untabify beg end)
709 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
710 ;; Check if we have links or dates
711 (goto-char beg)
712 (setq links (re-search-forward org-bracket-link-regexp end t))
713 (goto-char beg)
714 (setq emph (and org-hide-emphasis-markers
715 (re-search-forward org-emph-re end t)))
716 (goto-char beg)
717 (setq raise (and org-use-sub-superscripts
718 (re-search-forward org-match-substring-regexp end t)))
719 (goto-char beg)
720 (setq dates (and org-display-custom-times
721 (re-search-forward org-ts-regexp-both end t)))
722 ;; Make sure the link properties are right
723 (when links (goto-char beg) (while (org-activate-bracket-links end)))
724 ;; Make sure the date properties are right
725 (when dates (goto-char beg) (while (org-activate-dates end)))
726 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
727 (when raise (goto-char beg) (while (org-raise-scripts end)))
729 ;; Check if we are narrowing any columns
730 (goto-char beg)
731 (setq narrow (and org-table-do-narrow
732 org-format-transports-properties-p
733 (re-search-forward "<[lrc]?[0-9]+>" end t)))
734 (goto-char beg)
735 (setq falign (re-search-forward "<[lrc][0-9]*>" end t))
736 (goto-char beg)
737 ;; Get the rows
738 (setq lines (org-split-string
739 (buffer-substring beg end) "\n"))
740 ;; Store the indentation of the first line
741 (if (string-match "^ *" (car lines))
742 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
743 ;; Mark the hlines by setting the corresponding element to nil
744 ;; At the same time, we remove trailing space.
745 (setq lines (mapcar (lambda (l)
746 (if (string-match "^ *|-" l)
748 (if (string-match "[ \t]+$" l)
749 (substring l 0 (match-beginning 0))
750 l)))
751 lines))
752 ;; Get the data fields by splitting the lines.
753 (setq fields (mapcar
754 (lambda (l)
755 (org-split-string l " *| *"))
756 (delq nil (copy-sequence lines))))
757 ;; How many fields in the longest line?
758 (condition-case nil
759 (setq maxfields (apply 'max (mapcar 'length fields)))
760 (error
761 (kill-region beg end)
762 (org-table-create org-table-default-size)
763 (error "Empty table - created default table")))
764 ;; A list of empty strings to fill any short rows on output
765 (setq emptystrings (make-list maxfields ""))
766 ;; Check for special formatting.
767 (setq i -1)
768 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
769 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
770 ;; Check if there is an explicit width specified
771 (setq fmax nil)
772 (when (or narrow falign)
773 (setq c column fmax nil falign1 nil)
774 (while c
775 (setq e (pop c))
776 (when (and (stringp e) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e))
777 (if (match-end 1) (setq falign1 (match-string 1 e)))
778 (if (and org-table-do-narrow (match-end 2))
779 (setq fmax (string-to-number (match-string 2 e)) c nil))))
780 ;; Find fields that are wider than fmax, and shorten them
781 (when fmax
782 (loop for xx in column do
783 (when (and (stringp xx)
784 (> (org-string-width xx) fmax))
785 (org-add-props xx nil
786 'help-echo
787 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
788 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
789 (unless (> f1 1)
790 (error "Cannot narrow field starting with wide link \"%s\""
791 (match-string 0 xx)))
792 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
793 (add-text-properties (- f1 2) f1
794 (list 'display org-narrow-column-arrow)
795 xx)))))
796 ;; Get the maximum width for each column
797 (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
798 lengths)
799 ;; Get the fraction of numbers, to decide about alignment of the column
800 (if falign1
801 (push (equal (downcase falign1) "r") typenums)
802 (setq cnt 0 frac 0.0)
803 (loop for x in column do
804 (if (equal x "")
806 (setq frac ( / (+ (* frac cnt)
807 (if (string-match org-table-number-regexp x) 1 0))
808 (setq cnt (1+ cnt))))))
809 (push (>= frac org-table-number-fraction) typenums)))
810 (setq lengths (nreverse lengths) typenums (nreverse typenums))
812 ;; Store the alignment of this table, for later editing of single fields
813 (setq org-table-last-alignment typenums
814 org-table-last-column-widths lengths)
816 ;; With invisible characters, `format' does not get the field width right
817 ;; So we need to make these fields wide by hand.
818 (when (or links emph raise)
819 (loop for i from 0 upto (1- maxfields) do
820 (setq len (nth i lengths))
821 (loop for j from 0 upto (1- (length fields)) do
822 (setq c (nthcdr i (car (nthcdr j fields))))
823 (if (and (stringp (car c))
824 (or (text-property-any 0 (length (car c))
825 'invisible 'org-link (car c))
826 (text-property-any 0 (length (car c))
827 'org-dwidth t (car c)))
828 (< (org-string-width (car c)) len))
829 (progn
830 (setq space (make-string (- len (org-string-width (car c))) ?\ ))
831 (setcar c (if (nth i typenums)
832 (concat space (car c))
833 (concat (car c) space))))))))
835 ;; Compute the formats needed for output of the table
836 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
837 (while (setq l (pop lengths))
838 (setq ty (if (pop typenums) "" "-")) ; number types flushright
839 (setq rfmt (concat rfmt (format rfmt1 ty l))
840 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
841 (setq rfmt (concat rfmt "\n")
842 hfmt (concat (substring hfmt 0 -1) "|\n"))
844 (setq new (mapconcat
845 (lambda (l)
846 (if l (apply 'format rfmt
847 (append (pop fields) emptystrings))
848 hfmt))
849 lines ""))
850 (move-marker org-table-aligned-begin-marker (point))
851 (insert new)
852 ;; Replace the old one
853 (delete-region (point) end)
854 (move-marker end nil)
855 (move-marker org-table-aligned-end-marker (point))
856 (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
857 (goto-char org-table-aligned-begin-marker)
858 (while (org-hide-wide-columns org-table-aligned-end-marker)))
859 ;; Try to move to the old location
860 (org-goto-line winstartline)
861 (setq winstart (point-at-bol))
862 (org-goto-line linepos)
863 (set-window-start (selected-window) winstart 'noforce)
864 (org-table-goto-column colpos)
865 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
866 (setq org-table-may-need-update nil)
869 (defun org-table-begin (&optional table-type)
870 "Find the beginning of the table and return its position.
871 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
872 (save-excursion
873 (if (not (re-search-backward
874 (if table-type org-table-any-border-regexp
875 org-table-border-regexp)
876 nil t))
877 (progn (goto-char (point-min)) (point))
878 (goto-char (match-beginning 0))
879 (beginning-of-line 2)
880 (point))))
882 (defun org-table-end (&optional table-type)
883 "Find the end of the table and return its position.
884 With argument TABLE-TYPE, go to the end of a table.el-type table."
885 (save-excursion
886 (if (not (re-search-forward
887 (if table-type org-table-any-border-regexp
888 org-table-border-regexp)
889 nil t))
890 (goto-char (point-max))
891 (goto-char (match-beginning 0)))
892 (point-marker)))
894 ;;;###autoload
895 (defun org-table-justify-field-maybe (&optional new)
896 "Justify the current field, text to left, number to right.
897 Optional argument NEW may specify text to replace the current field content."
898 (cond
899 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
900 ((org-at-table-hline-p))
901 ((and (not new)
902 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
903 (current-buffer)))
904 (< (point) org-table-aligned-begin-marker)
905 (>= (point) org-table-aligned-end-marker)))
906 ;; This is not the same table, force a full re-align
907 (setq org-table-may-need-update t))
908 (t ;; realign the current field, based on previous full realign
909 (let* ((pos (point)) s
910 (col (org-table-current-column))
911 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
912 l f n o e)
913 (when (> col 0)
914 (skip-chars-backward "^|\n")
915 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
916 (progn
917 (setq s (match-string 1)
918 o (match-string 0)
919 l (max 1 (- (match-end 0) (match-beginning 0) 3))
920 e (not (= (match-beginning 2) (match-end 2))))
921 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
922 l (if e "|" (setq org-table-may-need-update t) ""))
923 n (format f s))
924 (if new
925 (if (<= (length new) l) ;; FIXME: length -> str-width?
926 (setq n (format f new))
927 (setq n (concat new "|") org-table-may-need-update t)))
928 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
929 (or (equal n o)
930 (let (org-table-may-need-update)
931 (replace-match n t t))))
932 (setq org-table-may-need-update t))
933 (goto-char pos))))))
935 ;;;###autoload
936 (defun org-table-next-field ()
937 "Go to the next field in the current table, creating new lines as needed.
938 Before doing so, re-align the table if necessary."
939 (interactive)
940 (org-table-maybe-eval-formula)
941 (org-table-maybe-recalculate-line)
942 (if (and org-table-automatic-realign
943 org-table-may-need-update)
944 (org-table-align))
945 (let ((end (org-table-end)))
946 (if (org-at-table-hline-p)
947 (end-of-line 1))
948 (condition-case nil
949 (progn
950 (re-search-forward "|" end)
951 (if (looking-at "[ \t]*$")
952 (re-search-forward "|" end))
953 (if (and (looking-at "-")
954 org-table-tab-jumps-over-hlines
955 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
956 (goto-char (match-beginning 1)))
957 (if (looking-at "-")
958 (progn
959 (beginning-of-line 0)
960 (org-table-insert-row 'below))
961 (if (looking-at " ") (forward-char 1))))
962 (error
963 (org-table-insert-row 'below)))))
965 ;;;###autoload
966 (defun org-table-previous-field ()
967 "Go to the previous field in the table.
968 Before doing so, re-align the table if necessary."
969 (interactive)
970 (org-table-justify-field-maybe)
971 (org-table-maybe-recalculate-line)
972 (if (and org-table-automatic-realign
973 org-table-may-need-update)
974 (org-table-align))
975 (if (org-at-table-hline-p)
976 (end-of-line 1))
977 (condition-case nil
978 (progn
979 (re-search-backward "|" (org-table-begin))
980 (re-search-backward "|" (org-table-begin)))
981 (error (error "Cannot move to previous table field")))
982 (while (looking-at "|\\(-\\|[ \t]*$\\)")
983 (re-search-backward "|" (org-table-begin)))
984 (if (looking-at "| ?")
985 (goto-char (match-end 0))))
987 (defun org-table-beginning-of-field (&optional n)
988 "Move to the end of the current table field.
989 If already at or after the end, move to the end of the next table field.
990 With numeric argument N, move N-1 fields forward first."
991 (interactive "p")
992 (let ((pos (point)))
993 (while (> n 1)
994 (setq n (1- n))
995 (org-table-previous-field))
996 (if (not (re-search-backward "|" (point-at-bol 0) t))
997 (error "No more table fields before the current")
998 (goto-char (match-end 0))
999 (and (looking-at " ") (forward-char 1)))
1000 (if (>= (point) pos) (org-table-beginning-of-field 2))))
1002 (defun org-table-end-of-field (&optional n)
1003 "Move to the beginning of the current table field.
1004 If already at or before the beginning, move to the beginning of the
1005 previous field.
1006 With numeric argument N, move N-1 fields backward first."
1007 (interactive "p")
1008 (let ((pos (point)))
1009 (while (> n 1)
1010 (setq n (1- n))
1011 (org-table-next-field))
1012 (when (re-search-forward "|" (point-at-eol 1) t)
1013 (backward-char 1)
1014 (skip-chars-backward " ")
1015 (if (and (equal (char-before (point)) ?|) (looking-at " "))
1016 (forward-char 1)))
1017 (if (<= (point) pos) (org-table-end-of-field 2))))
1019 ;;;###autoload
1020 (defun org-table-next-row ()
1021 "Go to the next row (same column) in the current table.
1022 Before doing so, re-align the table if necessary."
1023 (interactive)
1024 (org-table-maybe-eval-formula)
1025 (org-table-maybe-recalculate-line)
1026 (if (or (looking-at "[ \t]*$")
1027 (save-excursion (skip-chars-backward " \t") (bolp)))
1028 (newline)
1029 (if (and org-table-automatic-realign
1030 org-table-may-need-update)
1031 (org-table-align))
1032 (let ((col (org-table-current-column)))
1033 (beginning-of-line 2)
1034 (if (or (not (org-at-table-p))
1035 (org-at-table-hline-p))
1036 (progn
1037 (beginning-of-line 0)
1038 (org-table-insert-row 'below)))
1039 (org-table-goto-column col)
1040 (skip-chars-backward "^|\n\r")
1041 (if (looking-at " ") (forward-char 1)))))
1043 ;;;###autoload
1044 (defun org-table-copy-down (n)
1045 "Copy a field down in the current column.
1046 If the field at the cursor is empty, copy into it the content of
1047 the nearest non-empty field above. With argument N, use the Nth
1048 non-empty field. If the current field is not empty, it is copied
1049 down to the next row, and the cursor is moved with it.
1050 Therefore, repeating this command causes the column to be filled
1051 row-by-row.
1052 If the variable `org-table-copy-increment' is non-nil and the
1053 field is an integer or a timestamp, it will be incremented while
1054 copying. In the case of a timestamp, increment by one day."
1055 (interactive "p")
1056 (let* ((colpos (org-table-current-column))
1057 (col (current-column))
1058 (field (org-table-get-field))
1059 (non-empty (string-match "[^ \t]" field))
1060 (beg (org-table-begin))
1061 (orig-n n)
1062 txt)
1063 (org-table-check-inside-data-field)
1064 (if non-empty
1065 (progn
1066 (setq txt (org-trim field))
1067 (org-table-next-row)
1068 (org-table-blank-field))
1069 (save-excursion
1070 (setq txt
1071 (catch 'exit
1072 (while (progn (beginning-of-line 1)
1073 (re-search-backward org-table-dataline-regexp
1074 beg t))
1075 (org-table-goto-column colpos t)
1076 (if (and (looking-at
1077 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1078 (<= (setq n (1- n)) 0))
1079 (throw 'exit (match-string 1))))))))
1080 (if txt
1081 (progn
1082 (if (and org-table-copy-increment
1083 (not (equal orig-n 0))
1084 (string-match "^[0-9]+$" txt)
1085 (< (string-to-number txt) 100000000))
1086 (setq txt (format "%d" (+ (string-to-number txt) 1))))
1087 (insert txt)
1088 (org-move-to-column col)
1089 (if (and org-table-copy-increment (org-at-timestamp-p t))
1090 (org-timestamp-up-day)
1091 (org-table-maybe-recalculate-line))
1092 (org-table-align)
1093 (org-move-to-column col))
1094 (error "No non-empty field found"))))
1096 (defun org-table-check-inside-data-field (&optional noerror)
1097 "Is point inside a table data field?
1098 I.e. not on a hline or before the first or after the last column?
1099 This actually throws an error, so it aborts the current command."
1100 (if (or (not (org-at-table-p))
1101 (= (org-table-current-column) 0)
1102 (org-at-table-hline-p)
1103 (looking-at "[ \t]*$"))
1104 (if noerror
1106 (error "Not in table data field"))
1109 (defvar org-table-clip nil
1110 "Clipboard for table regions.")
1112 (defun org-table-get (line column)
1113 "Get the field in table line LINE, column COLUMN.
1114 If LINE is larger than the number of data lines in the table, the function
1115 returns nil. However, if COLUMN is too large, we will simply return an
1116 empty string.
1117 If LINE is nil, use the current line.
1118 If column is nil, use the current column."
1119 (setq column (or column (org-table-current-column)))
1120 (save-excursion
1121 (and (or (not line) (org-table-goto-line line))
1122 (org-trim (org-table-get-field column)))))
1124 (defun org-table-put (line column value &optional align)
1125 "Put VALUE into line LINE, column COLUMN.
1126 When ALIGN is set, also realign the table."
1127 (setq column (or column (org-table-current-column)))
1128 (prog1 (save-excursion
1129 (and (or (not line) (org-table-goto-line line))
1130 (progn (org-table-goto-column column nil 'force) t)
1131 (org-table-get-field column value)))
1132 (and align (org-table-align))))
1134 (defun org-table-current-line ()
1135 "Return the index of the current data line."
1136 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1137 (save-excursion
1138 (goto-char (org-table-begin))
1139 (while (and (re-search-forward org-table-dataline-regexp end t)
1140 (setq cnt (1+ cnt))
1141 (< (point-at-eol) pos))))
1142 cnt))
1144 (defun org-table-goto-line (N)
1145 "Go to the Nth data line in the current table.
1146 Return t when the line exists, nil if it does not exist."
1147 (goto-char (org-table-begin))
1148 (let ((end (org-table-end)) (cnt 0))
1149 (while (and (re-search-forward org-table-dataline-regexp end t)
1150 (< (setq cnt (1+ cnt)) N)))
1151 (= cnt N)))
1153 (defun org-table-blank-field ()
1154 "Blank the current table field or active region."
1155 (interactive)
1156 (org-table-check-inside-data-field)
1157 (if (and (org-called-interactively-p 'any) (org-region-active-p))
1158 (let (org-table-clip)
1159 (org-table-cut-region (region-beginning) (region-end)))
1160 (skip-chars-backward "^|")
1161 (backward-char 1)
1162 (if (looking-at "|[^|\n]+")
1163 (let* ((pos (match-beginning 0))
1164 (match (match-string 0))
1165 (len (org-string-width match)))
1166 (replace-match (concat "|" (make-string (1- len) ?\ )))
1167 (goto-char (+ 2 pos))
1168 (substring match 1)))))
1170 (defun org-table-get-field (&optional n replace)
1171 "Return the value of the field in column N of current row.
1172 N defaults to current field.
1173 If REPLACE is a string, replace field with this value. The return value
1174 is always the old value."
1175 (and n (org-table-goto-column n))
1176 (skip-chars-backward "^|\n")
1177 (backward-char 1)
1178 (if (looking-at "|[^|\r\n]*")
1179 (let* ((pos (match-beginning 0))
1180 (val (buffer-substring (1+ pos) (match-end 0))))
1181 (if replace
1182 (replace-match (concat "|" (if (equal replace "") " " replace))
1183 t t))
1184 (goto-char (min (point-at-eol) (+ 2 pos)))
1185 val)
1186 (forward-char 1) ""))
1188 ;;;###autoload
1189 (defun org-table-field-info (arg)
1190 "Show info about the current field, and highlight any reference at point."
1191 (interactive "P")
1192 (org-table-get-specials)
1193 (save-excursion
1194 (let* ((pos (point))
1195 (col (org-table-current-column))
1196 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1197 (name (car (rassoc (list (org-current-line) col)
1198 org-table-named-field-locations)))
1199 (eql (org-table-expand-lhs-ranges
1200 (mapcar
1201 (lambda (e)
1202 (cons (org-table-formula-handle-first/last-rc
1203 (car e)) (cdr e)))
1204 (org-table-get-stored-formulas))))
1205 (dline (org-table-current-dline))
1206 (ref (format "@%d$%d" dline col))
1207 (ref1 (org-table-convert-refs-to-an ref))
1208 (fequation (or (assoc name eql) (assoc ref eql)))
1209 (cequation (assoc (int-to-string col) eql))
1210 (eqn (or fequation cequation)))
1211 (if (and eqn (get-text-property 0 :orig-eqn (car eqn)))
1212 (setq eqn (get-text-property 0 :orig-eqn (car eqn))))
1213 (goto-char pos)
1214 (condition-case nil
1215 (org-table-show-reference 'local)
1216 (error nil))
1217 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1218 dline col
1219 (if cname (concat " or $" cname) "")
1220 dline col ref1
1221 (if name (concat " or $" name) "")
1222 ;; FIXME: formula info not correct if special table line
1223 (if eqn
1224 (concat ", formula: "
1225 (org-table-formula-to-user
1226 (concat
1227 (if (string-match "^[$@]"(car eqn)) "" "$")
1228 (car eqn) "=" (cdr eqn))))
1229 "")))))
1231 (defun org-table-current-column ()
1232 "Find out which column we are in."
1233 (interactive)
1234 (if (org-called-interactively-p 'any) (org-table-check-inside-data-field))
1235 (save-excursion
1236 (let ((cnt 0) (pos (point)))
1237 (beginning-of-line 1)
1238 (while (search-forward "|" pos t)
1239 (setq cnt (1+ cnt)))
1240 (when (org-called-interactively-p 'interactive)
1241 (message "In table column %d" cnt))
1242 cnt)))
1244 ;;;###autoload
1245 (defun org-table-current-dline ()
1246 "Find out what table data line we are in.
1247 Only data lines count for this."
1248 (interactive)
1249 (when (org-called-interactively-p 'any)
1250 (org-table-check-inside-data-field))
1251 (save-excursion
1252 (let ((cnt 0) (pos (point)))
1253 (goto-char (org-table-begin))
1254 (while (<= (point) pos)
1255 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1256 (beginning-of-line 2))
1257 (when (org-called-interactively-p 'any)
1258 (message "This is table line %d" cnt))
1259 cnt)))
1261 ;;;###autoload
1262 (defun org-table-goto-column (n &optional on-delim force)
1263 "Move the cursor to the Nth column in the current table line.
1264 With optional argument ON-DELIM, stop with point before the left delimiter
1265 of the field.
1266 If there are less than N fields, just go to after the last delimiter.
1267 However, when FORCE is non-nil, create new columns if necessary."
1268 (interactive "p")
1269 (beginning-of-line 1)
1270 (when (> n 0)
1271 (while (and (> (setq n (1- n)) -1)
1272 (or (search-forward "|" (point-at-eol) t)
1273 (and force
1274 (progn (end-of-line 1)
1275 (skip-chars-backward "^|")
1276 (insert " | ")
1277 t)))))
1278 (when (and force (not (looking-at ".*|")))
1279 (save-excursion (end-of-line 1) (insert " | ")))
1280 (if on-delim
1281 (backward-char 1)
1282 (if (looking-at " ") (forward-char 1)))))
1284 ;;;###autoload
1285 (defun org-table-insert-column ()
1286 "Insert a new column into the table."
1287 (interactive)
1288 (if (not (org-at-table-p))
1289 (error "Not at a table"))
1290 (org-table-find-dataline)
1291 (let* ((col (max 1 (org-table-current-column)))
1292 (beg (org-table-begin))
1293 (end (org-table-end))
1294 ;; Current cursor position
1295 (linepos (org-current-line))
1296 (colpos col))
1297 (goto-char beg)
1298 (while (< (point) end)
1299 (if (org-at-table-hline-p)
1301 (org-table-goto-column col t)
1302 (insert "| "))
1303 (beginning-of-line 2))
1304 (move-marker end nil)
1305 (org-goto-line linepos)
1306 (org-table-goto-column colpos)
1307 (org-table-align)
1308 (when (or (not org-table-fix-formulas-confirm)
1309 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1310 (org-table-fix-formulas "$" nil (1- col) 1)
1311 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1313 (defun org-table-find-dataline ()
1314 "Find a data line in the current table, which is needed for column commands."
1315 (if (and (org-at-table-p)
1316 (not (org-at-table-hline-p)))
1318 (let ((col (current-column))
1319 (end (org-table-end)))
1320 (org-move-to-column col)
1321 (while (and (< (point) end)
1322 (or (not (= (current-column) col))
1323 (org-at-table-hline-p)))
1324 (beginning-of-line 2)
1325 (org-move-to-column col))
1326 (if (and (org-at-table-p)
1327 (not (org-at-table-hline-p)))
1329 (error
1330 "Please position cursor in a data line for column operations")))))
1332 (defun org-table-line-to-dline (line &optional above)
1333 "Turn a buffer line number into a data line number.
1334 If there is no data line in this line, return nil.
1335 If there is no matching dline (most likely te reference was a hline), the
1336 first dline below it is used. When ABOVE is non-nil, the one above is used."
1337 (catch 'exit
1338 (let ((ll (length org-table-dlines))
1340 (if above
1341 (progn
1342 (setq i (1- ll))
1343 (while (> i 0)
1344 (if (<= (aref org-table-dlines i) line)
1345 (throw 'exit i))
1346 (setq i (1- i))))
1347 (setq i 1)
1348 (while (< i ll)
1349 (if (>= (aref org-table-dlines i) line)
1350 (throw 'exit i))
1351 (setq i (1+ i)))))
1352 nil))
1354 ;;;###autoload
1355 (defun org-table-delete-column ()
1356 "Delete a column from the table."
1357 (interactive)
1358 (if (not (org-at-table-p))
1359 (error "Not at a table"))
1360 (org-table-find-dataline)
1361 (org-table-check-inside-data-field)
1362 (let* ((col (org-table-current-column))
1363 (beg (org-table-begin))
1364 (end (org-table-end))
1365 ;; Current cursor position
1366 (linepos (org-current-line))
1367 (colpos col))
1368 (goto-char beg)
1369 (while (< (point) end)
1370 (if (org-at-table-hline-p)
1372 (org-table-goto-column col t)
1373 (and (looking-at "|[^|\n]+|")
1374 (replace-match "|")))
1375 (beginning-of-line 2))
1376 (move-marker end nil)
1377 (org-goto-line linepos)
1378 (org-table-goto-column colpos)
1379 (org-table-align)
1380 (when (or (not org-table-fix-formulas-confirm)
1381 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1382 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1383 col -1 col)
1384 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1385 col -1 col))))
1387 ;;;###autoload
1388 (defun org-table-move-column-right ()
1389 "Move column to the right."
1390 (interactive)
1391 (org-table-move-column nil))
1392 ;;;###autoload
1393 (defun org-table-move-column-left ()
1394 "Move column to the left."
1395 (interactive)
1396 (org-table-move-column 'left))
1398 ;;;###autoload
1399 (defun org-table-move-column (&optional left)
1400 "Move the current column to the right. With arg LEFT, move to the left."
1401 (interactive "P")
1402 (if (not (org-at-table-p))
1403 (error "Not at a table"))
1404 (org-table-find-dataline)
1405 (org-table-check-inside-data-field)
1406 (let* ((col (org-table-current-column))
1407 (col1 (if left (1- col) col))
1408 (beg (org-table-begin))
1409 (end (org-table-end))
1410 ;; Current cursor position
1411 (linepos (org-current-line))
1412 (colpos (if left (1- col) (1+ col))))
1413 (if (and left (= col 1))
1414 (error "Cannot move column further left"))
1415 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1416 (error "Cannot move column further right"))
1417 (goto-char beg)
1418 (while (< (point) end)
1419 (if (org-at-table-hline-p)
1421 (org-table-goto-column col1 t)
1422 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1423 (replace-match "|\\2|\\1|")))
1424 (beginning-of-line 2))
1425 (move-marker end nil)
1426 (org-goto-line linepos)
1427 (org-table-goto-column colpos)
1428 (org-table-align)
1429 (when (or (not org-table-fix-formulas-confirm)
1430 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1431 (org-table-fix-formulas
1432 "$" (list (cons (number-to-string col) (number-to-string colpos))
1433 (cons (number-to-string colpos) (number-to-string col))))
1434 (org-table-fix-formulas
1435 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1436 (cons (number-to-string colpos) (number-to-string col)))))))
1438 ;;;###autoload
1439 (defun org-table-move-row-down ()
1440 "Move table row down."
1441 (interactive)
1442 (org-table-move-row nil))
1443 ;;;###autoload
1444 (defun org-table-move-row-up ()
1445 "Move table row up."
1446 (interactive)
1447 (org-table-move-row 'up))
1449 ;;;###autoload
1450 (defun org-table-move-row (&optional up)
1451 "Move the current table line down. With arg UP, move it up."
1452 (interactive "P")
1453 (let* ((col (current-column))
1454 (pos (point))
1455 (hline1p (save-excursion (beginning-of-line 1)
1456 (looking-at org-table-hline-regexp)))
1457 (dline1 (org-table-current-dline))
1458 (dline2 (+ dline1 (if up -1 1)))
1459 (tonew (if up 0 2))
1460 txt hline2p)
1461 (beginning-of-line tonew)
1462 (unless (org-at-table-p)
1463 (goto-char pos)
1464 (error "Cannot move row further"))
1465 (setq hline2p (looking-at org-table-hline-regexp))
1466 (goto-char pos)
1467 (beginning-of-line 1)
1468 (setq pos (point))
1469 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1470 (delete-region (point) (1+ (point-at-eol)))
1471 (beginning-of-line tonew)
1472 (insert txt)
1473 (beginning-of-line 0)
1474 (org-move-to-column col)
1475 (unless (or hline1p hline2p
1476 (not (or (not org-table-fix-formulas-confirm)
1477 (funcall org-table-fix-formulas-confirm
1478 "Fix formulas? "))))
1479 (org-table-fix-formulas
1480 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1481 (cons (number-to-string dline2) (number-to-string dline1)))))))
1483 ;;;###autoload
1484 (defun org-table-insert-row (&optional arg)
1485 "Insert a new row above the current line into the table.
1486 With prefix ARG, insert below the current line."
1487 (interactive "P")
1488 (if (not (org-at-table-p))
1489 (error "Not at a table"))
1490 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1491 (new (org-table-clean-line line)))
1492 ;; Fix the first field if necessary
1493 (if (string-match "^[ \t]*| *[#$] *|" line)
1494 (setq new (replace-match (match-string 0 line) t t new)))
1495 (beginning-of-line (if arg 2 1))
1496 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1497 (beginning-of-line 0)
1498 (re-search-forward "| ?" (point-at-eol) t)
1499 (and (or org-table-may-need-update org-table-overlay-coordinates)
1500 (org-table-align))
1501 (when (or (not org-table-fix-formulas-confirm)
1502 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1503 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1505 ;;;###autoload
1506 (defun org-table-insert-hline (&optional above)
1507 "Insert a horizontal-line below the current line into the table.
1508 With prefix ABOVE, insert above the current line."
1509 (interactive "P")
1510 (if (not (org-at-table-p))
1511 (error "Not at a table"))
1512 (when (eobp) (insert "\n") (backward-char 1))
1513 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1514 (org-table-align))
1515 (let ((line (org-table-clean-line
1516 (buffer-substring (point-at-bol) (point-at-eol))))
1517 (col (current-column)))
1518 (while (string-match "|\\( +\\)|" line)
1519 (setq line (replace-match
1520 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1521 ?-) "|") t t line)))
1522 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1523 (beginning-of-line (if above 1 2))
1524 (insert line "\n")
1525 (beginning-of-line (if above 1 -1))
1526 (org-move-to-column col)
1527 (and org-table-overlay-coordinates (org-table-align))))
1529 ;;;###autoload
1530 (defun org-table-hline-and-move (&optional same-column)
1531 "Insert a hline and move to the row below that line."
1532 (interactive "P")
1533 (let ((col (org-table-current-column)))
1534 (org-table-maybe-eval-formula)
1535 (org-table-maybe-recalculate-line)
1536 (org-table-insert-hline)
1537 (end-of-line 2)
1538 (if (looking-at "\n[ \t]*|-")
1539 (progn (insert "\n|") (org-table-align))
1540 (org-table-next-field))
1541 (if same-column (org-table-goto-column col))))
1543 (defun org-table-clean-line (s)
1544 "Convert a table line S into a string with only \"|\" and space.
1545 In particular, this does handle wide and invisible characters."
1546 (if (string-match "^[ \t]*|-" s)
1547 ;; It's a hline, just map the characters
1548 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1549 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1550 (setq s (replace-match
1551 (concat "|" (make-string (org-string-width (match-string 1 s))
1552 ?\ ) "|")
1553 t t s)))
1556 ;;;###autoload
1557 (defun org-table-kill-row ()
1558 "Delete the current row or horizontal line from the table."
1559 (interactive)
1560 (if (not (org-at-table-p))
1561 (error "Not at a table"))
1562 (let ((col (current-column))
1563 (dline (org-table-current-dline)))
1564 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1565 (if (not (org-at-table-p)) (beginning-of-line 0))
1566 (org-move-to-column col)
1567 (when (or (not org-table-fix-formulas-confirm)
1568 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1569 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1570 dline -1 dline))))
1572 ;;;###autoload
1573 (defun org-table-sort-lines (with-case &optional sorting-type)
1574 "Sort table lines according to the column at point.
1576 The position of point indicates the column to be used for
1577 sorting, and the range of lines is the range between the nearest
1578 horizontal separator lines, or the entire table of no such lines
1579 exist. If point is before the first column, you will be prompted
1580 for the sorting column. If there is an active region, the mark
1581 specifies the first line and the sorting column, while point
1582 should be in the last line to be included into the sorting.
1584 The command then prompts for the sorting type which can be
1585 alphabetically, numerically, or by time (as given in a time stamp
1586 in the field). Sorting in reverse order is also possible.
1588 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1590 If SORTING-TYPE is specified when this function is called from a Lisp
1591 program, no prompting will take place. SORTING-TYPE must be a character,
1592 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1593 should be done in reverse order."
1594 (interactive "P")
1595 (let* ((thisline (org-current-line))
1596 (thiscol (org-table-current-column))
1597 (otc org-table-overlay-coordinates)
1598 beg end bcol ecol tend tbeg column lns pos)
1599 (when (equal thiscol 0)
1600 (if (org-called-interactively-p 'any)
1601 (setq thiscol
1602 (string-to-number
1603 (read-string "Use column N for sorting: ")))
1604 (setq thiscol 1))
1605 (org-table-goto-column thiscol))
1606 (org-table-check-inside-data-field)
1607 (if (org-region-active-p)
1608 (progn
1609 (setq beg (region-beginning) end (region-end))
1610 (goto-char beg)
1611 (setq column (org-table-current-column)
1612 beg (point-at-bol))
1613 (goto-char end)
1614 (setq end (point-at-bol 2)))
1615 (setq column (org-table-current-column)
1616 pos (point)
1617 tbeg (org-table-begin)
1618 tend (org-table-end))
1619 (if (re-search-backward org-table-hline-regexp tbeg t)
1620 (setq beg (point-at-bol 2))
1621 (goto-char tbeg)
1622 (setq beg (point-at-bol 1)))
1623 (goto-char pos)
1624 (if (re-search-forward org-table-hline-regexp tend t)
1625 (setq end (point-at-bol 1))
1626 (goto-char tend)
1627 (setq end (point-at-bol))))
1628 (setq beg (move-marker (make-marker) beg)
1629 end (move-marker (make-marker) end))
1630 (untabify beg end)
1631 (goto-char beg)
1632 (org-table-goto-column column)
1633 (skip-chars-backward "^|")
1634 (setq bcol (current-column))
1635 (org-table-goto-column (1+ column))
1636 (skip-chars-backward "^|")
1637 (setq ecol (1- (current-column)))
1638 (org-table-goto-column column)
1639 (setq lns (mapcar (lambda(x) (cons
1640 (org-sort-remove-invisible
1641 (nth (1- column)
1642 (org-split-string x "[ \t]*|[ \t]*")))
1644 (org-split-string (buffer-substring beg end) "\n")))
1645 (setq lns (org-do-sort lns "Table" with-case sorting-type))
1646 (when org-table-overlay-coordinates
1647 (org-table-toggle-coordinate-overlays))
1648 (delete-region beg end)
1649 (move-marker beg nil)
1650 (move-marker end nil)
1651 (insert (mapconcat 'cdr lns "\n") "\n")
1652 (org-goto-line thisline)
1653 (org-table-goto-column thiscol)
1654 (when otc (org-table-toggle-coordinate-overlays))
1655 (message "%d lines sorted, based on column %d" (length lns) column)))
1657 ;;;###autoload
1658 (defun org-table-cut-region (beg end)
1659 "Copy region in table to the clipboard and blank all relevant fields.
1660 If there is no active region, use just the field at point."
1661 (interactive (list
1662 (if (org-region-active-p) (region-beginning) (point))
1663 (if (org-region-active-p) (region-end) (point))))
1664 (org-table-copy-region beg end 'cut))
1666 ;;;###autoload
1667 (defun org-table-copy-region (beg end &optional cut)
1668 "Copy rectangular region in table to clipboard.
1669 A special clipboard is used which can only be accessed
1670 with `org-table-paste-rectangle'."
1671 (interactive (list
1672 (if (org-region-active-p) (region-beginning) (point))
1673 (if (org-region-active-p) (region-end) (point))
1674 current-prefix-arg))
1675 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1676 region cols
1677 (rpl (if cut " " nil)))
1678 (goto-char beg)
1679 (org-table-check-inside-data-field)
1680 (setq l01 (org-current-line)
1681 c01 (org-table-current-column))
1682 (goto-char end)
1683 (org-table-check-inside-data-field)
1684 (setq l02 (org-current-line)
1685 c02 (org-table-current-column))
1686 (setq l1 (min l01 l02) l2 (max l01 l02)
1687 c1 (min c01 c02) c2 (max c01 c02))
1688 (catch 'exit
1689 (while t
1690 (catch 'nextline
1691 (if (> l1 l2) (throw 'exit t))
1692 (org-goto-line l1)
1693 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1694 (setq cols nil ic1 c1 ic2 c2)
1695 (while (< ic1 (1+ ic2))
1696 (push (org-table-get-field ic1 rpl) cols)
1697 (setq ic1 (1+ ic1)))
1698 (push (nreverse cols) region)
1699 (setq l1 (1+ l1)))))
1700 (setq org-table-clip (nreverse region))
1701 (if cut (org-table-align))
1702 org-table-clip))
1704 ;;;###autoload
1705 (defun org-table-paste-rectangle ()
1706 "Paste a rectangular region into a table.
1707 The upper right corner ends up in the current field. All involved fields
1708 will be overwritten. If the rectangle does not fit into the present table,
1709 the table is enlarged as needed. The process ignores horizontal separator
1710 lines."
1711 (interactive)
1712 (unless (and org-table-clip (listp org-table-clip))
1713 (error "First cut/copy a region to paste!"))
1714 (org-table-check-inside-data-field)
1715 (let* ((clip org-table-clip)
1716 (line (org-current-line))
1717 (col (org-table-current-column))
1718 (org-enable-table-editor t)
1719 (org-table-automatic-realign nil)
1720 c cols field)
1721 (while (setq cols (pop clip))
1722 (while (org-at-table-hline-p) (beginning-of-line 2))
1723 (if (not (org-at-table-p))
1724 (progn (end-of-line 0) (org-table-next-field)))
1725 (setq c col)
1726 (while (setq field (pop cols))
1727 (org-table-goto-column c nil 'force)
1728 (org-table-get-field nil field)
1729 (setq c (1+ c)))
1730 (beginning-of-line 2))
1731 (org-goto-line line)
1732 (org-table-goto-column col)
1733 (org-table-align)))
1735 ;;;###autoload
1736 (defun org-table-convert ()
1737 "Convert from `org-mode' table to table.el and back.
1738 Obviously, this only works within limits. When an Org-mode table is
1739 converted to table.el, all horizontal separator lines get lost, because
1740 table.el uses these as cell boundaries and has no notion of horizontal lines.
1741 A table.el table can be converted to an Org-mode table only if it does not
1742 do row or column spanning. Multiline cells will become multiple cells.
1743 Beware, Org-mode does not test if the table can be successfully converted - it
1744 blindly applies a recipe that works for simple tables."
1745 (interactive)
1746 (require 'table)
1747 (if (org-at-table.el-p)
1748 ;; convert to Org-mode table
1749 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1750 (end (move-marker (make-marker) (org-table-end t))))
1751 (table-unrecognize-region beg end)
1752 (goto-char beg)
1753 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1754 (replace-match ""))
1755 (goto-char beg))
1756 (if (org-at-table-p)
1757 ;; convert to table.el table
1758 (let ((beg (move-marker (make-marker) (org-table-begin)))
1759 (end (move-marker (make-marker) (org-table-end))))
1760 ;; first, get rid of all horizontal lines
1761 (goto-char beg)
1762 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1763 (replace-match ""))
1764 ;; insert a hline before first
1765 (goto-char beg)
1766 (org-table-insert-hline 'above)
1767 (beginning-of-line -1)
1768 ;; insert a hline after each line
1769 (while (progn (beginning-of-line 3) (< (point) end))
1770 (org-table-insert-hline))
1771 (goto-char beg)
1772 (setq end (move-marker end (org-table-end)))
1773 ;; replace "+" at beginning and ending of hlines
1774 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1775 (replace-match "\\1+-"))
1776 (goto-char beg)
1777 (while (re-search-forward "-|[ \t]*$" end t)
1778 (replace-match "-+"))
1779 (goto-char beg)))))
1781 (defun org-table-transpose-table-at-point ()
1782 "Transpose orgmode table at point and eliminate hlines.
1783 So a table like
1785 | 1 | 2 | 4 | 5 |
1786 |---+---+---+---|
1787 | a | b | c | d |
1788 | e | f | g | h |
1790 will be transposed as
1792 | 1 | a | e |
1793 | 2 | b | f |
1794 | 4 | c | g |
1795 | 5 | d | h |
1797 Note that horizontal lines disappeared."
1798 (interactive)
1799 (let ((contents
1800 (apply #'mapcar* #'list
1801 ;; remove 'hline from list
1802 (delq nil (mapcar (lambda (x) (when (listp x) x))
1803 (org-table-to-lisp))))))
1804 (delete-region (org-table-begin) (org-table-end))
1805 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1806 contents ""))
1807 (org-table-align)))
1809 ;;;###autoload
1810 (defun org-table-wrap-region (arg)
1811 "Wrap several fields in a column like a paragraph.
1812 This is useful if you'd like to spread the contents of a field over several
1813 lines, in order to keep the table compact.
1815 If there is an active region, and both point and mark are in the same column,
1816 the text in the column is wrapped to minimum width for the given number of
1817 lines. Generally, this makes the table more compact. A prefix ARG may be
1818 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1819 formats the selected text to two lines. If the region was longer than two
1820 lines, the remaining lines remain empty. A negative prefix argument reduces
1821 the current number of lines by that amount. The wrapped text is pasted back
1822 into the table. If you formatted it to more lines than it was before, fields
1823 further down in the table get overwritten - so you might need to make space in
1824 the table first.
1826 If there is no region, the current field is split at the cursor position and
1827 the text fragment to the right of the cursor is prepended to the field one
1828 line down.
1830 If there is no region, but you specify a prefix ARG, the current field gets
1831 blank, and the content is appended to the field above."
1832 (interactive "P")
1833 (org-table-check-inside-data-field)
1834 (if (org-region-active-p)
1835 ;; There is a region: fill as a paragraph
1836 (let* ((beg (region-beginning))
1837 (cline (save-excursion (goto-char beg) (org-current-line)))
1838 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1839 nlines)
1840 (org-table-cut-region (region-beginning) (region-end))
1841 (if (> (length (car org-table-clip)) 1)
1842 (error "Region must be limited to single column"))
1843 (setq nlines (if arg
1844 (if (< arg 1)
1845 (+ (length org-table-clip) arg)
1846 arg)
1847 (length org-table-clip)))
1848 (setq org-table-clip
1849 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1850 nil nlines)))
1851 (org-goto-line cline)
1852 (org-table-goto-column ccol)
1853 (org-table-paste-rectangle))
1854 ;; No region, split the current field at point
1855 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1856 (skip-chars-forward "^\r\n|"))
1857 (if arg
1858 ;; combine with field above
1859 (let ((s (org-table-blank-field))
1860 (col (org-table-current-column)))
1861 (beginning-of-line 0)
1862 (while (org-at-table-hline-p) (beginning-of-line 0))
1863 (org-table-goto-column col)
1864 (skip-chars-forward "^|")
1865 (skip-chars-backward " ")
1866 (insert " " (org-trim s))
1867 (org-table-align))
1868 ;; split field
1869 (if (looking-at "\\([^|]+\\)+|")
1870 (let ((s (match-string 1)))
1871 (replace-match " |")
1872 (goto-char (match-beginning 0))
1873 (org-table-next-row)
1874 (insert (org-trim s) " ")
1875 (org-table-align))
1876 (org-table-next-row)))))
1878 (defvar org-field-marker nil)
1880 ;;;###autoload
1881 (defun org-table-edit-field (arg)
1882 "Edit table field in a different window.
1883 This is mainly useful for fields that contain hidden parts.
1884 When called with a \\[universal-argument] prefix, just make the full field visible so that
1885 it can be edited in place."
1886 (interactive "P")
1887 (cond
1888 ((equal arg '(16))
1889 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1890 (arg
1891 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1892 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1893 (remove-text-properties b e '(org-cwidth t invisible t
1894 display t intangible t))
1895 (if (and (boundp 'font-lock-mode) font-lock-mode)
1896 (font-lock-fontify-block))))
1898 (let ((pos (point-marker))
1899 (coord
1900 (if (eq org-table-use-standard-references t)
1901 (concat (org-number-to-letters (org-table-current-column))
1902 (int-to-string (org-table-current-dline)))
1903 (concat "@" (int-to-string (org-table-current-dline))
1904 "$" (int-to-string (org-table-current-column)))))
1905 (field (org-table-get-field))
1906 (cw (current-window-configuration))
1908 (goto-char pos)
1909 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1910 (when (and (local-variable-p 'org-field-marker)
1911 (markerp org-field-marker))
1912 (move-marker org-field-marker nil))
1913 (erase-buffer)
1914 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
1915 (let ((org-inhibit-startup t)) (org-mode))
1916 (auto-fill-mode -1)
1917 (setq truncate-lines nil)
1918 (setq word-wrap t)
1919 (goto-char (setq p (point-max)))
1920 (insert (org-trim field))
1921 (remove-text-properties p (point-max)
1922 '(invisible t org-cwidth t display t
1923 intangible t))
1924 (goto-char p)
1925 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
1926 (org-set-local 'org-window-configuration cw)
1927 (org-set-local 'org-field-marker pos)
1928 (message "Edit and finish with C-c C-c")))))
1930 (defun org-table-finish-edit-field ()
1931 "Finish editing a table data field.
1932 Remove all newline characters, insert the result into the table, realign
1933 the table and kill the editing buffer."
1934 (let ((pos org-field-marker)
1935 (cw org-window-configuration)
1936 (cb (current-buffer))
1937 text)
1938 (goto-char (point-min))
1939 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
1940 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
1941 (replace-match " "))
1942 (setq text (org-trim (buffer-string)))
1943 (set-window-configuration cw)
1944 (kill-buffer cb)
1945 (select-window (get-buffer-window (marker-buffer pos)))
1946 (goto-char pos)
1947 (move-marker pos nil)
1948 (org-table-check-inside-data-field)
1949 (org-table-get-field nil text)
1950 (org-table-align)
1951 (message "New field value inserted")))
1953 (define-minor-mode org-table-follow-field-mode
1954 "Minor mode to make the table field editor window follow the cursor.
1955 When this mode is active, the field editor window will always show the
1956 current field. The mode exits automatically when the cursor leaves the
1957 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1958 nil " TblFollow" nil
1959 (if org-table-follow-field-mode
1960 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
1961 'append 'local)
1962 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
1963 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1964 (win (and buf (get-buffer-window buf))))
1965 (when win (delete-window win))
1966 (when buf
1967 (with-current-buffer buf
1968 (move-marker org-field-marker nil))
1969 (kill-buffer buf)))))
1971 (defun org-table-follow-fields-with-editor ()
1972 (if (and org-table-exit-follow-field-mode-when-leaving-table
1973 (not (org-at-table-p)))
1974 ;; We have left the table, exit the follow mode
1975 (org-table-follow-field-mode -1)
1976 (when (org-table-check-inside-data-field 'noerror)
1977 (let ((win (selected-window)))
1978 (org-table-edit-field nil)
1979 (org-fit-window-to-buffer)
1980 (select-window win)))))
1982 (defvar org-timecnt) ; dynamically scoped parameter
1984 ;;;###autoload
1985 (defun org-table-sum (&optional beg end nlast)
1986 "Sum numbers in region of current table column.
1987 The result will be displayed in the echo area, and will be available
1988 as kill to be inserted with \\[yank].
1990 If there is an active region, it is interpreted as a rectangle and all
1991 numbers in that rectangle will be summed. If there is no active
1992 region and point is located in a table column, sum all numbers in that
1993 column.
1995 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1996 numbers are assumed to be times as well (in decimal hours) and the
1997 numbers are added as such.
1999 If NLAST is a number, only the NLAST fields will actually be summed."
2000 (interactive)
2001 (save-excursion
2002 (let (col (org-timecnt 0) diff h m s org-table-clip)
2003 (cond
2004 ((and beg end)) ; beg and end given explicitly
2005 ((org-region-active-p)
2006 (setq beg (region-beginning) end (region-end)))
2008 (setq col (org-table-current-column))
2009 (goto-char (org-table-begin))
2010 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2011 (error "No table data"))
2012 (org-table-goto-column col)
2013 (setq beg (point))
2014 (goto-char (org-table-end))
2015 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2016 (error "No table data"))
2017 (org-table-goto-column col)
2018 (setq end (point))))
2019 (let* ((items (apply 'append (org-table-copy-region beg end)))
2020 (items1 (cond ((not nlast) items)
2021 ((>= nlast (length items)) items)
2022 (t (setq items (reverse items))
2023 (setcdr (nthcdr (1- nlast) items) nil)
2024 (nreverse items))))
2025 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2026 items1)))
2027 (res (apply '+ numbers))
2028 (sres (if (= org-timecnt 0)
2029 (number-to-string res)
2030 (setq diff (* 3600 res)
2031 h (floor (/ diff 3600)) diff (mod diff 3600)
2032 m (floor (/ diff 60)) diff (mod diff 60)
2033 s diff)
2034 (format "%d:%02d:%02d" h m s))))
2035 (kill-new sres)
2036 (if (org-called-interactively-p 'interactive)
2037 (message "%s"
2038 (substitute-command-keys
2039 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2040 (length numbers) sres))))
2041 sres))))
2043 (defun org-table-get-number-for-summing (s)
2044 (let (n)
2045 (if (string-match "^ *|? *" s)
2046 (setq s (replace-match "" nil nil s)))
2047 (if (string-match " *|? *$" s)
2048 (setq s (replace-match "" nil nil s)))
2049 (setq n (string-to-number s))
2050 (cond
2051 ((and (string-match "0" s)
2052 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2053 ((string-match "\\`[ \t]+\\'" s) nil)
2054 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2055 (let ((h (string-to-number (or (match-string 1 s) "0")))
2056 (m (string-to-number (or (match-string 2 s) "0")))
2057 (s (string-to-number (or (match-string 4 s) "0"))))
2058 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2059 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2060 ((equal n 0) nil)
2061 (t n))))
2063 (defun org-table-current-field-formula (&optional key noerror)
2064 "Return the formula active for the current field.
2065 Assumes that specials are in place.
2066 If KEY is given, return the key to this formula.
2067 Otherwise return the formula preceded with \"=\" or \":=\"."
2068 (let* ((name (car (rassoc (list (org-current-line)
2069 (org-table-current-column))
2070 org-table-named-field-locations)))
2071 (col (org-table-current-column))
2072 (scol (int-to-string col))
2073 (ref (format "@%d$%d" (org-table-current-dline) col))
2074 (stored-list (org-table-get-stored-formulas noerror))
2075 (ass (or (assoc name stored-list)
2076 (assoc ref stored-list)
2077 (assoc scol stored-list))))
2078 (if key
2079 (car ass)
2080 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2081 (cdr ass))))))
2083 (defun org-table-get-formula (&optional equation named)
2084 "Read a formula from the minibuffer, offer stored formula as default.
2085 When NAMED is non-nil, look for a named equation."
2086 (let* ((stored-list (org-table-get-stored-formulas))
2087 (name (car (rassoc (list (org-current-line)
2088 (org-table-current-column))
2089 org-table-named-field-locations)))
2090 (ref (format "@%d$%d" (org-table-current-dline)
2091 (org-table-current-column)))
2092 (refass (assoc ref stored-list))
2093 (nameass (assoc name stored-list))
2094 (scol (if named
2095 (if (and name (not (string-match "^LR[0-9]+$" name)))
2096 name
2097 ref)
2098 (int-to-string (org-table-current-column))))
2099 (dummy (and (or nameass refass) (not named)
2100 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2101 (error "Abort")))
2102 (name (or name ref))
2103 (org-table-may-need-update nil)
2104 (stored (cdr (assoc scol stored-list)))
2105 (eq (cond
2106 ((and stored equation (string-match "^ *=? *$" equation))
2107 stored)
2108 ((stringp equation)
2109 equation)
2110 (t (org-table-formula-from-user
2111 (read-string
2112 (org-table-formula-to-user
2113 (format "%s formula %s%s="
2114 (if named "Field" "Column")
2115 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2116 scol))
2117 (if stored (org-table-formula-to-user stored) "")
2118 'org-table-formula-history
2119 )))))
2120 mustsave)
2121 (when (not (string-match "\\S-" eq))
2122 ;; remove formula
2123 (setq stored-list (delq (assoc scol stored-list) stored-list))
2124 (org-table-store-formulas stored-list)
2125 (error "Formula removed"))
2126 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2127 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2128 (if (and name (not named))
2129 ;; We set the column equation, delete the named one.
2130 (setq stored-list (delq (assoc name stored-list) stored-list)
2131 mustsave t))
2132 (if stored
2133 (setcdr (assoc scol stored-list) eq)
2134 (setq stored-list (cons (cons scol eq) stored-list)))
2135 (if (or mustsave (not (equal stored eq)))
2136 (org-table-store-formulas stored-list))
2137 eq))
2139 (defun org-table-store-formulas (alist)
2140 "Store the list of formulas below the current table."
2141 (setq alist (sort alist 'org-table-formula-less-p))
2142 (let ((case-fold-search t))
2143 (save-excursion
2144 (goto-char (org-table-end))
2145 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2146 (progn
2147 ;; don't overwrite TBLFM, we might use text properties to store stuff
2148 (goto-char (match-beginning 3))
2149 (delete-region (match-beginning 3) (match-end 0)))
2150 (org-indent-line)
2151 (insert (or (match-string 2) "#+TBLFM:")))
2152 (insert " "
2153 (mapconcat (lambda (x)
2154 (concat
2155 (if (equal (string-to-char (car x)) ?@) "" "$")
2156 (car x) "=" (cdr x)))
2157 alist "::")
2158 "\n"))))
2160 (defsubst org-table-formula-make-cmp-string (a)
2161 (when (string-match "\\`$[<>]" a)
2162 (let ((arrow (string-to-char (substring a 1))))
2163 ;; Fake a high number to make sure this is sorted at the end.
2164 (setq a (org-table-formula-handle-first/last-rc a))
2165 (setq a (format "$%d" (+ 10000
2166 (if (= arrow ?<) -1000 0)
2167 (string-to-number (substring a 1)))))))
2168 (when (string-match
2169 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2171 (concat
2172 (if (match-end 2)
2173 (format "@%05d" (string-to-number (match-string 2 a))) "")
2174 (if (match-end 4)
2175 (format "$%05d" (string-to-number (match-string 4 a))) "")
2176 (if (match-end 5)
2177 (concat "@@" (match-string 5 a))))))
2179 (defun org-table-formula-less-p (a b)
2180 "Compare two formulas for sorting."
2181 (let ((as (org-table-formula-make-cmp-string (car a)))
2182 (bs (org-table-formula-make-cmp-string (car b))))
2183 (and as bs (string< as bs))))
2185 ;;;###autoload
2186 (defun org-table-get-stored-formulas (&optional noerror)
2187 "Return an alist with the stored formulas directly after current table."
2188 (interactive) ;; FIXME interactive?
2189 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2190 (save-excursion
2191 (goto-char (org-table-end))
2192 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2193 (setq strings (org-split-string (org-match-string-no-properties 2)
2194 " *:: *"))
2195 (while (setq string (pop strings))
2196 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2197 (setq scol (if (match-end 2)
2198 (match-string 2 string)
2199 (match-string 1 string))
2200 scol (if (member (string-to-char scol) '(?< ?>))
2201 (concat "$" scol) scol)
2202 eq (match-string 3 string)
2203 eq-alist (cons (cons scol eq) eq-alist))
2204 (if (member scol seen)
2205 (if noerror
2206 (progn
2207 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2208 (ding)
2209 (sit-for 2))
2210 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2211 (push scol seen))))))
2212 (nreverse eq-alist)))
2214 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2215 "Modify the equations after the table structure has been edited.
2216 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2217 For all numbers larger than LIMIT, shift them by DELTA."
2218 (save-excursion
2219 (goto-char (org-table-end))
2220 (when (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2221 (let ((msg "The formulas in #+TBLFM have been updated")
2222 (re (concat key "\\([0-9]+\\)"))
2223 (re2
2224 (when remove
2225 (if (or (equal key "$") (equal key "$LR"))
2226 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2227 (regexp-quote key) remove)
2228 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2229 s n a)
2230 (when remove
2231 (while (re-search-forward re2 (point-at-eol) t)
2232 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2233 (if (equal (char-before (match-beginning 0)) ?.)
2234 (error "Change makes TBLFM term %s invalid, use undo to recover"
2235 (match-string 0))
2236 (replace-match "")))))
2237 (while (re-search-forward re (point-at-eol) t)
2238 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2239 (setq s (match-string 1) n (string-to-number s))
2240 (cond
2241 ((setq a (assoc s replace))
2242 (replace-match (concat key (cdr a)) t t)
2243 (message msg))
2244 ((and limit (> n limit))
2245 (replace-match (concat key (int-to-string (+ n delta))) t t)
2246 (message msg)))))))))
2248 (defun org-table-get-specials ()
2249 "Get the column names and local parameters for this table."
2250 (save-excursion
2251 (let ((beg (org-table-begin)) (end (org-table-end))
2252 names name fields fields1 field cnt
2253 c v l line col types dlines hlines last-dline)
2254 (setq org-table-column-names nil
2255 org-table-local-parameters nil
2256 org-table-named-field-locations nil
2257 org-table-current-begin-line nil
2258 org-table-current-begin-pos nil
2259 org-table-current-line-types nil
2260 org-table-current-ncol 0)
2261 (goto-char beg)
2262 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2263 (setq names (org-split-string (match-string 1) " *| *")
2264 cnt 1)
2265 (while (setq name (pop names))
2266 (setq cnt (1+ cnt))
2267 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
2268 (push (cons name (int-to-string cnt)) org-table-column-names))))
2269 (setq org-table-column-names (nreverse org-table-column-names))
2270 (setq org-table-column-name-regexp
2271 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2272 (goto-char beg)
2273 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2274 (setq fields (org-split-string (match-string 1) " *| *"))
2275 (while (setq field (pop fields))
2276 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2277 (push (cons (match-string 1 field) (match-string 2 field))
2278 org-table-local-parameters))))
2279 (goto-char beg)
2280 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2281 (setq c (match-string 1)
2282 fields (org-split-string (match-string 2) " *| *"))
2283 (save-excursion
2284 (beginning-of-line (if (equal c "_") 2 0))
2285 (setq line (org-current-line) col 1)
2286 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2287 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2288 (while (and fields1 (setq field (pop fields)))
2289 (setq v (pop fields1) col (1+ col))
2290 (when (and (stringp field) (stringp v)
2291 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
2292 (push (cons field v) org-table-local-parameters)
2293 (push (list field line col) org-table-named-field-locations))))
2294 ;; Analyse the line types
2295 (goto-char beg)
2296 (setq org-table-current-begin-line (org-current-line)
2297 org-table-current-begin-pos (point)
2298 l org-table-current-begin-line)
2299 (while (looking-at "[ \t]*|\\(-\\)?")
2300 (push (if (match-end 1) 'hline 'dline) types)
2301 (if (match-end 1) (push l hlines) (push l dlines))
2302 (beginning-of-line 2)
2303 (setq l (1+ l)))
2304 (push 'hline types) ;; add an imaginary extra hline to the end
2305 (setq org-table-current-line-types (apply 'vector (nreverse types))
2306 last-dline (car dlines)
2307 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2308 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2309 (org-goto-line last-dline)
2310 (let* ((l last-dline)
2311 (fields (org-split-string
2312 (buffer-substring (point-at-bol) (point-at-eol))
2313 "[ \t]*|[ \t]*"))
2314 (nfields (length fields))
2315 al al2)
2316 (setq org-table-current-ncol nfields)
2317 (loop for i from 1 to nfields do
2318 (push (list (format "LR%d" i) l i) al)
2319 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2320 (setq org-table-named-field-locations
2321 (append org-table-named-field-locations al))
2322 (setq org-table-local-parameters
2323 (append org-table-local-parameters al2))))))
2325 ;;;###autoload
2326 (defun org-table-maybe-eval-formula ()
2327 "Check if the current field starts with \"=\" or \":=\".
2328 If yes, store the formula and apply it."
2329 ;; We already know we are in a table. Get field will only return a formula
2330 ;; when appropriate. It might return a separator line, but no problem.
2331 (when org-table-formula-evaluate-inline
2332 (let* ((field (org-trim (or (org-table-get-field) "")))
2333 named eq)
2334 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2335 (setq named (equal (string-to-char field) ?:)
2336 eq (match-string 1 field))
2337 (if (or (fboundp 'calc-eval)
2338 (equal (substring eq 0 (min 2 (length eq))) "'("))
2339 (org-table-eval-formula (if named '(4) nil)
2340 (org-table-formula-from-user eq))
2341 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2343 (defvar org-recalc-commands nil
2344 "List of commands triggering the recalculation of a line.
2345 Will be filled automatically during use.")
2347 (defvar org-recalc-marks
2348 '((" " . "Unmarked: no special line, no automatic recalculation")
2349 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2350 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2351 ("!" . "Column name definition line. Reference in formula as $name.")
2352 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2353 ("_" . "Names for values in row below this one.")
2354 ("^" . "Names for values in row above this one.")))
2356 ;;;###autoload
2357 (defun org-table-rotate-recalc-marks (&optional newchar)
2358 "Rotate the recalculation mark in the first column.
2359 If in any row, the first field is not consistent with a mark,
2360 insert a new column for the markers.
2361 When there is an active region, change all the lines in the region,
2362 after prompting for the marking character.
2363 After each change, a message will be displayed indicating the meaning
2364 of the new mark."
2365 (interactive)
2366 (unless (org-at-table-p) (error "Not at a table"))
2367 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2368 (beg (org-table-begin))
2369 (end (org-table-end))
2370 (l (org-current-line))
2371 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2372 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2373 (have-col
2374 (save-excursion
2375 (goto-char beg)
2376 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2377 (col (org-table-current-column))
2378 (forcenew (car (assoc newchar org-recalc-marks)))
2379 epos new)
2380 (when l1
2381 (message "Change region to what mark? Type # * ! $ or SPC: ")
2382 (setq newchar (char-to-string (read-char-exclusive))
2383 forcenew (car (assoc newchar org-recalc-marks))))
2384 (if (and newchar (not forcenew))
2385 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2386 newchar))
2387 (if l1 (org-goto-line l1))
2388 (save-excursion
2389 (beginning-of-line 1)
2390 (unless (looking-at org-table-dataline-regexp)
2391 (error "Not at a table data line")))
2392 (unless have-col
2393 (org-table-goto-column 1)
2394 (org-table-insert-column)
2395 (org-table-goto-column (1+ col)))
2396 (setq epos (point-at-eol))
2397 (save-excursion
2398 (beginning-of-line 1)
2399 (org-table-get-field
2400 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2401 (concat " "
2402 (setq new (or forcenew
2403 (cadr (member (match-string 1) marks))))
2404 " ")
2405 " # ")))
2406 (if (and l1 l2)
2407 (progn
2408 (org-goto-line l1)
2409 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2410 (and (looking-at org-table-dataline-regexp)
2411 (org-table-get-field 1 (concat " " new " "))))
2412 (org-goto-line l1)))
2413 (if (not (= epos (point-at-eol))) (org-table-align))
2414 (org-goto-line l)
2415 (and (org-called-interactively-p 'interactive)
2416 (message "%s" (cdr (assoc new org-recalc-marks))))))
2418 ;;;###autoload
2419 (defun org-table-maybe-recalculate-line ()
2420 "Recompute the current line if marked for it, and if we haven't just done it."
2421 (interactive)
2422 (and org-table-allow-automatic-line-recalculation
2423 (not (and (memq last-command org-recalc-commands)
2424 (equal org-last-recalc-line (org-current-line))))
2425 (save-excursion (beginning-of-line 1)
2426 (looking-at org-table-auto-recalculate-regexp))
2427 (org-table-recalculate) t))
2429 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2430 (defsubst org-set-calc-mode (var &optional value)
2431 (if (stringp var)
2432 (setq var (assoc var '(("D" calc-angle-mode deg)
2433 ("R" calc-angle-mode rad)
2434 ("F" calc-prefer-frac t)
2435 ("S" calc-symbolic-mode t)))
2436 value (nth 2 var) var (nth 1 var)))
2437 (if (memq var org-tbl-calc-modes)
2438 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2439 (cons var (cons value org-tbl-calc-modes)))
2440 org-tbl-calc-modes)
2442 ;;;###autoload
2443 (defun org-table-eval-formula (&optional arg equation
2444 suppress-align suppress-const
2445 suppress-store suppress-analysis)
2446 "Replace the table field value at the cursor by the result of a calculation.
2448 This function makes use of Dave Gillespie's Calc package, in my view the
2449 most exciting program ever written for GNU Emacs. So you need to have Calc
2450 installed in order to use this function.
2452 In a table, this command replaces the value in the current field with the
2453 result of a formula. It also installs the formula as the \"current\" column
2454 formula, by storing it in a special line below the table. When called
2455 with a `C-u' prefix, the current field must be a named field, and the
2456 formula is installed as valid in only this specific field.
2458 When called with two `C-u' prefixes, insert the active equation
2459 for the field back into the current field, so that it can be
2460 edited there. This is useful in order to use \\[org-table-show-reference]
2461 to check the referenced fields.
2463 When called, the command first prompts for a formula, which is read in
2464 the minibuffer. Previously entered formulas are available through the
2465 history list, and the last used formula is offered as a default.
2466 These stored formulas are adapted correctly when moving, inserting, or
2467 deleting columns with the corresponding commands.
2469 The formula can be any algebraic expression understood by the Calc package.
2470 For details, see the Org-mode manual.
2472 This function can also be called from Lisp programs and offers
2473 additional arguments: EQUATION can be the formula to apply. If this
2474 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2475 used to speed-up recursive calls by by-passing unnecessary aligns.
2476 SUPPRESS-CONST suppresses the interpretation of constants in the
2477 formula, assuming that this has been done already outside the function.
2478 SUPPRESS-STORE means the formula should not be stored, either because
2479 it is already stored, or because it is a modified equation that should
2480 not overwrite the stored one."
2481 (interactive "P")
2482 (org-table-check-inside-data-field)
2483 (or suppress-analysis (org-table-get-specials))
2484 (if (equal arg '(16))
2485 (let ((eq (org-table-current-field-formula)))
2486 (or eq (error "No equation active for current field"))
2487 (org-table-get-field nil eq)
2488 (org-table-align)
2489 (setq org-table-may-need-update t))
2490 (let* (fields
2491 (ndown (if (integerp arg) arg 1))
2492 (org-table-automatic-realign nil)
2493 (case-fold-search nil)
2494 (down (> ndown 1))
2495 (formula (if (and equation suppress-store)
2496 equation
2497 (org-table-get-formula equation (equal arg '(4)))))
2498 (n0 (org-table-current-column))
2499 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2500 (numbers nil) ; was a variable, now fixed default
2501 (keep-empty nil)
2502 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2503 duration duration-output-format)
2504 ;; Parse the format string. Since we have a lot of modes, this is
2505 ;; a lot of work. However, I think calc still uses most of the time.
2506 (if (string-match ";" formula)
2507 (let ((tmp (org-split-string formula ";")))
2508 (setq formula (car tmp)
2509 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2510 (nth 1 tmp)))
2511 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2512 (setq c (string-to-char (match-string 1 fmt))
2513 n (string-to-number (match-string 2 fmt)))
2514 (if (= c ?p)
2515 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2516 (setq org-tbl-calc-modes
2517 (org-set-calc-mode
2518 'calc-float-format
2519 (list (cdr (assoc c '((?n . float) (?f . fix)
2520 (?s . sci) (?e . eng))))
2521 n))))
2522 (setq fmt (replace-match "" t t fmt)))
2523 (if (string-match "T" fmt)
2524 (setq duration t numbers t
2525 duration-output-format nil
2526 fmt (replace-match "" t t fmt)))
2527 (if (string-match "t" fmt)
2528 (setq duration t
2529 duration-output-format org-table-duration-custom-format
2530 numbers t
2531 fmt (replace-match "" t t fmt)))
2532 (if (string-match "N" fmt)
2533 (setq numbers t
2534 fmt (replace-match "" t t fmt)))
2535 (if (string-match "L" fmt)
2536 (setq literal t
2537 fmt (replace-match "" t t fmt)))
2538 (if (string-match "E" fmt)
2539 (setq keep-empty t
2540 fmt (replace-match "" t t fmt)))
2541 (while (string-match "[DRFS]" fmt)
2542 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2543 (setq fmt (replace-match "" t t fmt)))
2544 (unless (string-match "\\S-" fmt)
2545 (setq fmt nil))))
2546 (if (and (not suppress-const) org-table-formula-use-constants)
2547 (setq formula (org-table-formula-substitute-names formula)))
2548 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2549 (while (> ndown 0)
2550 (setq fields (org-split-string
2551 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2552 " *| *"))
2553 ;; replace fields with duration values if relevant
2554 (if duration
2555 (setq fields
2556 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2557 fields)))
2558 (if (eq numbers t)
2559 (setq fields (mapcar
2560 (lambda (x)
2561 (if (string-match "\\S-" x)
2562 (number-to-string (string-to-number x))
2564 fields)))
2565 (setq ndown (1- ndown))
2566 (setq form (copy-sequence formula)
2567 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2568 (if (and lispp literal) (setq lispp 'literal))
2570 ;; Insert row and column number of formula result field
2571 (while (string-match "[@$]#" form)
2572 (setq form
2573 (replace-match
2574 (format "%d"
2575 (save-match-data
2576 (if (equal (substring form (match-beginning 0)
2577 (1+ (match-beginning 0)))
2578 "@")
2579 (org-table-current-dline)
2580 (org-table-current-column))))
2581 t t form)))
2583 ;; Check for old vertical references
2584 (setq form (org-table-rewrite-old-row-references form))
2585 ;; Insert remote references
2586 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2587 (setq form
2588 (replace-match
2589 (save-match-data
2590 (org-table-make-reference
2591 (let ((rmtrng (org-table-get-remote-range
2592 (match-string 1 form) (match-string 2 form))))
2593 (if duration
2594 (if (listp rmtrng)
2595 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2596 (org-table-time-string-to-seconds rmtrng))
2597 rmtrng))
2598 keep-empty numbers lispp))
2599 t t form)))
2600 ;; Insert complex ranges
2601 (while (and (string-match org-table-range-regexp form)
2602 (> (length (match-string 0 form)) 1))
2603 (setq formrg (save-match-data
2604 (org-table-get-range (match-string 0 form) nil n0)))
2605 (setq formrpl
2606 (save-match-data
2607 (org-table-make-reference
2608 ;; possibly handle durations
2609 (if duration
2610 (if (listp formrg)
2611 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2612 (org-table-time-string-to-seconds formrg))
2613 formrg)
2614 keep-empty numbers lispp)))
2615 (if (not (save-match-data
2616 (string-match (regexp-quote form) formrpl)))
2617 (setq form (replace-match formrpl t t form))
2618 (error "Spreadsheet error: invalid reference \"%s\"" form)))
2619 ;; Insert simple ranges
2620 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2621 (setq form
2622 (replace-match
2623 (save-match-data
2624 (org-table-make-reference
2625 (org-sublist
2626 fields (string-to-number (match-string 1 form))
2627 (string-to-number (match-string 2 form)))
2628 keep-empty numbers lispp))
2629 t t form)))
2630 (setq form0 form)
2631 ;; Insert the references to fields in same row
2632 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2633 (setq n (+ (string-to-number (match-string 1 form))
2634 (if (match-end 2) n0 0))
2635 x (nth (1- (if (= n 0) n0 (max n 1))) fields))
2636 (unless x (error "Invalid field specifier \"%s\""
2637 (match-string 0 form)))
2638 (setq form (replace-match
2639 (save-match-data
2640 (org-table-make-reference
2641 x keep-empty numbers lispp))
2642 t t form)))
2644 (if lispp
2645 (setq ev (condition-case nil
2646 (eval (eval (read form)))
2647 (error "#ERROR"))
2648 ev (if (numberp ev) (number-to-string ev) ev)
2649 ev (if duration (org-table-time-seconds-to-string
2650 (string-to-number ev)
2651 duration-output-format) ev))
2652 (or (fboundp 'calc-eval)
2653 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2654 ;; Use <...> time-stamps so that Calc can handle them
2655 (setq form (replace-regexp-in-string org-ts-regexp3 "<\\1>" form))
2656 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2657 (when (string-match org-ts-regexp2 form)
2658 (let* ((ts (match-string 0 form))
2659 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2660 (system-time-locale "C")
2661 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2662 (cdr org-time-stamp-formats))
2663 (car org-time-stamp-formats))))
2664 (setq form (replace-match (format-time-string tf tsp) t t form))))
2666 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2667 form
2668 (calc-eval (cons form org-tbl-calc-modes)
2669 (when (and (not keep-empty) numbers) 'num)))
2670 ev (if duration (org-table-time-seconds-to-string
2671 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2672 (string-to-number (org-table-time-string-to-seconds ev))
2673 (string-to-number ev))
2674 duration-output-format)
2675 ev)))
2677 (when org-table-formula-debug
2678 (with-output-to-temp-buffer "*Substitution History*"
2679 (princ (format "Substitution history of formula
2680 Orig: %s
2681 $xyz-> %s
2682 @r$c-> %s
2683 $1-> %s\n" orig formula form0 form))
2684 (if (listp ev)
2685 (princ (format " %s^\nError: %s"
2686 (make-string (car ev) ?\-) (nth 1 ev)))
2687 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2688 ev (or fmt "NONE")
2689 (if fmt (format fmt (string-to-number ev)) ev)))))
2690 (setq bw (get-buffer-window "*Substitution History*"))
2691 (org-fit-window-to-buffer bw)
2692 (unless (and (org-called-interactively-p 'any) (not ndown))
2693 (unless (let (inhibit-redisplay)
2694 (y-or-n-p "Debugging Formula. Continue to next? "))
2695 (org-table-align)
2696 (error "Abort"))
2697 (delete-window bw)
2698 (message "")))
2699 (if (listp ev) (setq fmt nil ev "#ERROR"))
2700 (org-table-justify-field-maybe
2701 (format org-table-formula-field-format
2702 (if fmt (format fmt (string-to-number ev)) ev)))
2703 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2704 (call-interactively 'org-return)
2705 (setq ndown 0)))
2706 (and down (org-table-maybe-recalculate-line))
2707 (or suppress-align (and org-table-may-need-update
2708 (org-table-align))))))
2710 (defun org-table-put-field-property (prop value)
2711 (save-excursion
2712 (put-text-property (progn (skip-chars-backward "^|") (point))
2713 (progn (skip-chars-forward "^|") (point))
2714 prop value)))
2716 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2717 "Get a calc vector from a column, according to descriptor DESC.
2718 Optional arguments TBEG and COL can give the beginning of the table and
2719 the current column, to avoid unnecessary parsing.
2721 HIGHLIGHT means just highlight the range.
2723 When CORNERS-ONLY is set, only return the corners of the range as
2724 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2725 in the buffer and column1 and column2 are table column numbers."
2726 (if (not (equal (string-to-char desc) ?@))
2727 (setq desc (concat "@" desc)))
2728 (save-excursion
2729 (or tbeg (setq tbeg (org-table-begin)))
2730 (or col (setq col (org-table-current-column)))
2731 (let ((thisline (org-current-line))
2732 beg end c1 c2 r1 r2 rangep tmp)
2733 (unless (string-match org-table-range-regexp desc)
2734 (error "Invalid table range specifier `%s'" desc))
2735 (setq rangep (match-end 3)
2736 r1 (and (match-end 1) (match-string 1 desc))
2737 r2 (and (match-end 4) (match-string 4 desc))
2738 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2739 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2741 (and c1 (setq c1 (+ (string-to-number c1)
2742 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2743 (and c2 (setq c2 (+ (string-to-number c2)
2744 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2745 (if (equal r1 "") (setq r1 nil))
2746 (if (equal r2 "") (setq r2 nil))
2747 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2748 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2749 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2750 (if (not r1) (setq r1 thisline))
2751 (if (not r2) (setq r2 thisline))
2752 (if (or (not c1) (= 0 c1)) (setq c1 col))
2753 (if (or (not c2) (= 0 c2)) (setq c2 col))
2754 (if (and (not corners-only)
2755 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2756 ;; just one field
2757 (progn
2758 (org-goto-line r1)
2759 (while (not (looking-at org-table-dataline-regexp))
2760 (beginning-of-line 2))
2761 (prog1 (org-trim (org-table-get-field c1))
2762 (if highlight (org-table-highlight-rectangle (point) (point)))))
2763 ;; A range, return a vector
2764 ;; First sort the numbers to get a regular rectangle
2765 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2766 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2767 (if corners-only
2768 ;; Only return the corners of the range
2769 (list r1 c1 r2 c2)
2770 ;; Copy the range values into a list
2771 (org-goto-line r1)
2772 (while (not (looking-at org-table-dataline-regexp))
2773 (beginning-of-line 2))
2774 (org-table-goto-column c1)
2775 (setq beg (point))
2776 (org-goto-line r2)
2777 (while (not (looking-at org-table-dataline-regexp))
2778 (beginning-of-line 0))
2779 (org-table-goto-column c2)
2780 (setq end (point))
2781 (if highlight
2782 (org-table-highlight-rectangle
2783 beg (progn (skip-chars-forward "^|\n") (point))))
2784 ;; return string representation of calc vector
2785 (mapcar 'org-trim
2786 (apply 'append (org-table-copy-region beg end))))))))
2788 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2789 "Analyze descriptor DESC and retrieve the corresponding line number.
2790 The cursor is currently in line CLINE, the table begins in line BLINE,
2791 and TABLE is a vector with line types."
2792 (if (string-match "^[0-9]+$" desc)
2793 (aref org-table-dlines (string-to-number desc))
2794 (setq cline (or cline (org-current-line))
2795 bline (or bline org-table-current-begin-line)
2796 table (or table org-table-current-line-types))
2797 (if (or
2798 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2799 ;; 1 2 3 4 5 6
2800 (and (not (match-end 3)) (not (match-end 6)))
2801 (and (match-end 3) (match-end 6) (not (match-end 5))))
2802 (error "Invalid row descriptor `%s'" desc))
2803 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2804 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2805 (odir (and (match-end 5) (match-string 5 desc)))
2806 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2807 (i (- cline bline))
2808 (rel (and (match-end 6)
2809 (or (and (match-end 1) (not (match-end 3)))
2810 (match-end 5)))))
2811 (if (and hn (not hdir))
2812 (progn
2813 (setq i 0 hdir "+")
2814 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2815 (if (and (not hn) on (not odir))
2816 (error "Should never happen");;(aref org-table-dlines on)
2817 (if (and hn (> hn 0))
2818 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2819 nil hn cline desc)))
2820 (if on
2821 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2822 rel on cline desc)))
2823 (+ bline i)))))
2825 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2826 "FIXME: Needs more documentation."
2827 (let ((l (length table)))
2828 (while (> n 0)
2829 (while (and (setq i (+ i (if backwards -1 1)))
2830 (>= i 0) (< i l)
2831 (not (eq (aref table i) type))
2832 (if (and relative (eq (aref table i) 'hline))
2833 (cond
2834 ((eq org-table-relative-ref-may-cross-hline t) t)
2835 ((eq org-table-relative-ref-may-cross-hline 'error)
2836 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2837 (t (setq i (- i (if backwards -1 1))
2838 n 1)
2839 nil))
2840 t)))
2841 (setq n (1- n)))
2842 (if (or (< i 0) (>= i l))
2843 (error "Row descriptor %s used in line %d leads outside table"
2844 desc cline)
2845 i)))
2847 (defun org-table-rewrite-old-row-references (s)
2848 (if (string-match "&[-+0-9I]" s)
2849 (error "Formula contains old &row reference, please rewrite using @-syntax")
2852 (defun org-table-make-reference (elements keep-empty numbers lispp)
2853 "Convert list ELEMENTS to something appropriate to insert into formula.
2854 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2855 NUMBERS indicates that everything should be converted to numbers.
2856 LISPP non-nil means to return something appropriate for a Lisp
2857 list, 'literal is for the format specifier L."
2858 ;; Calc nan (not a number) is used for the conversion of the empty
2859 ;; field to a reference for several reasons: (i) It is accepted in a
2860 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2861 ;; (ii) In a single field (not in range) it can be distinguished
2862 ;; from "(nan)" which is the reference made from a single field
2863 ;; containing "nan".
2864 (if (stringp elements)
2865 ;; field reference
2866 (if lispp
2867 (if (eq lispp 'literal)
2868 elements
2869 (prin1-to-string (if numbers (string-to-number elements) elements)))
2870 (if (string-match "\\S-" elements)
2871 (progn
2872 (when numbers (setq elements (number-to-string
2873 (string-to-number elements))))
2874 (concat "(" elements ")"))
2875 (if (or (not keep-empty) numbers) "(0)" "nan")))
2876 ;; range reference
2877 (unless keep-empty
2878 (setq elements
2879 (delq nil
2880 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2881 elements))))
2882 (setq elements (or elements '("")))
2883 (if lispp
2884 (mapconcat
2885 (lambda (x)
2886 (if (eq lispp 'literal)
2888 (prin1-to-string (if numbers (string-to-number x) x))))
2889 elements " ")
2890 (concat "[" (mapconcat
2891 (lambda (x)
2892 (if (string-match "\\S-" x)
2893 (if numbers
2894 (number-to-string (string-to-number x))
2896 (if (or (not keep-empty) numbers) "0" "nan")))
2897 elements
2898 ",") "]"))))
2900 ;;;###autoload
2901 (defun org-table-recalculate (&optional all noalign)
2902 "Recalculate the current table line by applying all stored formulas.
2903 With prefix arg ALL, do this for all lines in the table.
2904 With the prefix argument ALL is `(16)' \
2905 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2906 it is the symbol `iterate', recompute the table until it no longer changes.
2907 If NOALIGN is not nil, do not re-align the table after the computations
2908 are done. This is typically used internally to save time, if it is
2909 known that the table will be realigned a little later anyway."
2910 (interactive "P")
2911 (or (memq this-command org-recalc-commands)
2912 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2913 (unless (org-at-table-p) (error "Not at a table"))
2914 (if (or (eq all 'iterate) (equal all '(16)))
2915 (org-table-iterate)
2916 (org-table-get-specials)
2917 (let* ((eqlist (sort (org-table-get-stored-formulas)
2918 (lambda (a b) (string< (car a) (car b)))))
2919 (eqlist1 (copy-sequence eqlist))
2920 (inhibit-redisplay (not debug-on-error))
2921 (line-re org-table-dataline-regexp)
2922 (thisline (org-current-line))
2923 (thiscol (org-table-current-column))
2924 seen-fields lhs1
2925 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
2926 ;; Insert constants in all formulas
2927 (setq eqlist
2928 (mapcar (lambda (x)
2929 (when (string-match "\\`$[<>]" (car x))
2930 (setq lhs1 (car x))
2931 (setq x (cons (substring
2932 (org-table-formula-handle-first/last-rc
2933 (car x)) 1)
2934 (cdr x)))
2935 (if (assoc (car x) eqlist1)
2936 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2937 lhs1 (car x))))
2938 (cons
2939 (org-table-formula-handle-first/last-rc (car x))
2940 (org-table-formula-substitute-names
2941 (org-table-formula-handle-first/last-rc (cdr x)))))
2942 eqlist))
2943 ;; Split the equation list
2944 (while (setq eq (pop eqlist))
2945 (if (<= (string-to-char (car eq)) ?9)
2946 (push eq eqlnum)
2947 (push eq eqlname)))
2948 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2949 ;; Expand ranges in lhs of formulas
2950 (setq eqlname (org-table-expand-lhs-ranges eqlname))
2952 ;; Get the correct line range to process
2953 (if all
2954 (progn
2955 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2956 (goto-char (setq beg (org-table-begin)))
2957 (if (re-search-forward org-table-calculate-mark-regexp end t)
2958 ;; This is a table with marked lines, compute selected lines
2959 (setq line-re org-table-recalculate-regexp)
2960 ;; Move forward to the first non-header line
2961 (if (and (re-search-forward org-table-dataline-regexp end t)
2962 (re-search-forward org-table-hline-regexp end t)
2963 (re-search-forward org-table-dataline-regexp end t))
2964 (setq beg (match-beginning 0))
2965 nil))) ;; just leave beg where it is
2966 (setq beg (point-at-bol)
2967 end (move-marker (make-marker) (1+ (point-at-eol)))))
2968 (goto-char beg)
2969 (and all (message "Re-applying formulas to full table..."))
2971 ;; First find the named fields, and mark them untouchable.
2972 ;; Also check if several field/range formulas try to set the same field.
2973 (remove-text-properties beg end '(org-untouchable t))
2974 (while (setq eq (pop eqlname))
2975 (setq name (car eq)
2976 a (assoc name org-table-named-field-locations))
2977 (setq name1 name)
2978 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
2979 (nth 2 a))))
2980 (when (member name1 seen-fields)
2981 (error "Several field/range formulas try to set %s" name1))
2982 (push name1 seen-fields)
2984 (and (not a)
2985 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2986 (setq a (list name
2987 (condition-case nil
2988 (aref org-table-dlines
2989 (string-to-number (match-string 1 name)))
2990 (error (error "Invalid row number in %s"
2991 name)))
2992 (string-to-number (match-string 2 name)))))
2993 (when (and a (or all (equal (nth 1 a) thisline)))
2994 (message "Re-applying formula to field: %s" name)
2995 (org-goto-line (nth 1 a))
2996 (org-table-goto-column (nth 2 a))
2997 (push (append a (list (cdr eq))) eqlname1)
2998 (org-table-put-field-property :org-untouchable t)))
2999 (setq eqlname1 (nreverse eqlname1))
3001 ;; Now evaluate the column formulas, but skip fields covered by
3002 ;; field formulas
3003 (goto-char beg)
3004 (while (re-search-forward line-re end t)
3005 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3006 ;; Unprotected line, recalculate
3007 (and all (message "Re-applying formulas to full table...(line %d)"
3008 (setq cnt (1+ cnt))))
3009 (setq org-last-recalc-line (org-current-line))
3010 (setq eql eqlnum)
3011 (while (setq entry (pop eql))
3012 (org-goto-line org-last-recalc-line)
3013 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3014 (unless (get-text-property (point) :org-untouchable)
3015 (org-table-eval-formula nil (cdr entry)
3016 'noalign 'nocst 'nostore 'noanalysis)))))
3018 ;; Now evaluate the field formulas
3019 (while (setq eq (pop eqlname1))
3020 (message "Re-applying formula to field: %s" (car eq))
3021 (org-goto-line (nth 1 eq))
3022 (org-table-goto-column (nth 2 eq))
3023 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
3024 'nostore 'noanalysis))
3026 (org-goto-line thisline)
3027 (org-table-goto-column thiscol)
3028 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3029 (or noalign (and org-table-may-need-update (org-table-align))
3030 (and all (message "Re-applying formulas to %d lines...done" cnt)))
3032 ;; back to initial position
3033 (message "Re-applying formulas...done")
3034 (org-goto-line thisline)
3035 (org-table-goto-column thiscol)
3036 (or noalign (and org-table-may-need-update (org-table-align))
3037 (and all (message "Re-applying formulas...done"))))))
3039 ;;;###autoload
3040 (defun org-table-iterate (&optional arg)
3041 "Recalculate the table until it does not change anymore.
3042 The maximum number of iterations is 10, but you can choose a different value
3043 with the prefix ARG."
3044 (interactive "P")
3045 (let ((imax (if arg (prefix-numeric-value arg) 10))
3046 (i 0)
3047 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3048 thistbl)
3049 (catch 'exit
3050 (while (< i imax)
3051 (setq i (1+ i))
3052 (org-table-recalculate 'all)
3053 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3054 (if (not (string= lasttbl thistbl))
3055 (setq lasttbl thistbl)
3056 (if (> i 1)
3057 (message "Convergence after %d iterations" i)
3058 (message "Table was already stable"))
3059 (throw 'exit t)))
3060 (error "No convergence after %d iterations" i))))
3062 ;;;###autoload
3063 (defun org-table-recalculate-buffer-tables ()
3064 "Recalculate all tables in the current buffer."
3065 (interactive)
3066 (save-excursion
3067 (save-restriction
3068 (widen)
3069 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3071 ;;;###autoload
3072 (defun org-table-iterate-buffer-tables ()
3073 "Iterate all tables in the buffer, to converge inter-table dependencies."
3074 (interactive)
3075 (let* ((imax 10)
3076 (i imax)
3077 (checksum (md5 (buffer-string)))
3079 (save-excursion
3080 (save-restriction
3081 (widen)
3082 (catch 'exit
3083 (while (> i 0)
3084 (setq i (1- i))
3085 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3086 (if (equal checksum (setq c1 (md5 (buffer-string))))
3087 (progn
3088 (message "Convergence after %d iterations" (- imax i))
3089 (throw 'exit t))
3090 (setq checksum c1)))
3091 (error "No convergence after %d iterations" imax))))))
3093 (defun org-table-expand-lhs-ranges (equations)
3094 "Expand list of formulas.
3095 If some of the RHS in the formulas are ranges or a row reference, expand
3096 them to individual field equations for each field."
3097 (let (e res lhs rhs range r1 r2 c1 c2)
3098 (while (setq e (pop equations))
3099 (setq lhs (car e) rhs (cdr e))
3100 (cond
3101 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3102 ;; This just refers to one fixed field
3103 (push e res))
3104 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3105 ;; This just refers to one fixed named field
3106 (push e res))
3107 ((string-match "^@[0-9]+$" lhs)
3108 (loop for ic from 1 to org-table-current-ncol do
3109 (push (cons (format "%s$%d" lhs ic) rhs) res)
3110 (put-text-property 0 (length (caar res))
3111 :orig-eqn e (caar res))))
3113 (setq range (org-table-get-range lhs org-table-current-begin-pos
3114 1 nil 'corners))
3115 (setq r1 (nth 0 range) c1 (nth 1 range)
3116 r2 (nth 2 range) c2 (nth 3 range))
3117 (setq r1 (org-table-line-to-dline r1))
3118 (setq r2 (org-table-line-to-dline r2 'above))
3119 (loop for ir from r1 to r2 do
3120 (loop for ic from c1 to c2 do
3121 (push (cons (format "@%d$%d" ir ic) rhs) res)
3122 (put-text-property 0 (length (caar res))
3123 :orig-eqn e (caar res)))))))
3124 (nreverse res)))
3126 (defun org-table-formula-handle-first/last-rc (s)
3127 "Replace @<, @>, $<, $> with first/last row/column of the table.
3128 So @< and $< will always be replaced with @1 and $1, respectively.
3129 The advantage of these special markers are that structure editing of
3130 the table will not change them, while @1 and $1 will be modified
3131 when a line/row is swapped out of that privileged position. So for
3132 formulas that use a range of rows or columns, it may often be better
3133 to anchor the formula with \"I\" row markers, or to offset from the
3134 borders of the table using the @< @> $< $> makers."
3135 (let (n nmax len char (start 0))
3136 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3137 s start)
3138 (if (match-end 3)
3139 (setq start (match-end 3))
3140 (setq nmax (if (equal (match-string 1 s) "@")
3141 (1- (length org-table-dlines))
3142 org-table-current-ncol)
3143 len (- (match-end 2) (match-beginning 2))
3144 char (string-to-char (match-string 2 s))
3145 n (if (= char ?<)
3147 (- nmax len -1)))
3148 (if (or (< n 1) (> n nmax))
3149 (error "Reference \"%s\" in expression \"%s\" points outside table"
3150 (match-string 0 s) s))
3151 (setq start (match-beginning 0))
3152 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3155 (defun org-table-formula-substitute-names (f)
3156 "Replace $const with values in string F."
3157 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3158 ;; First, check for column names
3159 (while (setq start (string-match org-table-column-name-regexp f start))
3160 (setq start (1+ start))
3161 (setq a (assoc (match-string 1 f) org-table-column-names))
3162 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3163 ;; Parameters and constants
3164 (setq start 0)
3165 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3166 (if (match-end 2)
3167 (setq start (match-end 2))
3168 (setq start (1+ start))
3169 (if (setq a (save-match-data
3170 (org-table-get-constant (match-string 1 f))))
3171 (setq f (replace-match
3172 (concat (if pp "(") a (if pp ")")) t t f)))))
3173 (if org-table-formula-debug
3174 (put-text-property 0 (length f) :orig-formula f1 f))
3177 (defun org-table-get-constant (const)
3178 "Find the value for a parameter or constant in a formula.
3179 Parameters get priority."
3180 (or (cdr (assoc const org-table-local-parameters))
3181 (cdr (assoc const org-table-formula-constants-local))
3182 (cdr (assoc const org-table-formula-constants))
3183 (and (fboundp 'constants-get) (constants-get const))
3184 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3185 (org-entry-get nil (substring const 5) 'inherit))
3186 "#UNDEFINED_NAME"))
3188 (defvar org-table-fedit-map
3189 (let ((map (make-sparse-keymap)))
3190 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3191 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3192 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3193 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3194 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3195 (org-defkey map "\C-c?" 'org-table-show-reference)
3196 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3197 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3198 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3199 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3200 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3201 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3202 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3203 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3204 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3205 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3206 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3207 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3208 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3209 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3210 map))
3212 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3213 '("Edit-Formulas"
3214 ["Finish and Install" org-table-fedit-finish t]
3215 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3216 ["Abort" org-table-fedit-abort t]
3217 "--"
3218 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3219 ["Complete Lisp Symbol" lisp-complete-symbol t]
3220 "--"
3221 "Shift Reference at Point"
3222 ["Up" org-table-fedit-ref-up t]
3223 ["Down" org-table-fedit-ref-down t]
3224 ["Left" org-table-fedit-ref-left t]
3225 ["Right" org-table-fedit-ref-right t]
3227 "Change Test Row for Column Formulas"
3228 ["Up" org-table-fedit-line-up t]
3229 ["Down" org-table-fedit-line-down t]
3230 "--"
3231 ["Scroll Table Window" org-table-fedit-scroll t]
3232 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3233 ["Show Table Grid" org-table-fedit-toggle-coordinates
3234 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3235 org-table-overlay-coordinates)]
3236 "--"
3237 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3238 :style toggle :selected org-table-buffer-is-an]))
3240 (defvar org-pos)
3242 ;;;###autoload
3243 (defun org-table-edit-formulas ()
3244 "Edit the formulas of the current table in a separate buffer."
3245 (interactive)
3246 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3247 (beginning-of-line 0))
3248 (unless (org-at-table-p) (error "Not at a table"))
3249 (org-table-get-specials)
3250 (let ((key (org-table-current-field-formula 'key 'noerror))
3251 (eql (sort (org-table-get-stored-formulas 'noerror)
3252 'org-table-formula-less-p))
3253 (pos (point-marker))
3254 (startline 1)
3255 (wc (current-window-configuration))
3256 (sel-win (selected-window))
3257 (titles '((column . "# Column Formulas\n")
3258 (field . "# Field and Range Formulas\n")
3259 (named . "# Named Field Formulas\n")))
3260 entry s type title)
3261 (org-switch-to-buffer-other-window "*Edit Formulas*")
3262 (erase-buffer)
3263 ;; Keep global-font-lock-mode from turning on font-lock-mode
3264 (let ((font-lock-global-modes '(not fundamental-mode)))
3265 (fundamental-mode))
3266 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3267 (org-set-local 'org-pos pos)
3268 (org-set-local 'org-window-configuration wc)
3269 (org-set-local 'org-selected-window sel-win)
3270 (use-local-map org-table-fedit-map)
3271 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3272 (easy-menu-add org-table-fedit-menu)
3273 (setq startline (org-current-line))
3274 (while (setq entry (pop eql))
3275 (setq type (cond
3276 ((string-match "\\`$[<>]" (car entry)) 'column)
3277 ((equal (string-to-char (car entry)) ?@) 'field)
3278 ((string-match "^[0-9]" (car entry)) 'column)
3279 (t 'named)))
3280 (when (setq title (assq type titles))
3281 (or (bobp) (insert "\n"))
3282 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3283 (setq titles (remove title titles)))
3284 (if (equal key (car entry)) (setq startline (org-current-line)))
3285 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3286 (car entry) " = " (cdr entry) "\n"))
3287 (remove-text-properties 0 (length s) '(face nil) s)
3288 (insert s))
3289 (if (eq org-table-use-standard-references t)
3290 (org-table-fedit-toggle-ref-type))
3291 (org-goto-line startline)
3292 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3294 (defun org-table-fedit-post-command ()
3295 (when (not (memq this-command '(lisp-complete-symbol)))
3296 (let ((win (selected-window)))
3297 (save-excursion
3298 (condition-case nil
3299 (org-table-show-reference)
3300 (error nil))
3301 (select-window win)))))
3303 (defun org-table-formula-to-user (s)
3304 "Convert a formula from internal to user representation."
3305 (if (eq org-table-use-standard-references t)
3306 (org-table-convert-refs-to-an s)
3309 (defun org-table-formula-from-user (s)
3310 "Convert a formula from user to internal representation."
3311 (if org-table-use-standard-references
3312 (org-table-convert-refs-to-rc s)
3315 (defun org-table-convert-refs-to-rc (s)
3316 "Convert spreadsheet references from A7 to @7$28.
3317 Works for single references, but also for entire formulas and even the
3318 full TBLFM line."
3319 (let ((start 0))
3320 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3321 (cond
3322 ((match-end 3)
3323 ;; format match, just advance
3324 (setq start (match-end 0)))
3325 ((and (> (match-beginning 0) 0)
3326 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3327 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3328 ;; 3.e5 or something like this.
3329 (setq start (match-end 0)))
3330 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3331 ;; (member (match-string 1 s)
3332 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3334 ;; function name, just advance
3335 (setq start (match-end 0)))
3337 (setq start (match-beginning 0)
3338 s (replace-match
3339 (if (equal (match-string 2 s) "&")
3340 (format "$%d" (org-letters-to-number (match-string 1 s)))
3341 (format "@%d$%d"
3342 (string-to-number (match-string 2 s))
3343 (org-letters-to-number (match-string 1 s))))
3344 t t s)))))
3347 (defun org-table-convert-refs-to-an (s)
3348 "Convert spreadsheet references from to @7$28 to AB7.
3349 Works for single references, but also for entire formulas and even the
3350 full TBLFM line."
3351 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3352 (setq s (replace-match
3353 (format "%s%d"
3354 (org-number-to-letters
3355 (string-to-number (match-string 2 s)))
3356 (string-to-number (match-string 1 s)))
3357 t t s)))
3358 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3359 (setq s (replace-match (concat "\\1"
3360 (org-number-to-letters
3361 (string-to-number (match-string 2 s))) "&")
3362 t nil s)))
3365 (defun org-letters-to-number (s)
3366 "Convert a base 26 number represented by letters into an integer.
3367 For example: AB -> 28."
3368 (let ((n 0))
3369 (setq s (upcase s))
3370 (while (> (length s) 0)
3371 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3372 s (substring s 1)))
3375 (defun org-number-to-letters (n)
3376 "Convert an integer into a base 26 number represented by letters.
3377 For example: 28 -> AB."
3378 (let ((s ""))
3379 (while (> n 0)
3380 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3381 n (/ (1- n) 26)))
3384 (defun org-table-time-string-to-seconds (s)
3385 "Convert a time string into numerical duration in seconds.
3386 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3387 If S is a string representing a number, keep this number."
3388 (if (equal s "")
3390 (let (hour minus min sec res)
3391 (cond
3392 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3393 (setq minus (< 0 (length (match-string 1 s)))
3394 hour (string-to-number (match-string 2 s))
3395 min (string-to-number (match-string 3 s))
3396 sec (string-to-number (match-string 4 s)))
3397 (if minus
3398 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3399 (setq res (+ (* hour 3600) (* min 60) sec))))
3400 ((and (not (string-match org-ts-regexp-both s))
3401 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3402 (setq minus (< 0 (length (match-string 1 s)))
3403 hour (string-to-number (match-string 2 s))
3404 min (string-to-number (match-string 3 s)))
3405 (if minus
3406 (setq res (- (+ (* hour 3600) (* min 60))))
3407 (setq res (+ (* hour 3600) (* min 60)))))
3408 (t (setq res (string-to-number s))))
3409 (number-to-string res))))
3411 (defun org-table-time-seconds-to-string (secs &optional output-format)
3412 "Convert a number of seconds to a time string.
3413 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3414 minutes or seconds."
3415 (let* ((secs0 (abs secs))
3416 (res
3417 (cond ((eq output-format 'days)
3418 (format "%.3f" (/ (float secs0) 86400)))
3419 ((eq output-format 'hours)
3420 (format "%.2f" (/ (float secs0) 3600)))
3421 ((eq output-format 'minutes)
3422 (format "%.1f" (/ (float secs0) 60)))
3423 ((eq output-format 'seconds)
3424 (format "%d" secs0))
3425 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3426 (if (< secs 0) (concat "-" res) res)))
3428 (defun org-table-fedit-convert-buffer (function)
3429 "Convert all references in this buffer, using FUNCTION."
3430 (let ((line (org-current-line)))
3431 (goto-char (point-min))
3432 (while (not (eobp))
3433 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3434 (delete-region (point) (point-at-eol))
3435 (or (eobp) (forward-char 1)))
3436 (org-goto-line line)))
3438 (defun org-table-fedit-toggle-ref-type ()
3439 "Convert all references in the buffer from B3 to @3$2 and back."
3440 (interactive)
3441 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3442 (org-table-fedit-convert-buffer
3443 (if org-table-buffer-is-an
3444 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3445 (message "Reference type switched to %s"
3446 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3448 (defun org-table-fedit-ref-up ()
3449 "Shift the reference at point one row/hline up."
3450 (interactive)
3451 (org-table-fedit-shift-reference 'up))
3452 (defun org-table-fedit-ref-down ()
3453 "Shift the reference at point one row/hline down."
3454 (interactive)
3455 (org-table-fedit-shift-reference 'down))
3456 (defun org-table-fedit-ref-left ()
3457 "Shift the reference at point one field to the left."
3458 (interactive)
3459 (org-table-fedit-shift-reference 'left))
3460 (defun org-table-fedit-ref-right ()
3461 "Shift the reference at point one field to the right."
3462 (interactive)
3463 (org-table-fedit-shift-reference 'right))
3465 (defun org-table-fedit-shift-reference (dir)
3466 (cond
3467 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3468 (if (memq dir '(left right))
3469 (org-rematch-and-replace 1 (eq dir 'left))
3470 (error "Cannot shift reference in this direction")))
3471 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3472 ;; A B3-like reference
3473 (if (memq dir '(up down))
3474 (org-rematch-and-replace 2 (eq dir 'up))
3475 (org-rematch-and-replace 1 (eq dir 'left))))
3476 ((org-at-regexp-p
3477 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3478 ;; An internal reference
3479 (if (memq dir '(up down))
3480 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3481 (org-rematch-and-replace 5 (eq dir 'left))))))
3483 (defun org-rematch-and-replace (n &optional decr hline)
3484 "Re-match the group N, and replace it with the shifted reference."
3485 (or (match-end n) (error "Cannot shift reference in this direction"))
3486 (goto-char (match-beginning n))
3487 (and (looking-at (regexp-quote (match-string n)))
3488 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3489 t t)))
3491 (defun org-table-shift-refpart (ref &optional decr hline)
3492 "Shift a reference part REF.
3493 If DECR is set, decrease the references row/column, else increase.
3494 If HLINE is set, this may be a hline reference, it certainly is not
3495 a translation reference."
3496 (save-match-data
3497 (let* ((sign (string-match "^[-+]" ref)) n)
3499 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3500 (cond
3501 ((and hline (string-match "^I+" ref))
3502 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3503 (setq n (+ n (if decr -1 1)))
3504 (if (= n 0) (setq n (+ n (if decr -1 1))))
3505 (if sign
3506 (setq sign (if (< n 0) "-" "+") n (abs n))
3507 (setq n (max 1 n)))
3508 (concat sign (make-string n ?I)))
3510 ((string-match "^[0-9]+" ref)
3511 (setq n (string-to-number (concat sign ref)))
3512 (setq n (+ n (if decr -1 1)))
3513 (if sign
3514 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3515 (number-to-string (max 1 n))))
3517 ((string-match "^[a-zA-Z]+" ref)
3518 (org-number-to-letters
3519 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3521 (t (error "Cannot shift reference"))))))
3523 (defun org-table-fedit-toggle-coordinates ()
3524 "Toggle the display of coordinates in the referenced table."
3525 (interactive)
3526 (let ((pos (marker-position org-pos)))
3527 (with-current-buffer (marker-buffer org-pos)
3528 (save-excursion
3529 (goto-char pos)
3530 (org-table-toggle-coordinate-overlays)))))
3532 (defun org-table-fedit-finish (&optional arg)
3533 "Parse the buffer for formula definitions and install them.
3534 With prefix ARG, apply the new formulas to the table."
3535 (interactive "P")
3536 (org-table-remove-rectangle-highlight)
3537 (if org-table-use-standard-references
3538 (progn
3539 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3540 (setq org-table-buffer-is-an nil)))
3541 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3542 (goto-char (point-min))
3543 (while (re-search-forward
3544 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3545 nil t)
3546 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3547 form (match-string 3))
3548 (setq form (org-trim form))
3549 (when (not (equal form ""))
3550 (while (string-match "[ \t]*\n[ \t]*" form)
3551 (setq form (replace-match " " t t form)))
3552 (when (assoc var eql)
3553 (error "Double formulas for %s" var))
3554 (push (cons var form) eql)))
3555 (setq org-pos nil)
3556 (set-window-configuration org-window-configuration)
3557 (select-window sel-win)
3558 (goto-char pos)
3559 (unless (org-at-table-p)
3560 (error "Lost table position - cannot install formulas"))
3561 (org-table-store-formulas eql)
3562 (move-marker pos nil)
3563 (kill-buffer "*Edit Formulas*")
3564 (if arg
3565 (org-table-recalculate 'all)
3566 (message "New formulas installed - press C-u C-c C-c to apply."))))
3568 (defun org-table-fedit-abort ()
3569 "Abort editing formulas, without installing the changes."
3570 (interactive)
3571 (org-table-remove-rectangle-highlight)
3572 (let ((pos org-pos) (sel-win org-selected-window))
3573 (set-window-configuration org-window-configuration)
3574 (select-window sel-win)
3575 (goto-char pos)
3576 (move-marker pos nil)
3577 (message "Formula editing aborted without installing changes")))
3579 (defun org-table-fedit-lisp-indent ()
3580 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3581 (interactive)
3582 (let ((pos (point)) beg end ind)
3583 (beginning-of-line 1)
3584 (cond
3585 ((looking-at "[ \t]")
3586 (goto-char pos)
3587 (call-interactively 'lisp-indent-line))
3588 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3589 ((not (fboundp 'pp-buffer))
3590 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3591 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3592 (goto-char (- (match-end 0) 2))
3593 (setq beg (point))
3594 (setq ind (make-string (current-column) ?\ ))
3595 (condition-case nil (forward-sexp 1)
3596 (error
3597 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3598 (setq end (point))
3599 (save-restriction
3600 (narrow-to-region beg end)
3601 (if (eq last-command this-command)
3602 (progn
3603 (goto-char (point-min))
3604 (setq this-command nil)
3605 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3606 (replace-match " ")))
3607 (pp-buffer)
3608 (untabify (point-min) (point-max))
3609 (goto-char (1+ (point-min)))
3610 (while (re-search-forward "^." nil t)
3611 (beginning-of-line 1)
3612 (insert ind))
3613 (goto-char (point-max))
3614 (org-delete-backward-char 1)))
3615 (goto-char beg))
3616 (t nil))))
3618 (defvar org-show-positions nil)
3620 (defun org-table-show-reference (&optional local)
3621 "Show the location/value of the $ expression at point."
3622 (interactive)
3623 (org-table-remove-rectangle-highlight)
3624 (catch 'exit
3625 (let ((pos (if local (point) org-pos))
3626 (face2 'highlight)
3627 (org-inhibit-highlight-removal t)
3628 (win (selected-window))
3629 (org-show-positions nil)
3630 var name e what match dest)
3631 (if local (org-table-get-specials))
3632 (setq what (cond
3633 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3634 (setq match (concat (substring (match-string 0) 0 -1)
3635 "$1.."
3636 (substring (match-string 0) 0 -1)
3637 "$100"))
3638 'range)
3639 ((or (org-at-regexp-p org-table-range-regexp2)
3640 (org-at-regexp-p org-table-translate-regexp)
3641 (org-at-regexp-p org-table-range-regexp))
3642 (setq match
3643 (save-match-data
3644 (org-table-convert-refs-to-rc (match-string 0))))
3645 'range)
3646 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3647 ((org-at-regexp-p "\\$[0-9]+") 'column)
3648 ((not local) nil)
3649 (t (error "No reference at point")))
3650 match (and what (or match (match-string 0))))
3651 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3652 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3653 'secondary-selection))
3654 (org-add-hook 'before-change-functions
3655 'org-table-remove-rectangle-highlight)
3656 (if (eq what 'name) (setq var (substring match 1)))
3657 (when (eq what 'range)
3658 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3659 (setq match (org-table-formula-substitute-names match)))
3660 (unless local
3661 (save-excursion
3662 (end-of-line 1)
3663 (re-search-backward "^\\S-" nil t)
3664 (beginning-of-line 1)
3665 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3666 (setq dest
3667 (save-match-data
3668 (org-table-convert-refs-to-rc (match-string 1))))
3669 (org-table-add-rectangle-overlay
3670 (match-beginning 1) (match-end 1) face2))))
3671 (if (and (markerp pos) (marker-buffer pos))
3672 (if (get-buffer-window (marker-buffer pos))
3673 (select-window (get-buffer-window (marker-buffer pos)))
3674 (org-switch-to-buffer-other-window (get-buffer-window
3675 (marker-buffer pos)))))
3676 (goto-char pos)
3677 (org-table-force-dataline)
3678 (when dest
3679 (setq name (substring dest 1))
3680 (cond
3681 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3682 (setq e (assoc name org-table-named-field-locations))
3683 (org-goto-line (nth 1 e))
3684 (org-table-goto-column (nth 2 e)))
3685 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3686 (let ((l (string-to-number (match-string 1 dest)))
3687 (c (string-to-number (match-string 2 dest))))
3688 (org-goto-line (aref org-table-dlines l))
3689 (org-table-goto-column c)))
3690 (t (org-table-goto-column (string-to-number name))))
3691 (move-marker pos (point))
3692 (org-table-highlight-rectangle nil nil face2))
3693 (cond
3694 ((equal dest match))
3695 ((not match))
3696 ((eq what 'range)
3697 (condition-case nil
3698 (save-excursion
3699 (org-table-get-range match nil nil 'highlight))
3700 (error nil)))
3701 ((setq e (assoc var org-table-named-field-locations))
3702 (org-goto-line (nth 1 e))
3703 (org-table-goto-column (nth 2 e))
3704 (org-table-highlight-rectangle (point) (point))
3705 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3706 ((setq e (assoc var org-table-column-names))
3707 (org-table-goto-column (string-to-number (cdr e)))
3708 (org-table-highlight-rectangle (point) (point))
3709 (goto-char (org-table-begin))
3710 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3711 (org-table-end) t)
3712 (progn
3713 (goto-char (match-beginning 1))
3714 (org-table-highlight-rectangle)
3715 (message "Named column (column %s)" (cdr e)))
3716 (error "Column name not found")))
3717 ((eq what 'column)
3718 ;; column number
3719 (org-table-goto-column (string-to-number (substring match 1)))
3720 (org-table-highlight-rectangle (point) (point))
3721 (message "Column %s" (substring match 1)))
3722 ((setq e (assoc var org-table-local-parameters))
3723 (goto-char (org-table-begin))
3724 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3725 (progn
3726 (goto-char (match-beginning 1))
3727 (org-table-highlight-rectangle)
3728 (message "Local parameter."))
3729 (error "Parameter not found")))
3731 (cond
3732 ((not var) (error "No reference at point"))
3733 ((setq e (assoc var org-table-formula-constants-local))
3734 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3735 var (cdr e)))
3736 ((setq e (assoc var org-table-formula-constants))
3737 (message "Constant: $%s=%s in `org-table-formula-constants'."
3738 var (cdr e)))
3739 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3740 (message "Constant: $%s=%s, from `constants.el'%s."
3741 var e (format " (%s units)" constants-unit-system)))
3742 (t (error "Undefined name $%s" var)))))
3743 (goto-char pos)
3744 (when (and org-show-positions
3745 (not (memq this-command '(org-table-fedit-scroll
3746 org-table-fedit-scroll-down))))
3747 (push pos org-show-positions)
3748 (push org-table-current-begin-pos org-show-positions)
3749 (let ((min (apply 'min org-show-positions))
3750 (max (apply 'max org-show-positions)))
3751 (goto-char min) (recenter 0)
3752 (goto-char max)
3753 (or (pos-visible-in-window-p max) (recenter -1))))
3754 (select-window win))))
3756 (defun org-table-force-dataline ()
3757 "Make sure the cursor is in a dataline in a table."
3758 (unless (save-excursion
3759 (beginning-of-line 1)
3760 (looking-at org-table-dataline-regexp))
3761 (let* ((re org-table-dataline-regexp)
3762 (p1 (save-excursion (re-search-forward re nil 'move)))
3763 (p2 (save-excursion (re-search-backward re nil 'move))))
3764 (cond ((and p1 p2)
3765 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3766 p1 p2)))
3767 ((or p1 p2) (goto-char (or p1 p2)))
3768 (t (error "No table dataline around here"))))))
3770 (defun org-table-fedit-line-up ()
3771 "Move cursor one line up in the window showing the table."
3772 (interactive)
3773 (org-table-fedit-move 'previous-line))
3775 (defun org-table-fedit-line-down ()
3776 "Move cursor one line down in the window showing the table."
3777 (interactive)
3778 (org-table-fedit-move 'next-line))
3780 (defun org-table-fedit-move (command)
3781 "Move the cursor in the window showing the table.
3782 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3783 (let ((org-table-allow-automatic-line-recalculation nil)
3784 (pos org-pos) (win (selected-window)) p)
3785 (select-window (get-buffer-window (marker-buffer org-pos)))
3786 (setq p (point))
3787 (call-interactively command)
3788 (while (and (org-at-table-p)
3789 (org-at-table-hline-p))
3790 (call-interactively command))
3791 (or (org-at-table-p) (goto-char p))
3792 (move-marker pos (point))
3793 (select-window win)))
3795 (defun org-table-fedit-scroll (N)
3796 (interactive "p")
3797 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3798 (scroll-other-window N)))
3800 (defun org-table-fedit-scroll-down (N)
3801 (interactive "p")
3802 (org-table-fedit-scroll (- N)))
3804 (defvar org-table-rectangle-overlays nil)
3806 (defun org-table-add-rectangle-overlay (beg end &optional face)
3807 "Add a new overlay."
3808 (let ((ov (make-overlay beg end)))
3809 (overlay-put ov 'face (or face 'secondary-selection))
3810 (push ov org-table-rectangle-overlays)))
3812 (defun org-table-highlight-rectangle (&optional beg end face)
3813 "Highlight rectangular region in a table."
3814 (setq beg (or beg (point)) end (or end (point)))
3815 (let ((b (min beg end))
3816 (e (max beg end))
3817 l1 c1 l2 c2 tmp)
3818 (and (boundp 'org-show-positions)
3819 (setq org-show-positions (cons b (cons e org-show-positions))))
3820 (goto-char (min beg end))
3821 (setq l1 (org-current-line)
3822 c1 (org-table-current-column))
3823 (goto-char (max beg end))
3824 (setq l2 (org-current-line)
3825 c2 (org-table-current-column))
3826 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3827 (org-goto-line l1)
3828 (beginning-of-line 1)
3829 (loop for line from l1 to l2 do
3830 (when (looking-at org-table-dataline-regexp)
3831 (org-table-goto-column c1)
3832 (skip-chars-backward "^|\n") (setq beg (point))
3833 (org-table-goto-column c2)
3834 (skip-chars-forward "^|\n") (setq end (point))
3835 (org-table-add-rectangle-overlay beg end face))
3836 (beginning-of-line 2))
3837 (goto-char b))
3838 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3840 (defun org-table-remove-rectangle-highlight (&rest ignore)
3841 "Remove the rectangle overlays."
3842 (unless org-inhibit-highlight-removal
3843 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3844 (mapc 'delete-overlay org-table-rectangle-overlays)
3845 (setq org-table-rectangle-overlays nil)))
3847 (defvar org-table-coordinate-overlays nil
3848 "Collects the coordinate grid overlays, so that they can be removed.")
3849 (make-variable-buffer-local 'org-table-coordinate-overlays)
3851 (defun org-table-overlay-coordinates ()
3852 "Add overlays to the table at point, to show row/column coordinates."
3853 (interactive)
3854 (mapc 'delete-overlay org-table-coordinate-overlays)
3855 (setq org-table-coordinate-overlays nil)
3856 (save-excursion
3857 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3858 (goto-char (org-table-begin))
3859 (while (org-at-table-p)
3860 (setq eol (point-at-eol))
3861 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3862 (push ov org-table-coordinate-overlays)
3863 (setq hline (looking-at org-table-hline-regexp))
3864 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3865 (format "%4d" (setq id (1+ id)))))
3866 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3867 (when hline
3868 (setq ic 0)
3869 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3870 (setq beg (1+ (match-beginning 0))
3871 ic (1+ ic)
3872 s1 (concat "$" (int-to-string ic))
3873 s2 (org-number-to-letters ic)
3874 str (if (eq org-table-use-standard-references t) s2 s1))
3875 (setq ov (make-overlay beg (+ beg (length str))))
3876 (push ov org-table-coordinate-overlays)
3877 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3878 (beginning-of-line 2)))))
3880 ;;;###autoload
3881 (defun org-table-toggle-coordinate-overlays ()
3882 "Toggle the display of Row/Column numbers in tables."
3883 (interactive)
3884 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3885 (message "Tables Row/Column numbers display turned %s"
3886 (if org-table-overlay-coordinates "on" "off"))
3887 (if (and (org-at-table-p) org-table-overlay-coordinates)
3888 (org-table-align))
3889 (unless org-table-overlay-coordinates
3890 (mapc 'delete-overlay org-table-coordinate-overlays)
3891 (setq org-table-coordinate-overlays nil)))
3893 ;;;###autoload
3894 (defun org-table-toggle-formula-debugger ()
3895 "Toggle the formula debugger in tables."
3896 (interactive)
3897 (setq org-table-formula-debug (not org-table-formula-debug))
3898 (message "Formula debugging has been turned %s"
3899 (if org-table-formula-debug "on" "off")))
3901 ;;; The orgtbl minor mode
3903 ;; Define a minor mode which can be used in other modes in order to
3904 ;; integrate the org-mode table editor.
3906 ;; This is really a hack, because the org-mode table editor uses several
3907 ;; keys which normally belong to the major mode, for example the TAB and
3908 ;; RET keys. Here is how it works: The minor mode defines all the keys
3909 ;; necessary to operate the table editor, but wraps the commands into a
3910 ;; function which tests if the cursor is currently inside a table. If that
3911 ;; is the case, the table editor command is executed. However, when any of
3912 ;; those keys is used outside a table, the function uses `key-binding' to
3913 ;; look up if the key has an associated command in another currently active
3914 ;; keymap (minor modes, major mode, global), and executes that command.
3915 ;; There might be problems if any of the keys used by the table editor is
3916 ;; otherwise used as a prefix key.
3918 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3919 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3920 ;; addresses this by checking explicitly for both bindings.
3922 ;; The optimized version (see variable `orgtbl-optimized') takes over
3923 ;; all keys which are bound to `self-insert-command' in the *global map*.
3924 ;; Some modes bind other commands to simple characters, for example
3925 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3926 ;; active, this binding is ignored inside tables and replaced with a
3927 ;; modified self-insert.
3930 (defvar orgtbl-mode-map (make-keymap)
3931 "Keymap for `orgtbl-mode'.")
3933 (defvar org-old-auto-fill-inhibit-regexp nil
3934 "Local variable used by `orgtbl-mode'.")
3936 (defconst orgtbl-line-start-regexp
3937 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
3938 "Matches a line belonging to an orgtbl.")
3940 (defconst orgtbl-extra-font-lock-keywords
3941 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3942 0 (quote 'org-table) 'prepend))
3943 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3945 ;; Install it as a minor mode.
3946 (put 'orgtbl-mode :included t)
3947 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3949 ;;;###autoload
3950 (define-minor-mode orgtbl-mode
3951 "The `org-mode' table editor as a minor mode for use in other modes."
3952 :lighter " OrgTbl" :keymap orgtbl-mode-map
3953 (org-load-modules-maybe)
3954 (cond
3955 ((derived-mode-p 'org-mode)
3956 ;; Exit without error, in case some hook functions calls this
3957 ;; by accident in org-mode.
3958 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3959 (orgtbl-mode
3960 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3961 ;; Make sure we are first in minor-mode-map-alist
3962 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3963 ;; FIXME: maybe it should use emulation-mode-map-alists?
3964 (and c (setq minor-mode-map-alist
3965 (cons c (delq c minor-mode-map-alist)))))
3966 (org-set-local (quote org-table-may-need-update) t)
3967 (org-add-hook 'before-change-functions 'org-before-change-function
3968 nil 'local)
3969 (org-set-local 'org-old-auto-fill-inhibit-regexp
3970 auto-fill-inhibit-regexp)
3971 (org-set-local 'auto-fill-inhibit-regexp
3972 (if auto-fill-inhibit-regexp
3973 (concat orgtbl-line-start-regexp "\\|"
3974 auto-fill-inhibit-regexp)
3975 orgtbl-line-start-regexp))
3976 (add-to-invisibility-spec '(org-cwidth))
3977 (when (fboundp 'font-lock-add-keywords)
3978 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3979 (org-restart-font-lock))
3980 (easy-menu-add orgtbl-mode-menu))
3982 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3983 (org-table-cleanup-narrow-column-properties)
3984 (org-remove-from-invisibility-spec '(org-cwidth))
3985 (remove-hook 'before-change-functions 'org-before-change-function t)
3986 (when (fboundp 'font-lock-remove-keywords)
3987 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3988 (org-restart-font-lock))
3989 (easy-menu-remove orgtbl-mode-menu)
3990 (force-mode-line-update 'all))))
3992 (defun org-table-cleanup-narrow-column-properties ()
3993 "Remove all properties related to narrow-column invisibility."
3994 (let ((s (point-min)))
3995 (while (setq s (text-property-any s (point-max)
3996 'display org-narrow-column-arrow))
3997 (remove-text-properties s (1+ s) '(display t)))
3998 (setq s (point-min))
3999 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4000 (remove-text-properties s (1+ s) '(org-cwidth t)))
4001 (setq s (point-min))
4002 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4003 (remove-text-properties s (1+ s) '(invisible t)))))
4005 (defun orgtbl-make-binding (fun n &rest keys)
4006 "Create a function for binding in the table minor mode.
4007 FUN is the command to call inside a table. N is used to create a unique
4008 command name. KEYS are keys that should be checked in for a command
4009 to execute outside of tables."
4010 (eval
4011 (list 'defun
4012 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4013 '(arg)
4014 (concat "In tables, run `" (symbol-name fun) "'.\n"
4015 "Outside of tables, run the binding of `"
4016 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
4017 "'.")
4018 '(interactive "p")
4019 (list 'if
4020 '(org-at-table-p)
4021 (list 'call-interactively (list 'quote fun))
4022 (list 'let '(orgtbl-mode)
4023 (list 'call-interactively
4024 (append '(or)
4025 (mapcar (lambda (k)
4026 (list 'key-binding k))
4027 keys)
4028 '('orgtbl-error))))))))
4030 (defun orgtbl-error ()
4031 "Error when there is no default binding for a table key."
4032 (interactive)
4033 (error "This key has no function outside tables"))
4035 (defun orgtbl-setup ()
4036 "Setup orgtbl keymaps."
4037 (let ((nfunc 0)
4038 (bindings
4039 '(([(meta shift left)] org-table-delete-column)
4040 ([(meta left)] org-table-move-column-left)
4041 ([(meta right)] org-table-move-column-right)
4042 ([(meta shift right)] org-table-insert-column)
4043 ([(meta shift up)] org-table-kill-row)
4044 ([(meta shift down)] org-table-insert-row)
4045 ([(meta up)] org-table-move-row-up)
4046 ([(meta down)] org-table-move-row-down)
4047 ("\C-c\C-w" org-table-cut-region)
4048 ("\C-c\M-w" org-table-copy-region)
4049 ("\C-c\C-y" org-table-paste-rectangle)
4050 ("\C-c\C-w" org-table-wrap-region)
4051 ("\C-c-" org-table-insert-hline)
4052 ("\C-c}" org-table-toggle-coordinate-overlays)
4053 ("\C-c{" org-table-toggle-formula-debugger)
4054 ("\C-m" org-table-next-row)
4055 ([(shift return)] org-table-copy-down)
4056 ("\C-c?" org-table-field-info)
4057 ("\C-c " org-table-blank-field)
4058 ("\C-c+" org-table-sum)
4059 ("\C-c=" org-table-eval-formula)
4060 ("\C-c'" org-table-edit-formulas)
4061 ("\C-c`" org-table-edit-field)
4062 ("\C-c*" org-table-recalculate)
4063 ("\C-c^" org-table-sort-lines)
4064 ("\M-a" org-table-beginning-of-field)
4065 ("\M-e" org-table-end-of-field)
4066 ([(control ?#)] org-table-rotate-recalc-marks)))
4067 elt key fun cmd)
4068 (while (setq elt (pop bindings))
4069 (setq nfunc (1+ nfunc))
4070 (setq key (org-key (car elt))
4071 fun (nth 1 elt)
4072 cmd (orgtbl-make-binding fun nfunc key))
4073 (org-defkey orgtbl-mode-map key cmd))
4075 ;; Special treatment needed for TAB and RET
4076 (org-defkey orgtbl-mode-map [(return)]
4077 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4078 (org-defkey orgtbl-mode-map "\C-m"
4079 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4081 (org-defkey orgtbl-mode-map [(tab)]
4082 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4083 (org-defkey orgtbl-mode-map "\C-i"
4084 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4086 (org-defkey orgtbl-mode-map [(shift tab)]
4087 (orgtbl-make-binding 'org-table-previous-field 104
4088 [(shift tab)] [(tab)] "\C-i"))
4091 (unless (featurep 'xemacs)
4092 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4093 (orgtbl-make-binding 'org-table-previous-field 107
4094 [S-iso-lefttab] [backtab] [(shift tab)]
4095 [(tab)] "\C-i")))
4097 (org-defkey orgtbl-mode-map [backtab]
4098 (orgtbl-make-binding 'org-table-previous-field 108
4099 [backtab] [S-iso-lefttab] [(shift tab)]
4100 [(tab)] "\C-i"))
4102 (org-defkey orgtbl-mode-map "\M-\C-m"
4103 (orgtbl-make-binding 'org-table-wrap-region 105
4104 "\M-\C-m" [(meta return)]))
4105 (org-defkey orgtbl-mode-map [(meta return)]
4106 (orgtbl-make-binding 'org-table-wrap-region 106
4107 [(meta return)] "\M-\C-m"))
4109 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4110 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4112 (when orgtbl-optimized
4113 ;; If the user wants maximum table support, we need to hijack
4114 ;; some standard editing functions
4115 (org-remap orgtbl-mode-map
4116 'self-insert-command 'orgtbl-self-insert-command
4117 'delete-char 'org-delete-char
4118 'delete-backward-char 'org-delete-backward-char)
4119 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4120 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4121 '("OrgTbl"
4122 ["Create or convert" org-table-create-or-convert-from-region
4123 :active (not (org-at-table-p)) :keys "C-c |" ]
4124 "--"
4125 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4126 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4127 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4128 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4129 "--"
4130 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4131 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4132 ["Copy Field from Above"
4133 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4134 "--"
4135 ("Column"
4136 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4137 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4138 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4139 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4140 ("Row"
4141 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4142 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4143 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4144 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4145 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4146 "--"
4147 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4148 ("Rectangle"
4149 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4150 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4151 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4152 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4153 "--"
4154 ("Radio tables"
4155 ["Insert table template" orgtbl-insert-radio-table
4156 (assq major-mode orgtbl-radio-table-templates)]
4157 ["Comment/uncomment table" orgtbl-toggle-comment t])
4158 "--"
4159 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4160 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4161 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4162 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4163 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4164 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4165 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4166 ["Sum Column/Rectangle" org-table-sum
4167 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4168 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4169 ["Debug Formulas"
4170 org-table-toggle-formula-debugger :active (org-at-table-p)
4171 :keys "C-c {"
4172 :style toggle :selected org-table-formula-debug]
4173 ["Show Col/Row Numbers"
4174 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4175 :keys "C-c }"
4176 :style toggle :selected org-table-overlay-coordinates]
4180 (defun orgtbl-ctrl-c-ctrl-c (arg)
4181 "If the cursor is inside a table, realign the table.
4182 If it is a table to be sent away to a receiver, do it.
4183 With prefix arg, also recompute table."
4184 (interactive "P")
4185 (let ((case-fold-search t) (pos (point)) action consts-str consts cst const-str)
4186 (save-excursion
4187 (beginning-of-line 1)
4188 (setq action (cond
4189 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4190 ((looking-at "[ \t]*|") pos)
4191 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4192 (cond
4193 ((integerp action)
4194 (goto-char action)
4195 (org-table-maybe-eval-formula)
4196 (if arg
4197 (call-interactively 'org-table-recalculate)
4198 (org-table-maybe-recalculate-line))
4199 (call-interactively 'org-table-align)
4200 (when (orgtbl-send-table 'maybe)
4201 (run-hooks 'orgtbl-after-send-table-hook)))
4202 ((eq action 'recalc)
4203 (save-excursion
4204 (goto-char (point-min))
4205 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4206 (setq const-str (substring-no-properties (match-string 1)))
4207 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4208 (when consts
4209 (let (e)
4210 (while (setq e (pop consts))
4211 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4212 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4213 (setq org-table-formula-constants-local cst)))))
4214 (save-excursion
4215 (beginning-of-line 1)
4216 (skip-chars-backward " \r\n\t")
4217 (if (org-at-table-p)
4218 (org-call-with-arg 'org-table-recalculate t))))
4219 (t (let (orgtbl-mode)
4220 (call-interactively (key-binding "\C-c\C-c")))))))
4222 (defun orgtbl-create-or-convert-from-region (arg)
4223 "Create table or convert region to table, if no conflicting binding.
4224 This installs the table binding `C-c |', but only if there is no
4225 conflicting binding to this key outside orgtbl-mode."
4226 (interactive "P")
4227 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4228 (if cmd
4229 (call-interactively cmd)
4230 (call-interactively 'org-table-create-or-convert-from-region))))
4232 (defun orgtbl-tab (arg)
4233 "Justification and field motion for `orgtbl-mode'."
4234 (interactive "P")
4235 (if arg (org-table-edit-field t)
4236 (org-table-justify-field-maybe)
4237 (org-table-next-field)))
4239 (defun orgtbl-ret ()
4240 "Justification and field motion for `orgtbl-mode'."
4241 (interactive)
4242 (if (bobp)
4243 (newline)
4244 (org-table-justify-field-maybe)
4245 (org-table-next-row)))
4247 (defun orgtbl-self-insert-command (N)
4248 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4249 If the cursor is in a table looking at whitespace, the whitespace is
4250 overwritten, and the table is not marked as requiring realignment."
4251 (interactive "p")
4252 (if (and (org-at-table-p)
4254 (and org-table-auto-blank-field
4255 (member last-command
4256 '(orgtbl-hijacker-command-100
4257 orgtbl-hijacker-command-101
4258 orgtbl-hijacker-command-102
4259 orgtbl-hijacker-command-103
4260 orgtbl-hijacker-command-104
4261 orgtbl-hijacker-command-105
4262 yas/expand))
4263 (org-table-blank-field))
4265 (eq N 1)
4266 (looking-at "[^|\n]* +|"))
4267 (let (org-table-may-need-update)
4268 (goto-char (1- (match-end 0)))
4269 (org-delete-backward-char 1)
4270 (goto-char (match-beginning 0))
4271 (self-insert-command N))
4272 (setq org-table-may-need-update t)
4273 (let* (orgtbl-mode
4275 (cmd (or (key-binding
4276 (or (and (listp function-key-map)
4277 (setq a (assoc last-input-event function-key-map))
4278 (cdr a))
4279 (vector last-input-event)))
4280 'self-insert-command)))
4281 (call-interactively cmd)
4282 (if (and org-self-insert-cluster-for-undo
4283 (eq cmd 'self-insert-command))
4284 (if (not (eq last-command 'orgtbl-self-insert-command))
4285 (setq org-self-insert-command-undo-counter 1)
4286 (if (>= org-self-insert-command-undo-counter 20)
4287 (setq org-self-insert-command-undo-counter 1)
4288 (and (> org-self-insert-command-undo-counter 0)
4289 buffer-undo-list
4290 (not (cadr buffer-undo-list)) ; remove nil entry
4291 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4292 (setq org-self-insert-command-undo-counter
4293 (1+ org-self-insert-command-undo-counter))))))))
4295 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4296 "Regular expression matching exponentials as produced by calc.")
4298 (defun orgtbl-export (table target)
4299 (require 'org-exp)
4300 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4301 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4302 org-table-last-alignment org-table-last-column-widths
4303 maxcol column)
4304 (if (not (fboundp func))
4305 (error "Cannot export orgtbl table to %s" target))
4306 (setq lines (org-table-clean-before-export lines))
4307 (setq table
4308 (mapcar
4309 (lambda (x)
4310 (if (string-match org-table-hline-regexp x)
4311 'hline
4312 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4313 lines))
4314 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4315 table)))
4316 (loop for i from (1- maxcol) downto 0 do
4317 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4318 (setq column (delq nil column))
4319 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4320 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
4321 (funcall func table nil)))
4323 (defun orgtbl-gather-send-defs ()
4324 "Gather a plist of :name, :transform, :params for each destination before
4325 a radio table."
4326 (save-excursion
4327 (goto-char (org-table-begin))
4328 (let (rtn)
4329 (beginning-of-line 0)
4330 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4331 (let ((name (org-no-properties (match-string 1)))
4332 (transform (intern (match-string 2)))
4333 (params (if (match-end 3)
4334 (read (concat "(" (match-string 3) ")")))))
4335 (push (list :name name :transform transform :params params)
4336 rtn)
4337 (beginning-of-line 0)))
4338 rtn)))
4340 (defun orgtbl-send-replace-tbl (name txt)
4341 "Find and replace table NAME with TXT."
4342 (save-excursion
4343 (goto-char (point-min))
4344 (unless (re-search-forward
4345 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4346 (error "Don't know where to insert translated table"))
4347 (goto-char (match-beginning 0))
4348 (beginning-of-line 2)
4349 (save-excursion
4350 (let ((beg (point)))
4351 (unless (re-search-forward
4352 (concat "END RECEIVE ORGTBL +" name) nil t)
4353 (error "Cannot find end of insertion region"))
4354 (beginning-of-line 1)
4355 (delete-region beg (point))))
4356 (insert txt "\n")))
4358 ;;;###autoload
4359 (defun org-table-to-lisp (&optional txt)
4360 "Convert the table at point to a Lisp structure.
4361 The structure will be a list. Each item is either the symbol `hline'
4362 for a horizontal separator line, or a list of field values as strings.
4363 The table is taken from the parameter TXT, or from the buffer at point."
4364 (unless txt
4365 (unless (org-at-table-p)
4366 (error "No table at point")))
4367 (let* ((txt (or txt
4368 (buffer-substring-no-properties (org-table-begin)
4369 (org-table-end))))
4370 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4372 (mapcar
4373 (lambda (x)
4374 (if (string-match org-table-hline-regexp x)
4375 'hline
4376 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4377 lines)))
4379 (defun orgtbl-send-table (&optional maybe)
4380 "Send a transformed version of this table to the receiver position.
4381 With argument MAYBE, fail quietly if no transformation is defined for
4382 this table."
4383 (interactive)
4384 (catch 'exit
4385 (unless (org-at-table-p) (error "Not at a table"))
4386 ;; when non-interactive, we assume align has just happened.
4387 (when (org-called-interactively-p 'any) (org-table-align))
4388 (let ((dests (orgtbl-gather-send-defs))
4389 (txt (buffer-substring-no-properties (org-table-begin)
4390 (org-table-end)))
4391 (ntbl 0))
4392 (unless dests (if maybe (throw 'exit nil)
4393 (error "Don't know how to transform this table")))
4394 (dolist (dest dests)
4395 (let* ((name (plist-get dest :name))
4396 (transform (plist-get dest :transform))
4397 (params (plist-get dest :params))
4398 (skip (plist-get params :skip))
4399 (skipcols (plist-get params :skipcols))
4400 (no-escape (plist-get params :no-escape))
4402 (lines (org-table-clean-before-export
4403 (nthcdr (or skip 0)
4404 (org-split-string txt "[ \t]*\n[ \t]*"))))
4405 (i0 (if org-table-clean-did-remove-column 2 1))
4406 (lines (if no-escape lines
4407 (mapcar (lambda(l) (replace-regexp-in-string
4408 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4409 (table (mapcar
4410 (lambda (x)
4411 (if (string-match org-table-hline-regexp x)
4412 'hline
4413 (org-remove-by-index
4414 (org-split-string (org-trim x) "\\s-*|\\s-*")
4415 skipcols i0)))
4416 lines))
4417 (fun (if (= i0 2) 'cdr 'identity))
4418 (org-table-last-alignment
4419 (org-remove-by-index (funcall fun org-table-last-alignment)
4420 skipcols i0))
4421 (org-table-last-column-widths
4422 (org-remove-by-index (funcall fun org-table-last-column-widths)
4423 skipcols i0))
4424 (txt (if (fboundp transform)
4425 (funcall transform table params)
4426 (error "No such transformation function %s" transform))))
4427 (orgtbl-send-replace-tbl name txt))
4428 (setq ntbl (1+ ntbl)))
4429 (message "Table converted and installed at %d receiver location%s"
4430 ntbl (if (> ntbl 1) "s" ""))
4431 (if (> ntbl 0)
4432 ntbl
4433 nil))))
4435 (defun org-remove-by-index (list indices &optional i0)
4436 "Remove the elements in LIST with indices in INDICES.
4437 First element has index 0, or I0 if given."
4438 (if (not indices)
4439 list
4440 (if (integerp indices) (setq indices (list indices)))
4441 (setq i0 (1- (or i0 0)))
4442 (delq :rm (mapcar (lambda (x)
4443 (setq i0 (1+ i0))
4444 (if (memq i0 indices) :rm x))
4445 list))))
4447 (defun orgtbl-toggle-comment ()
4448 "Comment or uncomment the orgtbl at point."
4449 (interactive)
4450 (let* ((case-fold-search t)
4451 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4452 (re2 (concat "^" orgtbl-line-start-regexp))
4453 (commented (save-excursion (beginning-of-line 1)
4454 (cond ((looking-at re1) t)
4455 ((looking-at re2) nil)
4456 (t (error "Not at an org table")))))
4457 (re (if commented re1 re2))
4458 beg end)
4459 (save-excursion
4460 (beginning-of-line 1)
4461 (while (looking-at re) (beginning-of-line 0))
4462 (beginning-of-line 2)
4463 (setq beg (point))
4464 (while (looking-at re) (beginning-of-line 2))
4465 (setq end (point)))
4466 (comment-region beg end (if commented '(4) nil))))
4468 (defun orgtbl-insert-radio-table ()
4469 "Insert a radio table template appropriate for this major mode."
4470 (interactive)
4471 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4472 (txt (nth 1 e))
4473 name pos)
4474 (unless e (error "No radio table setup defined for %s" major-mode))
4475 (setq name (read-string "Table name: "))
4476 (while (string-match "%n" txt)
4477 (setq txt (replace-match name t t txt)))
4478 (or (bolp) (insert "\n"))
4479 (setq pos (point))
4480 (insert txt)
4481 (goto-char pos)))
4483 ;; Dynamically bound input and output for table formatting.
4484 (defvar *orgtbl-table* nil
4485 "Carries the current table through formatting routines.")
4486 (defvar *orgtbl-rtn* nil
4487 "Formatting routines push the output lines here.")
4488 ;; Formatting parameters for the current table section.
4489 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4490 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4491 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4492 (defvar *orgtbl-fmt* nil "Format for each entry.")
4493 (defvar *orgtbl-efmt* nil "Format for numbers.")
4494 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4495 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4496 (defvar *orgtbl-lstart* nil "Text starting a row.")
4497 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4498 (defvar *orgtbl-lend* nil "Text ending a row.")
4499 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4501 (defsubst orgtbl-get-fmt (fmt i)
4502 "Retrieve the format from FMT corresponding to the Ith column."
4503 (if (and (not (functionp fmt)) (consp fmt))
4504 (plist-get fmt i)
4505 fmt))
4507 (defsubst orgtbl-apply-fmt (fmt &rest args)
4508 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4509 (cond ((functionp fmt) (apply fmt args))
4510 (fmt (apply 'format fmt args))
4511 (args (car args))
4512 (t args)))
4514 (defsubst orgtbl-eval-str (str)
4515 "If STR is a function, evaluate it with no arguments."
4516 (if (functionp str)
4517 (funcall str)
4518 str))
4520 (defun orgtbl-format-line (line)
4521 "Format LINE as a table row."
4522 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4523 (let* ((i 0)
4524 (line
4525 (mapcar
4526 (lambda (f)
4527 (setq i (1+ i))
4528 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4529 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4530 (orgtbl-apply-fmt efmt (match-string 1 f)
4531 (match-string 2 f))
4532 f)))
4533 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4534 *orgtbl-default-fmt*)
4535 f)))
4536 line)))
4537 (push (if *orgtbl-lfmt*
4538 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4539 (concat (orgtbl-eval-str *orgtbl-lstart*)
4540 (mapconcat 'identity line *orgtbl-sep*)
4541 (orgtbl-eval-str *orgtbl-lend*)))
4542 *orgtbl-rtn*))))
4544 (defun orgtbl-format-section (section-stopper)
4545 "Format lines until the first occurrence of SECTION-STOPPER."
4546 (let (prevline)
4547 (progn
4548 (while (not (eq (car *orgtbl-table*) section-stopper))
4549 (if prevline (orgtbl-format-line prevline))
4550 (setq prevline (pop *orgtbl-table*)))
4551 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4552 (*orgtbl-lend* *orgtbl-llend*)
4553 (*orgtbl-lfmt* *orgtbl-llfmt*))
4554 (orgtbl-format-line prevline))))))
4556 ;;;###autoload
4557 (defun orgtbl-to-generic (table params)
4558 "Convert the orgtbl-mode TABLE to some other format.
4559 This generic routine can be used for many standard cases.
4560 TABLE is a list, each entry either the symbol `hline' for a horizontal
4561 separator line, or a list of fields for that line.
4562 PARAMS is a property list of parameters that can influence the conversion.
4563 For the generic converter, some parameters are obligatory: you need to
4564 specify either :lfmt, or all of (:lstart :lend :sep).
4566 Valid parameters are:
4568 :splice When set to t, return only table body lines, don't wrap
4569 them into :tstart and :tend. Default is nil. When :splice
4570 is non-nil, this also means that the exporter should not look
4571 for and interpret header and footer sections.
4573 :hline String to be inserted on horizontal separation lines.
4574 May be nil to ignore hlines.
4576 :sep Separator between two fields
4577 :remove-nil-lines Do not include lines that evaluate to nil.
4579 Each in the following group may be either a string or a function
4580 of no arguments returning a string:
4582 :tstart String to start the table. Ignored when :splice is t.
4583 :tend String to end the table. Ignored when :splice is t.
4584 :lstart String to start a new table line.
4585 :llstart String to start the last table line, defaults to :lstart.
4586 :lend String to end a table line
4587 :llend String to end the last table line, defaults to :lend.
4589 Each in the following group may be a string, a function of one
4590 argument (the field or line) returning a string, or a plist
4591 mapping columns to either of the above:
4593 :lfmt Format for entire line, with enough %s to capture all fields.
4594 If this is present, :lstart, :lend, and :sep are ignored.
4595 :llfmt Format for the entire last line, defaults to :lfmt.
4596 :fmt A format to be used to wrap the field, should contain
4597 %s for the original field value. For example, to wrap
4598 everything in dollars, you could use :fmt \"$%s$\".
4599 This may also be a property list with column numbers and
4600 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4601 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4602 Same as above, specific for the header lines in the table.
4603 All lines before the first hline are treated as header.
4604 If any of these is not present, the data line value is used.
4606 This may be either a string or a function of two arguments:
4608 :efmt Use this format to print numbers with exponentials.
4609 The format should have %s twice for inserting mantissa
4610 and exponent, for example \"%s\\\\times10^{%s}\". This
4611 may also be a property list with column numbers and
4612 formats. :fmt will still be applied after :efmt.
4614 In addition to this, the parameters :skip and :skipcols are always handled
4615 directly by `orgtbl-send-table'. See manual."
4616 (let* ((splicep (plist-get params :splice))
4617 (hline (plist-get params :hline))
4618 (skipheadrule (plist-get params :skipheadrule))
4619 (remove-nil-linesp (plist-get params :remove-nil-lines))
4620 (remove-newlines (plist-get params :remove-newlines))
4621 (*orgtbl-hline* hline)
4622 (*orgtbl-table* table)
4623 (*orgtbl-sep* (plist-get params :sep))
4624 (*orgtbl-efmt* (plist-get params :efmt))
4625 (*orgtbl-lstart* (plist-get params :lstart))
4626 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4627 (*orgtbl-lend* (plist-get params :lend))
4628 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4629 (*orgtbl-lfmt* (plist-get params :lfmt))
4630 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4631 (*orgtbl-fmt* (plist-get params :fmt))
4632 *orgtbl-rtn*)
4634 ;; Put header
4635 (unless splicep
4636 (when (plist-member params :tstart)
4637 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4638 (if tstart (push tstart *orgtbl-rtn*)))))
4640 ;; Do we have a heading section? If so, format it and handle the
4641 ;; trailing hline.
4642 (if (and (not splicep)
4643 (or (consp (car *orgtbl-table*))
4644 (consp (nth 1 *orgtbl-table*)))
4645 (memq 'hline (cdr *orgtbl-table*)))
4646 (progn
4647 (when (eq 'hline (car *orgtbl-table*))
4648 ;; there is a hline before the first data line
4649 (and hline (push hline *orgtbl-rtn*))
4650 (pop *orgtbl-table*))
4651 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4652 *orgtbl-lstart*))
4653 (*orgtbl-llstart* (or (plist-get params :hllstart)
4654 *orgtbl-llstart*))
4655 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4656 (*orgtbl-llend* (or (plist-get params :hllend)
4657 (plist-get params :hlend) *orgtbl-llend*))
4658 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4659 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4660 (plist-get params :hlfmt) *orgtbl-llfmt*))
4661 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4662 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4663 (orgtbl-format-section 'hline))
4664 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4665 (pop *orgtbl-table*)))
4667 ;; Now format the main section.
4668 (orgtbl-format-section nil)
4670 (unless splicep
4671 (when (plist-member params :tend)
4672 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4673 (if tend (push tend *orgtbl-rtn*)))))
4675 (mapconcat (if remove-newlines
4676 (lambda (tend)
4677 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4678 'identity)
4679 (nreverse (if remove-nil-linesp
4680 (remq nil *orgtbl-rtn*)
4681 *orgtbl-rtn*)) "\n")))
4683 ;;;###autoload
4684 (defun orgtbl-to-tsv (table params)
4685 "Convert the orgtbl-mode table to TAB separated material."
4686 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4687 ;;;###autoload
4688 (defun orgtbl-to-csv (table params)
4689 "Convert the orgtbl-mode table to CSV material.
4690 This does take care of the proper quoting of fields with comma or quotes."
4691 (orgtbl-to-generic table (org-combine-plists
4692 '(:sep "," :fmt org-quote-csv-field)
4693 params)))
4695 ;;;###autoload
4696 (defun orgtbl-to-latex (table params)
4697 "Convert the orgtbl-mode TABLE to LaTeX.
4698 TABLE is a list, each entry either the symbol `hline' for a horizontal
4699 separator line, or a list of fields for that line.
4700 PARAMS is a property list of parameters that can influence the conversion.
4701 Supports all parameters from `orgtbl-to-generic'. Most important for
4702 LaTeX are:
4704 :splice When set to t, return only table body lines, don't wrap
4705 them into a tabular environment. Default is nil.
4707 :fmt A format to be used to wrap the field, should contain %s for the
4708 original field value. For example, to wrap everything in dollars,
4709 use :fmt \"$%s$\". This may also be a property list with column
4710 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4711 The format may also be a function that formats its one argument.
4713 :efmt Format for transforming numbers with exponentials. The format
4714 should have %s twice for inserting mantissa and exponent, for
4715 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4716 This may also be a property list with column numbers and formats.
4717 The format may also be a function that formats its two arguments.
4719 :llend If you find too much space below the last line of a table,
4720 pass a value of \"\" for :llend to suppress the final \\\\.
4722 The general parameters :skip and :skipcols have already been applied when
4723 this function is called."
4724 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4725 org-table-last-alignment ""))
4726 (params2
4727 (list
4728 :tstart (concat "\\begin{tabular}{" alignment "}")
4729 :tend "\\end{tabular}"
4730 :lstart "" :lend " \\\\" :sep " & "
4731 :efmt "%s\\,(%s)" :hline "\\hline")))
4732 (orgtbl-to-generic table (org-combine-plists params2 params))))
4734 ;;;###autoload
4735 (defun orgtbl-to-html (table params)
4736 "Convert the orgtbl-mode TABLE to HTML.
4737 TABLE is a list, each entry either the symbol `hline' for a horizontal
4738 separator line, or a list of fields for that line.
4739 PARAMS is a property list of parameters that can influence the conversion.
4740 Currently this function recognizes the following parameters:
4742 :splice When set to t, return only table body lines, don't wrap
4743 them into a <table> environment. Default is nil.
4745 The general parameters :skip and :skipcols have already been applied when
4746 this function is called. The function does *not* use `orgtbl-to-generic',
4747 so you cannot specify parameters for it."
4748 (let* ((splicep (plist-get params :splice))
4749 (html-table-tag org-export-html-table-tag)
4750 html)
4751 ;; Just call the formatter we already have
4752 ;; We need to make text lines for it, so put the fields back together.
4753 (setq html (org-format-org-table-html
4754 (mapcar
4755 (lambda (x)
4756 (if (eq x 'hline)
4757 "|----+----|"
4758 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4759 table)
4760 splicep))
4761 (if (string-match "\n+\\'" html)
4762 (setq html (replace-match "" t t html)))
4763 html))
4765 ;;;###autoload
4766 (defun orgtbl-to-texinfo (table params)
4767 "Convert the orgtbl-mode TABLE to TeXInfo.
4768 TABLE is a list, each entry either the symbol `hline' for a horizontal
4769 separator line, or a list of fields for that line.
4770 PARAMS is a property list of parameters that can influence the conversion.
4771 Supports all parameters from `orgtbl-to-generic'. Most important for
4772 TeXInfo are:
4774 :splice nil/t When set to t, return only table body lines, don't wrap
4775 them into a multitable environment. Default is nil.
4777 :fmt fmt A format to be used to wrap the field, should contain
4778 %s for the original field value. For example, to wrap
4779 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4780 This may also be a property list with column numbers and
4781 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4782 Each format also may be a function that formats its one
4783 argument.
4785 :cf \"f1 f2..\" The column fractions for the table. By default these
4786 are computed automatically from the width of the columns
4787 under org-mode.
4789 The general parameters :skip and :skipcols have already been applied when
4790 this function is called."
4791 (let* ((total (float (apply '+ org-table-last-column-widths)))
4792 (colfrac (or (plist-get params :cf)
4793 (mapconcat
4794 (lambda (x) (format "%.3f" (/ (float x) total)))
4795 org-table-last-column-widths " ")))
4796 (params2
4797 (list
4798 :tstart (concat "@multitable @columnfractions " colfrac)
4799 :tend "@end multitable"
4800 :lstart "@item " :lend "" :sep " @tab "
4801 :hlstart "@headitem ")))
4802 (orgtbl-to-generic table (org-combine-plists params2 params))))
4804 ;;;###autoload
4805 (defun orgtbl-to-orgtbl (table params)
4806 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4807 Useful when slicing one table into many. The :hline, :sep,
4808 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4809 and :tend suppress strings without splicing; they can be set to
4810 provide ORGTBL directives for the generated table."
4811 (let* ((params2
4812 (list
4813 :remove-newlines t
4814 :tstart nil :tend nil
4815 :hline "|---"
4816 :sep " | "
4817 :lstart "| "
4818 :lend " |"))
4819 (params (org-combine-plists params2 params)))
4820 (with-temp-buffer
4821 (insert (orgtbl-to-generic table params))
4822 (goto-char (point-min))
4823 (while (re-search-forward org-table-hline-regexp nil t)
4824 (org-table-align))
4825 (buffer-substring 1 (buffer-size)))))
4827 (defun orgtbl-to-table.el (table params)
4828 "Convert the orgtbl-mode TABLE into a table.el table."
4829 (with-temp-buffer
4830 (insert (orgtbl-to-orgtbl table params))
4831 (org-table-align)
4832 (replace-regexp-in-string
4833 "-|" "-+"
4834 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4836 (defun orgtbl-to-unicode (table params)
4837 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4838 You need the ascii-art-to-unicode.el package for this. You can download
4839 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4840 (with-temp-buffer
4841 (insert (orgtbl-to-table.el table params))
4842 (goto-char (point-min))
4843 (if (or (featurep 'ascii-art-to-unicode)
4844 (require 'ascii-art-to-unicode nil t))
4845 (aa2u)
4846 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4847 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4848 "Link to ascii-art-to-unicode.el") org-stored-links))
4849 (error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4850 (buffer-string)))
4852 (defun org-table-get-remote-range (name-or-id form)
4853 "Get a field value or a list of values in a range from table at ID.
4855 NAME-OR-ID may be the name of a table in the current file as set by
4856 a \"#+TBLNAME:\" directive. The first table following this line
4857 will then be used. Alternatively, it may be an ID referring to
4858 any entry, also in a different file. In this case, the first table
4859 in that entry will be referenced.
4860 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4861 \"@I$2..@II$2\". All the references must be absolute, not relative.
4863 The return value is either a single string for a single field, or a
4864 list of the fields in the rectangle ."
4865 (save-match-data
4866 (let ((case-fold-search t) (id-loc nil)
4867 ;; Protect a bunch of variables from being overwritten
4868 ;; by the context of the remote table
4869 org-table-column-names org-table-column-name-regexp
4870 org-table-local-parameters org-table-named-field-locations
4871 org-table-current-line-types org-table-current-begin-line
4872 org-table-current-begin-pos org-table-dlines
4873 org-table-current-ncol
4874 org-table-hlines org-table-last-alignment
4875 org-table-last-column-widths org-table-last-alignment
4876 org-table-last-column-widths tbeg
4877 buffer loc)
4878 (setq form (org-table-convert-refs-to-rc form))
4879 (save-excursion
4880 (save-restriction
4881 (widen)
4882 (save-excursion
4883 (goto-char (point-min))
4884 (if (re-search-forward
4885 (concat "^[ \t]*#\\+tblname:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4886 nil t)
4887 (setq buffer (current-buffer) loc (match-beginning 0))
4888 (setq id-loc (org-id-find name-or-id 'marker))
4889 (unless (and id-loc (markerp id-loc))
4890 (error "Can't find remote table \"%s\"" name-or-id))
4891 (setq buffer (marker-buffer id-loc)
4892 loc (marker-position id-loc))
4893 (move-marker id-loc nil)))
4894 (with-current-buffer buffer
4895 (save-excursion
4896 (save-restriction
4897 (widen)
4898 (goto-char loc)
4899 (forward-char 1)
4900 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4901 (not (match-beginning 1)))
4902 (error "Cannot find a table at NAME or ID %s" name-or-id))
4903 (setq tbeg (point-at-bol))
4904 (org-table-get-specials)
4905 (setq form (org-table-formula-substitute-names
4906 (org-table-formula-handle-first/last-rc form)))
4907 (if (and (string-match org-table-range-regexp form)
4908 (> (length (match-string 0 form)) 1))
4909 (save-match-data
4910 (org-table-get-range (match-string 0 form) tbeg 1))
4911 form)))))))))
4913 (defmacro org-define-lookup-function (mode)
4914 (let ((mode-str (symbol-name mode))
4915 (first-p (equal mode 'first))
4916 (all-p (equal mode 'all)))
4917 (let ((plural-str (if all-p "s" "")))
4918 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4919 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4920 If R-LIST is nil, return matching element%s of S-LIST.
4921 If PREDICATE is not nil, use it instead of `equal' to match VAL.
4922 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
4923 This function is generated by a call to the macro `org-define-lookup-function'."
4924 mode-str plural-str plural-str plural-str)
4925 (let ,(let ((lvars '((p (or predicate 'equal))
4926 (sl s-list)
4927 (rl (or r-list s-list))
4928 (ret nil))))
4929 (if first-p (add-to-list 'lvars '(match-p nil)))
4930 lvars)
4931 (while ,(if first-p '(and (not match-p) sl) 'sl)
4932 (progn
4933 (if (funcall p val (car sl))
4934 (progn
4935 ,(if first-p '(setq match-p t))
4936 (let ((rval (car rl)))
4937 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
4938 (setq sl (cdr sl) rl (cdr rl))))
4939 ret)))))
4941 (org-define-lookup-function first)
4942 (org-define-lookup-function last)
4943 (org-define-lookup-function all)
4945 (provide 'org-table)
4947 ;; Local variables:
4948 ;; generated-autoload-file: "org-loaddefs.el"
4949 ;; End:
4951 ;;; org-table.el ends here