6a9d0b4a4821ac0b317fc9a0031bc2c9163d5a20
[org-mode.git] / lisp / org-table.el
blob6a9d0b4a4821ac0b317fc9a0031bc2c9163d5a20
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2012 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) (number-to-string (string-to-number x)))
2561 fields)))
2562 (setq ndown (1- ndown))
2563 (setq form (copy-sequence formula)
2564 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2565 (if (and lispp literal) (setq lispp 'literal))
2567 ;; Insert row and column number of formula result field
2568 (while (string-match "[@$]#" form)
2569 (setq form
2570 (replace-match
2571 (format "%d"
2572 (save-match-data
2573 (if (equal (substring form (match-beginning 0)
2574 (1+ (match-beginning 0)))
2575 "@")
2576 (org-table-current-dline)
2577 (org-table-current-column))))
2578 t t form)))
2580 ;; Check for old vertical references
2581 (setq form (org-table-rewrite-old-row-references form))
2582 ;; Insert remote references
2583 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2584 (setq form
2585 (replace-match
2586 (save-match-data
2587 (org-table-make-reference
2588 (let ((rmtrng (org-table-get-remote-range
2589 (match-string 1 form) (match-string 2 form))))
2590 (if duration
2591 (if (listp rmtrng)
2592 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2593 (org-table-time-string-to-seconds rmtrng))
2594 rmtrng))
2595 keep-empty numbers lispp))
2596 t t form)))
2597 ;; Insert complex ranges
2598 (while (and (string-match org-table-range-regexp form)
2599 (> (length (match-string 0 form)) 1))
2600 (setq formrg (save-match-data
2601 (org-table-get-range (match-string 0 form) nil n0)))
2602 (setq formrpl
2603 (save-match-data
2604 (org-table-make-reference
2605 ;; possibly handle durations
2606 (if duration
2607 (if (listp formrg)
2608 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2609 (org-table-time-string-to-seconds formrg))
2610 formrg)
2611 keep-empty numbers lispp)))
2612 (if (not (save-match-data
2613 (string-match (regexp-quote form) formrpl)))
2614 (setq form (replace-match formrpl t t form))
2615 (error "Spreadsheet error: invalid reference \"%s\"" form)))
2616 ;; Insert simple ranges
2617 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2618 (setq form
2619 (replace-match
2620 (save-match-data
2621 (org-table-make-reference
2622 (org-sublist
2623 fields (string-to-number (match-string 1 form))
2624 (string-to-number (match-string 2 form)))
2625 keep-empty numbers lispp))
2626 t t form)))
2627 (setq form0 form)
2628 ;; Insert the references to fields in same row
2629 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2630 (setq n (+ (string-to-number (match-string 1 form))
2631 (if (match-end 2) n0 0))
2632 x (nth (1- (if (= n 0) n0 (max n 1))) fields))
2633 (unless x (error "Invalid field specifier \"%s\""
2634 (match-string 0 form)))
2635 (setq form (replace-match
2636 (save-match-data
2637 (org-table-make-reference x nil numbers lispp))
2638 t t form)))
2640 (if lispp
2641 (setq ev (condition-case nil
2642 (eval (eval (read form)))
2643 (error "#ERROR"))
2644 ev (if (numberp ev) (number-to-string ev) ev)
2645 ev (if duration (org-table-time-seconds-to-string
2646 (string-to-number ev)
2647 duration-output-format) ev))
2648 (or (fboundp 'calc-eval)
2649 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2650 ;; Use <...> time-stamps so that Calc can handle them
2651 (setq form (replace-regexp-in-string org-ts-regexp3 "<\\1>" form))
2652 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2653 (when (string-match org-ts-regexp2 form)
2654 (let* ((ts (match-string 0 form))
2655 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2656 (system-time-locale "C")
2657 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2658 (cdr org-time-stamp-formats))
2659 (car org-time-stamp-formats))))
2660 (setq form (replace-match (format-time-string tf tsp) t t form))))
2662 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2663 form
2664 (calc-eval (cons form org-tbl-calc-modes) (if numbers 'num)))
2665 ev (if duration (org-table-time-seconds-to-string
2666 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2667 (string-to-number (org-table-time-string-to-seconds ev))
2668 (string-to-number ev))
2669 duration-output-format)
2670 ev)))
2672 (when org-table-formula-debug
2673 (with-output-to-temp-buffer "*Substitution History*"
2674 (princ (format "Substitution history of formula
2675 Orig: %s
2676 $xyz-> %s
2677 @r$c-> %s
2678 $1-> %s\n" orig formula form0 form))
2679 (if (listp ev)
2680 (princ (format " %s^\nError: %s"
2681 (make-string (car ev) ?\-) (nth 1 ev)))
2682 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2683 ev (or fmt "NONE")
2684 (if fmt (format fmt (string-to-number ev)) ev)))))
2685 (setq bw (get-buffer-window "*Substitution History*"))
2686 (org-fit-window-to-buffer bw)
2687 (unless (and (org-called-interactively-p 'any) (not ndown))
2688 (unless (let (inhibit-redisplay)
2689 (y-or-n-p "Debugging Formula. Continue to next? "))
2690 (org-table-align)
2691 (error "Abort"))
2692 (delete-window bw)
2693 (message "")))
2694 (if (listp ev) (setq fmt nil ev "#ERROR"))
2695 (org-table-justify-field-maybe
2696 (format org-table-formula-field-format
2697 (if fmt (format fmt (string-to-number ev)) ev)))
2698 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2699 (call-interactively 'org-return)
2700 (setq ndown 0)))
2701 (and down (org-table-maybe-recalculate-line))
2702 (or suppress-align (and org-table-may-need-update
2703 (org-table-align))))))
2705 (defun org-table-put-field-property (prop value)
2706 (save-excursion
2707 (put-text-property (progn (skip-chars-backward "^|") (point))
2708 (progn (skip-chars-forward "^|") (point))
2709 prop value)))
2711 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2712 "Get a calc vector from a column, according to descriptor DESC.
2713 Optional arguments TBEG and COL can give the beginning of the table and
2714 the current column, to avoid unnecessary parsing.
2716 HIGHLIGHT means just highlight the range.
2718 When CORNERS-ONLY is set, only return the corners of the range as
2719 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2720 in the buffer and column1 and column2 are table column numbers."
2721 (if (not (equal (string-to-char desc) ?@))
2722 (setq desc (concat "@" desc)))
2723 (save-excursion
2724 (or tbeg (setq tbeg (org-table-begin)))
2725 (or col (setq col (org-table-current-column)))
2726 (let ((thisline (org-current-line))
2727 beg end c1 c2 r1 r2 rangep tmp)
2728 (unless (string-match org-table-range-regexp desc)
2729 (error "Invalid table range specifier `%s'" desc))
2730 (setq rangep (match-end 3)
2731 r1 (and (match-end 1) (match-string 1 desc))
2732 r2 (and (match-end 4) (match-string 4 desc))
2733 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2734 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2736 (and c1 (setq c1 (+ (string-to-number c1)
2737 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2738 (and c2 (setq c2 (+ (string-to-number c2)
2739 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2740 (if (equal r1 "") (setq r1 nil))
2741 (if (equal r2 "") (setq r2 nil))
2742 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2743 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2744 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2745 (if (not r1) (setq r1 thisline))
2746 (if (not r2) (setq r2 thisline))
2747 (if (or (not c1) (= 0 c1)) (setq c1 col))
2748 (if (or (not c2) (= 0 c2)) (setq c2 col))
2749 (if (and (not corners-only)
2750 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2751 ;; just one field
2752 (progn
2753 (org-goto-line r1)
2754 (while (not (looking-at org-table-dataline-regexp))
2755 (beginning-of-line 2))
2756 (prog1 (org-trim (org-table-get-field c1))
2757 (if highlight (org-table-highlight-rectangle (point) (point)))))
2758 ;; A range, return a vector
2759 ;; First sort the numbers to get a regular rectangle
2760 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2761 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2762 (if corners-only
2763 ;; Only return the corners of the range
2764 (list r1 c1 r2 c2)
2765 ;; Copy the range values into a list
2766 (org-goto-line r1)
2767 (while (not (looking-at org-table-dataline-regexp))
2768 (beginning-of-line 2))
2769 (org-table-goto-column c1)
2770 (setq beg (point))
2771 (org-goto-line r2)
2772 (while (not (looking-at org-table-dataline-regexp))
2773 (beginning-of-line 0))
2774 (org-table-goto-column c2)
2775 (setq end (point))
2776 (if highlight
2777 (org-table-highlight-rectangle
2778 beg (progn (skip-chars-forward "^|\n") (point))))
2779 ;; return string representation of calc vector
2780 (mapcar 'org-trim
2781 (apply 'append (org-table-copy-region beg end))))))))
2783 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2784 "Analyze descriptor DESC and retrieve the corresponding line number.
2785 The cursor is currently in line CLINE, the table begins in line BLINE,
2786 and TABLE is a vector with line types."
2787 (if (string-match "^[0-9]+$" desc)
2788 (aref org-table-dlines (string-to-number desc))
2789 (setq cline (or cline (org-current-line))
2790 bline (or bline org-table-current-begin-line)
2791 table (or table org-table-current-line-types))
2792 (if (or
2793 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2794 ;; 1 2 3 4 5 6
2795 (and (not (match-end 3)) (not (match-end 6)))
2796 (and (match-end 3) (match-end 6) (not (match-end 5))))
2797 (error "Invalid row descriptor `%s'" desc))
2798 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2799 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2800 (odir (and (match-end 5) (match-string 5 desc)))
2801 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2802 (i (- cline bline))
2803 (rel (and (match-end 6)
2804 (or (and (match-end 1) (not (match-end 3)))
2805 (match-end 5)))))
2806 (if (and hn (not hdir))
2807 (progn
2808 (setq i 0 hdir "+")
2809 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2810 (if (and (not hn) on (not odir))
2811 (error "Should never happen");;(aref org-table-dlines on)
2812 (if (and hn (> hn 0))
2813 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2814 nil hn cline desc)))
2815 (if on
2816 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2817 rel on cline desc)))
2818 (+ bline i)))))
2820 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2821 "FIXME: Needs more documentation."
2822 (let ((l (length table)))
2823 (while (> n 0)
2824 (while (and (setq i (+ i (if backwards -1 1)))
2825 (>= i 0) (< i l)
2826 (not (eq (aref table i) type))
2827 (if (and relative (eq (aref table i) 'hline))
2828 (cond
2829 ((eq org-table-relative-ref-may-cross-hline t) t)
2830 ((eq org-table-relative-ref-may-cross-hline 'error)
2831 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2832 (t (setq i (- i (if backwards -1 1))
2833 n 1)
2834 nil))
2835 t)))
2836 (setq n (1- n)))
2837 (if (or (< i 0) (>= i l))
2838 (error "Row descriptor %s used in line %d leads outside table"
2839 desc cline)
2840 i)))
2842 (defun org-table-rewrite-old-row-references (s)
2843 (if (string-match "&[-+0-9I]" s)
2844 (error "Formula contains old &row reference, please rewrite using @-syntax")
2847 (defun org-table-make-reference (elements keep-empty numbers lispp)
2848 "Convert list ELEMENTS to something appropriate to insert into formula.
2849 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2850 NUMBERS indicates that everything should be converted to numbers.
2851 LISPP means to return something appropriate for a Lisp list."
2852 (if (stringp elements) ; just a single val
2853 (if lispp
2854 (if (eq lispp 'literal)
2855 elements
2856 (prin1-to-string (if numbers (string-to-number elements) elements)))
2857 (if (equal elements "") (setq elements "0"))
2858 (if numbers (setq elements (number-to-string (string-to-number elements))))
2859 (concat "(" elements ")"))
2860 (unless keep-empty
2861 (setq elements
2862 (delq nil
2863 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2864 elements))))
2865 (setq elements (or elements '("0")))
2866 (if lispp
2867 (mapconcat
2868 (lambda (x)
2869 (if (eq lispp 'literal)
2871 (prin1-to-string (if numbers (string-to-number x) x))))
2872 elements " ")
2873 (concat "[" (mapconcat
2874 (lambda (x)
2875 (if numbers (number-to-string (string-to-number x)) x))
2876 elements
2877 ",") "]"))))
2879 ;;;###autoload
2880 (defun org-table-recalculate (&optional all noalign)
2881 "Recalculate the current table line by applying all stored formulas.
2882 With prefix arg ALL, do this for all lines in the table.
2883 With the prefix argument ALL is `(16)' \
2884 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2885 it is the symbol `iterate', recompute the table until it no longer changes.
2886 If NOALIGN is not nil, do not re-align the table after the computations
2887 are done. This is typically used internally to save time, if it is
2888 known that the table will be realigned a little later anyway."
2889 (interactive "P")
2890 (or (memq this-command org-recalc-commands)
2891 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2892 (unless (org-at-table-p) (error "Not at a table"))
2893 (if (or (eq all 'iterate) (equal all '(16)))
2894 (org-table-iterate)
2895 (org-table-get-specials)
2896 (let* ((eqlist (sort (org-table-get-stored-formulas)
2897 (lambda (a b) (string< (car a) (car b)))))
2898 (eqlist1 (copy-sequence eqlist))
2899 (inhibit-redisplay (not debug-on-error))
2900 (line-re org-table-dataline-regexp)
2901 (thisline (org-current-line))
2902 (thiscol (org-table-current-column))
2903 seen-fields lhs1
2904 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
2905 ;; Insert constants in all formulas
2906 (setq eqlist
2907 (mapcar (lambda (x)
2908 (when (string-match "\\`$[<>]" (car x))
2909 (setq lhs1 (car x))
2910 (setq x (cons (substring
2911 (org-table-formula-handle-first/last-rc
2912 (car x)) 1)
2913 (cdr x)))
2914 (if (assoc (car x) eqlist1)
2915 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2916 lhs1 (car x))))
2917 (cons
2918 (org-table-formula-handle-first/last-rc (car x))
2919 (org-table-formula-substitute-names
2920 (org-table-formula-handle-first/last-rc (cdr x)))))
2921 eqlist))
2922 ;; Split the equation list
2923 (while (setq eq (pop eqlist))
2924 (if (<= (string-to-char (car eq)) ?9)
2925 (push eq eqlnum)
2926 (push eq eqlname)))
2927 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2928 ;; Expand ranges in lhs of formulas
2929 (setq eqlname (org-table-expand-lhs-ranges eqlname))
2931 ;; Get the correct line range to process
2932 (if all
2933 (progn
2934 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2935 (goto-char (setq beg (org-table-begin)))
2936 (if (re-search-forward org-table-calculate-mark-regexp end t)
2937 ;; This is a table with marked lines, compute selected lines
2938 (setq line-re org-table-recalculate-regexp)
2939 ;; Move forward to the first non-header line
2940 (if (and (re-search-forward org-table-dataline-regexp end t)
2941 (re-search-forward org-table-hline-regexp end t)
2942 (re-search-forward org-table-dataline-regexp end t))
2943 (setq beg (match-beginning 0))
2944 nil))) ;; just leave beg where it is
2945 (setq beg (point-at-bol)
2946 end (move-marker (make-marker) (1+ (point-at-eol)))))
2947 (goto-char beg)
2948 (and all (message "Re-applying formulas to full table..."))
2950 ;; First find the named fields, and mark them untouchable.
2951 ;; Also check if several field/range formulas try to set the same field.
2952 (remove-text-properties beg end '(org-untouchable t))
2953 (while (setq eq (pop eqlname))
2954 (setq name (car eq)
2955 a (assoc name org-table-named-field-locations))
2956 (setq name1 name)
2957 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
2958 (nth 2 a))))
2959 (when (member name1 seen-fields)
2960 (error "Several field/range formulas try to set %s" name1))
2961 (push name1 seen-fields)
2963 (and (not a)
2964 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2965 (setq a (list name
2966 (condition-case nil
2967 (aref org-table-dlines
2968 (string-to-number (match-string 1 name)))
2969 (error (error "Invalid row number in %s"
2970 name)))
2971 (string-to-number (match-string 2 name)))))
2972 (when (and a (or all (equal (nth 1 a) thisline)))
2973 (message "Re-applying formula to field: %s" name)
2974 (org-goto-line (nth 1 a))
2975 (org-table-goto-column (nth 2 a))
2976 (push (append a (list (cdr eq))) eqlname1)
2977 (org-table-put-field-property :org-untouchable t)))
2978 (setq eqlname1 (nreverse eqlname1))
2980 ;; Now evaluate the column formulas, but skip fields covered by
2981 ;; field formulas
2982 (goto-char beg)
2983 (while (re-search-forward line-re end t)
2984 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2985 ;; Unprotected line, recalculate
2986 (and all (message "Re-applying formulas to full table...(line %d)"
2987 (setq cnt (1+ cnt))))
2988 (setq org-last-recalc-line (org-current-line))
2989 (setq eql eqlnum)
2990 (while (setq entry (pop eql))
2991 (org-goto-line org-last-recalc-line)
2992 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2993 (unless (get-text-property (point) :org-untouchable)
2994 (org-table-eval-formula nil (cdr entry)
2995 'noalign 'nocst 'nostore 'noanalysis)))))
2997 ;; Now evaluate the field formulas
2998 (while (setq eq (pop eqlname1))
2999 (message "Re-applying formula to field: %s" (car eq))
3000 (org-goto-line (nth 1 eq))
3001 (org-table-goto-column (nth 2 eq))
3002 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
3003 'nostore 'noanalysis))
3005 (org-goto-line thisline)
3006 (org-table-goto-column thiscol)
3007 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3008 (or noalign (and org-table-may-need-update (org-table-align))
3009 (and all (message "Re-applying formulas to %d lines...done" cnt)))
3011 ;; back to initial position
3012 (message "Re-applying formulas...done")
3013 (org-goto-line thisline)
3014 (org-table-goto-column thiscol)
3015 (or noalign (and org-table-may-need-update (org-table-align))
3016 (and all (message "Re-applying formulas...done"))))))
3018 ;;;###autoload
3019 (defun org-table-iterate (&optional arg)
3020 "Recalculate the table until it does not change anymore.
3021 The maximum number of iterations is 10, but you can choose a different value
3022 with the prefix ARG."
3023 (interactive "P")
3024 (let ((imax (if arg (prefix-numeric-value arg) 10))
3025 (i 0)
3026 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3027 thistbl)
3028 (catch 'exit
3029 (while (< i imax)
3030 (setq i (1+ i))
3031 (org-table-recalculate 'all)
3032 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3033 (if (not (string= lasttbl thistbl))
3034 (setq lasttbl thistbl)
3035 (if (> i 1)
3036 (message "Convergence after %d iterations" i)
3037 (message "Table was already stable"))
3038 (throw 'exit t)))
3039 (error "No convergence after %d iterations" i))))
3041 ;;;###autoload
3042 (defun org-table-recalculate-buffer-tables ()
3043 "Recalculate all tables in the current buffer."
3044 (interactive)
3045 (save-excursion
3046 (save-restriction
3047 (widen)
3048 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3050 ;;;###autoload
3051 (defun org-table-iterate-buffer-tables ()
3052 "Iterate all tables in the buffer, to converge inter-table dependencies."
3053 (interactive)
3054 (let* ((imax 10)
3055 (i imax)
3056 (checksum (md5 (buffer-string)))
3058 (save-excursion
3059 (save-restriction
3060 (widen)
3061 (catch 'exit
3062 (while (> i 0)
3063 (setq i (1- i))
3064 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3065 (if (equal checksum (setq c1 (md5 (buffer-string))))
3066 (progn
3067 (message "Convergence after %d iterations" (- imax i))
3068 (throw 'exit t))
3069 (setq checksum c1)))
3070 (error "No convergence after %d iterations" imax))))))
3072 (defun org-table-expand-lhs-ranges (equations)
3073 "Expand list of formulas.
3074 If some of the RHS in the formulas are ranges or a row reference, expand
3075 them to individual field equations for each field."
3076 (let (e res lhs rhs range r1 r2 c1 c2)
3077 (while (setq e (pop equations))
3078 (setq lhs (car e) rhs (cdr e))
3079 (cond
3080 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3081 ;; This just refers to one fixed field
3082 (push e res))
3083 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3084 ;; This just refers to one fixed named field
3085 (push e res))
3086 ((string-match "^@[0-9]+$" lhs)
3087 (loop for ic from 1 to org-table-current-ncol do
3088 (push (cons (format "%s$%d" lhs ic) rhs) res)
3089 (put-text-property 0 (length (caar res))
3090 :orig-eqn e (caar res))))
3092 (setq range (org-table-get-range lhs org-table-current-begin-pos
3093 1 nil 'corners))
3094 (setq r1 (nth 0 range) c1 (nth 1 range)
3095 r2 (nth 2 range) c2 (nth 3 range))
3096 (setq r1 (org-table-line-to-dline r1))
3097 (setq r2 (org-table-line-to-dline r2 'above))
3098 (loop for ir from r1 to r2 do
3099 (loop for ic from c1 to c2 do
3100 (push (cons (format "@%d$%d" ir ic) rhs) res)
3101 (put-text-property 0 (length (caar res))
3102 :orig-eqn e (caar res)))))))
3103 (nreverse res)))
3105 (defun org-table-formula-handle-first/last-rc (s)
3106 "Replace @<, @>, $<, $> with first/last row/column of the table.
3107 So @< and $< will always be replaced with @1 and $1, respectively.
3108 The advantage of these special markers are that structure editing of
3109 the table will not change them, while @1 and $1 will be modified
3110 when a line/row is swapped out of that privileged position. So for
3111 formulas that use a range of rows or columns, it may often be better
3112 to anchor the formula with \"I\" row markers, or to offset from the
3113 borders of the table using the @< @> $< $> makers."
3114 (let (n nmax len char (start 0))
3115 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3116 s start)
3117 (if (match-end 3)
3118 (setq start (match-end 3))
3119 (setq nmax (if (equal (match-string 1 s) "@")
3120 (1- (length org-table-dlines))
3121 org-table-current-ncol)
3122 len (- (match-end 2) (match-beginning 2))
3123 char (string-to-char (match-string 2 s))
3124 n (if (= char ?<)
3126 (- nmax len -1)))
3127 (if (or (< n 1) (> n nmax))
3128 (error "Reference \"%s\" in expression \"%s\" points outside table"
3129 (match-string 0 s) s))
3130 (setq start (match-beginning 0))
3131 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3134 (defun org-table-formula-substitute-names (f)
3135 "Replace $const with values in string F."
3136 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3137 ;; First, check for column names
3138 (while (setq start (string-match org-table-column-name-regexp f start))
3139 (setq start (1+ start))
3140 (setq a (assoc (match-string 1 f) org-table-column-names))
3141 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3142 ;; Parameters and constants
3143 (setq start 0)
3144 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3145 (if (match-end 2)
3146 (setq start (match-end 2))
3147 (setq start (1+ start))
3148 (if (setq a (save-match-data
3149 (org-table-get-constant (match-string 1 f))))
3150 (setq f (replace-match
3151 (concat (if pp "(") a (if pp ")")) t t f)))))
3152 (if org-table-formula-debug
3153 (put-text-property 0 (length f) :orig-formula f1 f))
3156 (defun org-table-get-constant (const)
3157 "Find the value for a parameter or constant in a formula.
3158 Parameters get priority."
3159 (or (cdr (assoc const org-table-local-parameters))
3160 (cdr (assoc const org-table-formula-constants-local))
3161 (cdr (assoc const org-table-formula-constants))
3162 (and (fboundp 'constants-get) (constants-get const))
3163 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3164 (org-entry-get nil (substring const 5) 'inherit))
3165 "#UNDEFINED_NAME"))
3167 (defvar org-table-fedit-map
3168 (let ((map (make-sparse-keymap)))
3169 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3170 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3171 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3172 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3173 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3174 (org-defkey map "\C-c?" 'org-table-show-reference)
3175 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3176 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3177 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3178 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3179 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3180 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3181 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3182 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3183 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3184 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3185 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3186 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3187 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3188 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3189 map))
3191 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3192 '("Edit-Formulas"
3193 ["Finish and Install" org-table-fedit-finish t]
3194 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3195 ["Abort" org-table-fedit-abort t]
3196 "--"
3197 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3198 ["Complete Lisp Symbol" lisp-complete-symbol t]
3199 "--"
3200 "Shift Reference at Point"
3201 ["Up" org-table-fedit-ref-up t]
3202 ["Down" org-table-fedit-ref-down t]
3203 ["Left" org-table-fedit-ref-left t]
3204 ["Right" org-table-fedit-ref-right t]
3206 "Change Test Row for Column Formulas"
3207 ["Up" org-table-fedit-line-up t]
3208 ["Down" org-table-fedit-line-down t]
3209 "--"
3210 ["Scroll Table Window" org-table-fedit-scroll t]
3211 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3212 ["Show Table Grid" org-table-fedit-toggle-coordinates
3213 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3214 org-table-overlay-coordinates)]
3215 "--"
3216 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3217 :style toggle :selected org-table-buffer-is-an]))
3219 (defvar org-pos)
3221 ;;;###autoload
3222 (defun org-table-edit-formulas ()
3223 "Edit the formulas of the current table in a separate buffer."
3224 (interactive)
3225 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3226 (beginning-of-line 0))
3227 (unless (org-at-table-p) (error "Not at a table"))
3228 (org-table-get-specials)
3229 (let ((key (org-table-current-field-formula 'key 'noerror))
3230 (eql (sort (org-table-get-stored-formulas 'noerror)
3231 'org-table-formula-less-p))
3232 (pos (point-marker))
3233 (startline 1)
3234 (wc (current-window-configuration))
3235 (sel-win (selected-window))
3236 (titles '((column . "# Column Formulas\n")
3237 (field . "# Field and Range Formulas\n")
3238 (named . "# Named Field Formulas\n")))
3239 entry s type title)
3240 (org-switch-to-buffer-other-window "*Edit Formulas*")
3241 (erase-buffer)
3242 ;; Keep global-font-lock-mode from turning on font-lock-mode
3243 (let ((font-lock-global-modes '(not fundamental-mode)))
3244 (fundamental-mode))
3245 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3246 (org-set-local 'org-pos pos)
3247 (org-set-local 'org-window-configuration wc)
3248 (org-set-local 'org-selected-window sel-win)
3249 (use-local-map org-table-fedit-map)
3250 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3251 (easy-menu-add org-table-fedit-menu)
3252 (setq startline (org-current-line))
3253 (while (setq entry (pop eql))
3254 (setq type (cond
3255 ((string-match "\\`$[<>]" (car entry)) 'column)
3256 ((equal (string-to-char (car entry)) ?@) 'field)
3257 ((string-match "^[0-9]" (car entry)) 'column)
3258 (t 'named)))
3259 (when (setq title (assq type titles))
3260 (or (bobp) (insert "\n"))
3261 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3262 (setq titles (remove title titles)))
3263 (if (equal key (car entry)) (setq startline (org-current-line)))
3264 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3265 (car entry) " = " (cdr entry) "\n"))
3266 (remove-text-properties 0 (length s) '(face nil) s)
3267 (insert s))
3268 (if (eq org-table-use-standard-references t)
3269 (org-table-fedit-toggle-ref-type))
3270 (org-goto-line startline)
3271 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3273 (defun org-table-fedit-post-command ()
3274 (when (not (memq this-command '(lisp-complete-symbol)))
3275 (let ((win (selected-window)))
3276 (save-excursion
3277 (condition-case nil
3278 (org-table-show-reference)
3279 (error nil))
3280 (select-window win)))))
3282 (defun org-table-formula-to-user (s)
3283 "Convert a formula from internal to user representation."
3284 (if (eq org-table-use-standard-references t)
3285 (org-table-convert-refs-to-an s)
3288 (defun org-table-formula-from-user (s)
3289 "Convert a formula from user to internal representation."
3290 (if org-table-use-standard-references
3291 (org-table-convert-refs-to-rc s)
3294 (defun org-table-convert-refs-to-rc (s)
3295 "Convert spreadsheet references from A7 to @7$28.
3296 Works for single references, but also for entire formulas and even the
3297 full TBLFM line."
3298 (let ((start 0))
3299 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3300 (cond
3301 ((match-end 3)
3302 ;; format match, just advance
3303 (setq start (match-end 0)))
3304 ((and (> (match-beginning 0) 0)
3305 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3306 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3307 ;; 3.e5 or something like this.
3308 (setq start (match-end 0)))
3309 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3310 ;; (member (match-string 1 s)
3311 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3313 ;; function name, just advance
3314 (setq start (match-end 0)))
3316 (setq start (match-beginning 0)
3317 s (replace-match
3318 (if (equal (match-string 2 s) "&")
3319 (format "$%d" (org-letters-to-number (match-string 1 s)))
3320 (format "@%d$%d"
3321 (string-to-number (match-string 2 s))
3322 (org-letters-to-number (match-string 1 s))))
3323 t t s)))))
3326 (defun org-table-convert-refs-to-an (s)
3327 "Convert spreadsheet references from to @7$28 to AB7.
3328 Works for single references, but also for entire formulas and even the
3329 full TBLFM line."
3330 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3331 (setq s (replace-match
3332 (format "%s%d"
3333 (org-number-to-letters
3334 (string-to-number (match-string 2 s)))
3335 (string-to-number (match-string 1 s)))
3336 t t s)))
3337 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3338 (setq s (replace-match (concat "\\1"
3339 (org-number-to-letters
3340 (string-to-number (match-string 2 s))) "&")
3341 t nil s)))
3344 (defun org-letters-to-number (s)
3345 "Convert a base 26 number represented by letters into an integer.
3346 For example: AB -> 28."
3347 (let ((n 0))
3348 (setq s (upcase s))
3349 (while (> (length s) 0)
3350 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3351 s (substring s 1)))
3354 (defun org-number-to-letters (n)
3355 "Convert an integer into a base 26 number represented by letters.
3356 For example: 28 -> AB."
3357 (let ((s ""))
3358 (while (> n 0)
3359 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3360 n (/ (1- n) 26)))
3363 (defun org-table-time-string-to-seconds (s)
3364 "Convert a time string into numerical duration in seconds.
3365 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3366 If S is a string representing a number, keep this number."
3367 (if (equal s "")
3369 (let (hour minus min sec res)
3370 (cond
3371 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3372 (setq minus (< 0 (length (match-string 1 s)))
3373 hour (string-to-number (match-string 2 s))
3374 min (string-to-number (match-string 3 s))
3375 sec (string-to-number (match-string 4 s)))
3376 (if minus
3377 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3378 (setq res (+ (* hour 3600) (* min 60) sec))))
3379 ((and (not (string-match org-ts-regexp-both s))
3380 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3381 (setq minus (< 0 (length (match-string 1 s)))
3382 hour (string-to-number (match-string 2 s))
3383 min (string-to-number (match-string 3 s)))
3384 (if minus
3385 (setq res (- (+ (* hour 3600) (* min 60))))
3386 (setq res (+ (* hour 3600) (* min 60)))))
3387 (t (setq res (string-to-number s))))
3388 (number-to-string res))))
3390 (defun org-table-time-seconds-to-string (secs &optional output-format)
3391 "Convert a number of seconds to a time string.
3392 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3393 minutes or seconds."
3394 (let* ((secs0 (abs secs))
3395 (res
3396 (cond ((eq output-format 'days)
3397 (format "%.3f" (/ (float secs0) 86400)))
3398 ((eq output-format 'hours)
3399 (format "%.2f" (/ (float secs0) 3600)))
3400 ((eq output-format 'minutes)
3401 (format "%.1f" (/ (float secs0) 60)))
3402 ((eq output-format 'seconds)
3403 (format "%d" secs0))
3404 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3405 (if (< secs 0) (concat "-" res) res)))
3407 (defun org-table-fedit-convert-buffer (function)
3408 "Convert all references in this buffer, using FUNCTION."
3409 (let ((line (org-current-line)))
3410 (goto-char (point-min))
3411 (while (not (eobp))
3412 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3413 (delete-region (point) (point-at-eol))
3414 (or (eobp) (forward-char 1)))
3415 (org-goto-line line)))
3417 (defun org-table-fedit-toggle-ref-type ()
3418 "Convert all references in the buffer from B3 to @3$2 and back."
3419 (interactive)
3420 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3421 (org-table-fedit-convert-buffer
3422 (if org-table-buffer-is-an
3423 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3424 (message "Reference type switched to %s"
3425 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3427 (defun org-table-fedit-ref-up ()
3428 "Shift the reference at point one row/hline up."
3429 (interactive)
3430 (org-table-fedit-shift-reference 'up))
3431 (defun org-table-fedit-ref-down ()
3432 "Shift the reference at point one row/hline down."
3433 (interactive)
3434 (org-table-fedit-shift-reference 'down))
3435 (defun org-table-fedit-ref-left ()
3436 "Shift the reference at point one field to the left."
3437 (interactive)
3438 (org-table-fedit-shift-reference 'left))
3439 (defun org-table-fedit-ref-right ()
3440 "Shift the reference at point one field to the right."
3441 (interactive)
3442 (org-table-fedit-shift-reference 'right))
3444 (defun org-table-fedit-shift-reference (dir)
3445 (cond
3446 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3447 (if (memq dir '(left right))
3448 (org-rematch-and-replace 1 (eq dir 'left))
3449 (error "Cannot shift reference in this direction")))
3450 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3451 ;; A B3-like reference
3452 (if (memq dir '(up down))
3453 (org-rematch-and-replace 2 (eq dir 'up))
3454 (org-rematch-and-replace 1 (eq dir 'left))))
3455 ((org-at-regexp-p
3456 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3457 ;; An internal reference
3458 (if (memq dir '(up down))
3459 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3460 (org-rematch-and-replace 5 (eq dir 'left))))))
3462 (defun org-rematch-and-replace (n &optional decr hline)
3463 "Re-match the group N, and replace it with the shifted reference."
3464 (or (match-end n) (error "Cannot shift reference in this direction"))
3465 (goto-char (match-beginning n))
3466 (and (looking-at (regexp-quote (match-string n)))
3467 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3468 t t)))
3470 (defun org-table-shift-refpart (ref &optional decr hline)
3471 "Shift a reference part REF.
3472 If DECR is set, decrease the references row/column, else increase.
3473 If HLINE is set, this may be a hline reference, it certainly is not
3474 a translation reference."
3475 (save-match-data
3476 (let* ((sign (string-match "^[-+]" ref)) n)
3478 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3479 (cond
3480 ((and hline (string-match "^I+" ref))
3481 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3482 (setq n (+ n (if decr -1 1)))
3483 (if (= n 0) (setq n (+ n (if decr -1 1))))
3484 (if sign
3485 (setq sign (if (< n 0) "-" "+") n (abs n))
3486 (setq n (max 1 n)))
3487 (concat sign (make-string n ?I)))
3489 ((string-match "^[0-9]+" ref)
3490 (setq n (string-to-number (concat sign ref)))
3491 (setq n (+ n (if decr -1 1)))
3492 (if sign
3493 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3494 (number-to-string (max 1 n))))
3496 ((string-match "^[a-zA-Z]+" ref)
3497 (org-number-to-letters
3498 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3500 (t (error "Cannot shift reference"))))))
3502 (defun org-table-fedit-toggle-coordinates ()
3503 "Toggle the display of coordinates in the referenced table."
3504 (interactive)
3505 (let ((pos (marker-position org-pos)))
3506 (with-current-buffer (marker-buffer org-pos)
3507 (save-excursion
3508 (goto-char pos)
3509 (org-table-toggle-coordinate-overlays)))))
3511 (defun org-table-fedit-finish (&optional arg)
3512 "Parse the buffer for formula definitions and install them.
3513 With prefix ARG, apply the new formulas to the table."
3514 (interactive "P")
3515 (org-table-remove-rectangle-highlight)
3516 (if org-table-use-standard-references
3517 (progn
3518 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3519 (setq org-table-buffer-is-an nil)))
3520 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3521 (goto-char (point-min))
3522 (while (re-search-forward
3523 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3524 nil t)
3525 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3526 form (match-string 3))
3527 (setq form (org-trim form))
3528 (when (not (equal form ""))
3529 (while (string-match "[ \t]*\n[ \t]*" form)
3530 (setq form (replace-match " " t t form)))
3531 (when (assoc var eql)
3532 (error "Double formulas for %s" var))
3533 (push (cons var form) eql)))
3534 (setq org-pos nil)
3535 (set-window-configuration org-window-configuration)
3536 (select-window sel-win)
3537 (goto-char pos)
3538 (unless (org-at-table-p)
3539 (error "Lost table position - cannot install formulas"))
3540 (org-table-store-formulas eql)
3541 (move-marker pos nil)
3542 (kill-buffer "*Edit Formulas*")
3543 (if arg
3544 (org-table-recalculate 'all)
3545 (message "New formulas installed - press C-u C-c C-c to apply."))))
3547 (defun org-table-fedit-abort ()
3548 "Abort editing formulas, without installing the changes."
3549 (interactive)
3550 (org-table-remove-rectangle-highlight)
3551 (let ((pos org-pos) (sel-win org-selected-window))
3552 (set-window-configuration org-window-configuration)
3553 (select-window sel-win)
3554 (goto-char pos)
3555 (move-marker pos nil)
3556 (message "Formula editing aborted without installing changes")))
3558 (defun org-table-fedit-lisp-indent ()
3559 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3560 (interactive)
3561 (let ((pos (point)) beg end ind)
3562 (beginning-of-line 1)
3563 (cond
3564 ((looking-at "[ \t]")
3565 (goto-char pos)
3566 (call-interactively 'lisp-indent-line))
3567 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3568 ((not (fboundp 'pp-buffer))
3569 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3570 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3571 (goto-char (- (match-end 0) 2))
3572 (setq beg (point))
3573 (setq ind (make-string (current-column) ?\ ))
3574 (condition-case nil (forward-sexp 1)
3575 (error
3576 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3577 (setq end (point))
3578 (save-restriction
3579 (narrow-to-region beg end)
3580 (if (eq last-command this-command)
3581 (progn
3582 (goto-char (point-min))
3583 (setq this-command nil)
3584 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3585 (replace-match " ")))
3586 (pp-buffer)
3587 (untabify (point-min) (point-max))
3588 (goto-char (1+ (point-min)))
3589 (while (re-search-forward "^." nil t)
3590 (beginning-of-line 1)
3591 (insert ind))
3592 (goto-char (point-max))
3593 (org-delete-backward-char 1)))
3594 (goto-char beg))
3595 (t nil))))
3597 (defvar org-show-positions nil)
3599 (defun org-table-show-reference (&optional local)
3600 "Show the location/value of the $ expression at point."
3601 (interactive)
3602 (org-table-remove-rectangle-highlight)
3603 (catch 'exit
3604 (let ((pos (if local (point) org-pos))
3605 (face2 'highlight)
3606 (org-inhibit-highlight-removal t)
3607 (win (selected-window))
3608 (org-show-positions nil)
3609 var name e what match dest)
3610 (if local (org-table-get-specials))
3611 (setq what (cond
3612 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3613 (setq match (concat (substring (match-string 0) 0 -1)
3614 "$1.."
3615 (substring (match-string 0) 0 -1)
3616 "$100"))
3617 'range)
3618 ((or (org-at-regexp-p org-table-range-regexp2)
3619 (org-at-regexp-p org-table-translate-regexp)
3620 (org-at-regexp-p org-table-range-regexp))
3621 (setq match
3622 (save-match-data
3623 (org-table-convert-refs-to-rc (match-string 0))))
3624 'range)
3625 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3626 ((org-at-regexp-p "\\$[0-9]+") 'column)
3627 ((not local) nil)
3628 (t (error "No reference at point")))
3629 match (and what (or match (match-string 0))))
3630 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3631 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3632 'secondary-selection))
3633 (org-add-hook 'before-change-functions
3634 'org-table-remove-rectangle-highlight)
3635 (if (eq what 'name) (setq var (substring match 1)))
3636 (when (eq what 'range)
3637 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3638 (setq match (org-table-formula-substitute-names match)))
3639 (unless local
3640 (save-excursion
3641 (end-of-line 1)
3642 (re-search-backward "^\\S-" nil t)
3643 (beginning-of-line 1)
3644 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3645 (setq dest
3646 (save-match-data
3647 (org-table-convert-refs-to-rc (match-string 1))))
3648 (org-table-add-rectangle-overlay
3649 (match-beginning 1) (match-end 1) face2))))
3650 (if (and (markerp pos) (marker-buffer pos))
3651 (if (get-buffer-window (marker-buffer pos))
3652 (select-window (get-buffer-window (marker-buffer pos)))
3653 (org-switch-to-buffer-other-window (get-buffer-window
3654 (marker-buffer pos)))))
3655 (goto-char pos)
3656 (org-table-force-dataline)
3657 (when dest
3658 (setq name (substring dest 1))
3659 (cond
3660 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3661 (setq e (assoc name org-table-named-field-locations))
3662 (org-goto-line (nth 1 e))
3663 (org-table-goto-column (nth 2 e)))
3664 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3665 (let ((l (string-to-number (match-string 1 dest)))
3666 (c (string-to-number (match-string 2 dest))))
3667 (org-goto-line (aref org-table-dlines l))
3668 (org-table-goto-column c)))
3669 (t (org-table-goto-column (string-to-number name))))
3670 (move-marker pos (point))
3671 (org-table-highlight-rectangle nil nil face2))
3672 (cond
3673 ((equal dest match))
3674 ((not match))
3675 ((eq what 'range)
3676 (condition-case nil
3677 (save-excursion
3678 (org-table-get-range match nil nil 'highlight))
3679 (error nil)))
3680 ((setq e (assoc var org-table-named-field-locations))
3681 (org-goto-line (nth 1 e))
3682 (org-table-goto-column (nth 2 e))
3683 (org-table-highlight-rectangle (point) (point))
3684 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3685 ((setq e (assoc var org-table-column-names))
3686 (org-table-goto-column (string-to-number (cdr e)))
3687 (org-table-highlight-rectangle (point) (point))
3688 (goto-char (org-table-begin))
3689 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3690 (org-table-end) t)
3691 (progn
3692 (goto-char (match-beginning 1))
3693 (org-table-highlight-rectangle)
3694 (message "Named column (column %s)" (cdr e)))
3695 (error "Column name not found")))
3696 ((eq what 'column)
3697 ;; column number
3698 (org-table-goto-column (string-to-number (substring match 1)))
3699 (org-table-highlight-rectangle (point) (point))
3700 (message "Column %s" (substring match 1)))
3701 ((setq e (assoc var org-table-local-parameters))
3702 (goto-char (org-table-begin))
3703 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3704 (progn
3705 (goto-char (match-beginning 1))
3706 (org-table-highlight-rectangle)
3707 (message "Local parameter."))
3708 (error "Parameter not found")))
3710 (cond
3711 ((not var) (error "No reference at point"))
3712 ((setq e (assoc var org-table-formula-constants-local))
3713 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3714 var (cdr e)))
3715 ((setq e (assoc var org-table-formula-constants))
3716 (message "Constant: $%s=%s in `org-table-formula-constants'."
3717 var (cdr e)))
3718 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3719 (message "Constant: $%s=%s, from `constants.el'%s."
3720 var e (format " (%s units)" constants-unit-system)))
3721 (t (error "Undefined name $%s" var)))))
3722 (goto-char pos)
3723 (when (and org-show-positions
3724 (not (memq this-command '(org-table-fedit-scroll
3725 org-table-fedit-scroll-down))))
3726 (push pos org-show-positions)
3727 (push org-table-current-begin-pos org-show-positions)
3728 (let ((min (apply 'min org-show-positions))
3729 (max (apply 'max org-show-positions)))
3730 (goto-char min) (recenter 0)
3731 (goto-char max)
3732 (or (pos-visible-in-window-p max) (recenter -1))))
3733 (select-window win))))
3735 (defun org-table-force-dataline ()
3736 "Make sure the cursor is in a dataline in a table."
3737 (unless (save-excursion
3738 (beginning-of-line 1)
3739 (looking-at org-table-dataline-regexp))
3740 (let* ((re org-table-dataline-regexp)
3741 (p1 (save-excursion (re-search-forward re nil 'move)))
3742 (p2 (save-excursion (re-search-backward re nil 'move))))
3743 (cond ((and p1 p2)
3744 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3745 p1 p2)))
3746 ((or p1 p2) (goto-char (or p1 p2)))
3747 (t (error "No table dataline around here"))))))
3749 (defun org-table-fedit-line-up ()
3750 "Move cursor one line up in the window showing the table."
3751 (interactive)
3752 (org-table-fedit-move 'previous-line))
3754 (defun org-table-fedit-line-down ()
3755 "Move cursor one line down in the window showing the table."
3756 (interactive)
3757 (org-table-fedit-move 'next-line))
3759 (defun org-table-fedit-move (command)
3760 "Move the cursor in the window showing the table.
3761 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3762 (let ((org-table-allow-automatic-line-recalculation nil)
3763 (pos org-pos) (win (selected-window)) p)
3764 (select-window (get-buffer-window (marker-buffer org-pos)))
3765 (setq p (point))
3766 (call-interactively command)
3767 (while (and (org-at-table-p)
3768 (org-at-table-hline-p))
3769 (call-interactively command))
3770 (or (org-at-table-p) (goto-char p))
3771 (move-marker pos (point))
3772 (select-window win)))
3774 (defun org-table-fedit-scroll (N)
3775 (interactive "p")
3776 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3777 (scroll-other-window N)))
3779 (defun org-table-fedit-scroll-down (N)
3780 (interactive "p")
3781 (org-table-fedit-scroll (- N)))
3783 (defvar org-table-rectangle-overlays nil)
3785 (defun org-table-add-rectangle-overlay (beg end &optional face)
3786 "Add a new overlay."
3787 (let ((ov (make-overlay beg end)))
3788 (overlay-put ov 'face (or face 'secondary-selection))
3789 (push ov org-table-rectangle-overlays)))
3791 (defun org-table-highlight-rectangle (&optional beg end face)
3792 "Highlight rectangular region in a table."
3793 (setq beg (or beg (point)) end (or end (point)))
3794 (let ((b (min beg end))
3795 (e (max beg end))
3796 l1 c1 l2 c2 tmp)
3797 (and (boundp 'org-show-positions)
3798 (setq org-show-positions (cons b (cons e org-show-positions))))
3799 (goto-char (min beg end))
3800 (setq l1 (org-current-line)
3801 c1 (org-table-current-column))
3802 (goto-char (max beg end))
3803 (setq l2 (org-current-line)
3804 c2 (org-table-current-column))
3805 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3806 (org-goto-line l1)
3807 (beginning-of-line 1)
3808 (loop for line from l1 to l2 do
3809 (when (looking-at org-table-dataline-regexp)
3810 (org-table-goto-column c1)
3811 (skip-chars-backward "^|\n") (setq beg (point))
3812 (org-table-goto-column c2)
3813 (skip-chars-forward "^|\n") (setq end (point))
3814 (org-table-add-rectangle-overlay beg end face))
3815 (beginning-of-line 2))
3816 (goto-char b))
3817 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3819 (defun org-table-remove-rectangle-highlight (&rest ignore)
3820 "Remove the rectangle overlays."
3821 (unless org-inhibit-highlight-removal
3822 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3823 (mapc 'delete-overlay org-table-rectangle-overlays)
3824 (setq org-table-rectangle-overlays nil)))
3826 (defvar org-table-coordinate-overlays nil
3827 "Collects the coordinate grid overlays, so that they can be removed.")
3828 (make-variable-buffer-local 'org-table-coordinate-overlays)
3830 (defun org-table-overlay-coordinates ()
3831 "Add overlays to the table at point, to show row/column coordinates."
3832 (interactive)
3833 (mapc 'delete-overlay org-table-coordinate-overlays)
3834 (setq org-table-coordinate-overlays nil)
3835 (save-excursion
3836 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3837 (goto-char (org-table-begin))
3838 (while (org-at-table-p)
3839 (setq eol (point-at-eol))
3840 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3841 (push ov org-table-coordinate-overlays)
3842 (setq hline (looking-at org-table-hline-regexp))
3843 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3844 (format "%4d" (setq id (1+ id)))))
3845 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3846 (when hline
3847 (setq ic 0)
3848 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3849 (setq beg (1+ (match-beginning 0))
3850 ic (1+ ic)
3851 s1 (concat "$" (int-to-string ic))
3852 s2 (org-number-to-letters ic)
3853 str (if (eq org-table-use-standard-references t) s2 s1))
3854 (setq ov (make-overlay beg (+ beg (length str))))
3855 (push ov org-table-coordinate-overlays)
3856 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3857 (beginning-of-line 2)))))
3859 ;;;###autoload
3860 (defun org-table-toggle-coordinate-overlays ()
3861 "Toggle the display of Row/Column numbers in tables."
3862 (interactive)
3863 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3864 (message "Tables Row/Column numbers display turned %s"
3865 (if org-table-overlay-coordinates "on" "off"))
3866 (if (and (org-at-table-p) org-table-overlay-coordinates)
3867 (org-table-align))
3868 (unless org-table-overlay-coordinates
3869 (mapc 'delete-overlay org-table-coordinate-overlays)
3870 (setq org-table-coordinate-overlays nil)))
3872 ;;;###autoload
3873 (defun org-table-toggle-formula-debugger ()
3874 "Toggle the formula debugger in tables."
3875 (interactive)
3876 (setq org-table-formula-debug (not org-table-formula-debug))
3877 (message "Formula debugging has been turned %s"
3878 (if org-table-formula-debug "on" "off")))
3880 ;;; The orgtbl minor mode
3882 ;; Define a minor mode which can be used in other modes in order to
3883 ;; integrate the org-mode table editor.
3885 ;; This is really a hack, because the org-mode table editor uses several
3886 ;; keys which normally belong to the major mode, for example the TAB and
3887 ;; RET keys. Here is how it works: The minor mode defines all the keys
3888 ;; necessary to operate the table editor, but wraps the commands into a
3889 ;; function which tests if the cursor is currently inside a table. If that
3890 ;; is the case, the table editor command is executed. However, when any of
3891 ;; those keys is used outside a table, the function uses `key-binding' to
3892 ;; look up if the key has an associated command in another currently active
3893 ;; keymap (minor modes, major mode, global), and executes that command.
3894 ;; There might be problems if any of the keys used by the table editor is
3895 ;; otherwise used as a prefix key.
3897 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3898 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3899 ;; addresses this by checking explicitly for both bindings.
3901 ;; The optimized version (see variable `orgtbl-optimized') takes over
3902 ;; all keys which are bound to `self-insert-command' in the *global map*.
3903 ;; Some modes bind other commands to simple characters, for example
3904 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3905 ;; active, this binding is ignored inside tables and replaced with a
3906 ;; modified self-insert.
3909 (defvar orgtbl-mode-map (make-keymap)
3910 "Keymap for `orgtbl-mode'.")
3912 (defvar org-old-auto-fill-inhibit-regexp nil
3913 "Local variable used by `orgtbl-mode'.")
3915 (defconst orgtbl-line-start-regexp
3916 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
3917 "Matches a line belonging to an orgtbl.")
3919 (defconst orgtbl-extra-font-lock-keywords
3920 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3921 0 (quote 'org-table) 'prepend))
3922 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3924 ;; Install it as a minor mode.
3925 (put 'orgtbl-mode :included t)
3926 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3928 ;;;###autoload
3929 (define-minor-mode orgtbl-mode
3930 "The `org-mode' table editor as a minor mode for use in other modes."
3931 :lighter " OrgTbl" :keymap orgtbl-mode-map
3932 (org-load-modules-maybe)
3933 (cond
3934 ((derived-mode-p 'org-mode)
3935 ;; Exit without error, in case some hook functions calls this
3936 ;; by accident in org-mode.
3937 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3938 (orgtbl-mode
3939 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3940 ;; Make sure we are first in minor-mode-map-alist
3941 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3942 ;; FIXME: maybe it should use emulation-mode-map-alists?
3943 (and c (setq minor-mode-map-alist
3944 (cons c (delq c minor-mode-map-alist)))))
3945 (org-set-local (quote org-table-may-need-update) t)
3946 (org-add-hook 'before-change-functions 'org-before-change-function
3947 nil 'local)
3948 (org-set-local 'org-old-auto-fill-inhibit-regexp
3949 auto-fill-inhibit-regexp)
3950 (org-set-local 'auto-fill-inhibit-regexp
3951 (if auto-fill-inhibit-regexp
3952 (concat orgtbl-line-start-regexp "\\|"
3953 auto-fill-inhibit-regexp)
3954 orgtbl-line-start-regexp))
3955 (add-to-invisibility-spec '(org-cwidth))
3956 (when (fboundp 'font-lock-add-keywords)
3957 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3958 (org-restart-font-lock))
3959 (easy-menu-add orgtbl-mode-menu))
3961 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3962 (org-table-cleanup-narrow-column-properties)
3963 (org-remove-from-invisibility-spec '(org-cwidth))
3964 (remove-hook 'before-change-functions 'org-before-change-function t)
3965 (when (fboundp 'font-lock-remove-keywords)
3966 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3967 (org-restart-font-lock))
3968 (easy-menu-remove orgtbl-mode-menu)
3969 (force-mode-line-update 'all))))
3971 (defun org-table-cleanup-narrow-column-properties ()
3972 "Remove all properties related to narrow-column invisibility."
3973 (let ((s (point-min)))
3974 (while (setq s (text-property-any s (point-max)
3975 'display org-narrow-column-arrow))
3976 (remove-text-properties s (1+ s) '(display t)))
3977 (setq s (point-min))
3978 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3979 (remove-text-properties s (1+ s) '(org-cwidth t)))
3980 (setq s (point-min))
3981 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3982 (remove-text-properties s (1+ s) '(invisible t)))))
3984 (defun orgtbl-make-binding (fun n &rest keys)
3985 "Create a function for binding in the table minor mode.
3986 FUN is the command to call inside a table. N is used to create a unique
3987 command name. KEYS are keys that should be checked in for a command
3988 to execute outside of tables."
3989 (eval
3990 (list 'defun
3991 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3992 '(arg)
3993 (concat "In tables, run `" (symbol-name fun) "'.\n"
3994 "Outside of tables, run the binding of `"
3995 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3996 "'.")
3997 '(interactive "p")
3998 (list 'if
3999 '(org-at-table-p)
4000 (list 'call-interactively (list 'quote fun))
4001 (list 'let '(orgtbl-mode)
4002 (list 'call-interactively
4003 (append '(or)
4004 (mapcar (lambda (k)
4005 (list 'key-binding k))
4006 keys)
4007 '('orgtbl-error))))))))
4009 (defun orgtbl-error ()
4010 "Error when there is no default binding for a table key."
4011 (interactive)
4012 (error "This key has no function outside tables"))
4014 (defun orgtbl-setup ()
4015 "Setup orgtbl keymaps."
4016 (let ((nfunc 0)
4017 (bindings
4018 '(([(meta shift left)] org-table-delete-column)
4019 ([(meta left)] org-table-move-column-left)
4020 ([(meta right)] org-table-move-column-right)
4021 ([(meta shift right)] org-table-insert-column)
4022 ([(meta shift up)] org-table-kill-row)
4023 ([(meta shift down)] org-table-insert-row)
4024 ([(meta up)] org-table-move-row-up)
4025 ([(meta down)] org-table-move-row-down)
4026 ("\C-c\C-w" org-table-cut-region)
4027 ("\C-c\M-w" org-table-copy-region)
4028 ("\C-c\C-y" org-table-paste-rectangle)
4029 ("\C-c\C-w" org-table-wrap-region)
4030 ("\C-c-" org-table-insert-hline)
4031 ("\C-c}" org-table-toggle-coordinate-overlays)
4032 ("\C-c{" org-table-toggle-formula-debugger)
4033 ("\C-m" org-table-next-row)
4034 ([(shift return)] org-table-copy-down)
4035 ("\C-c?" org-table-field-info)
4036 ("\C-c " org-table-blank-field)
4037 ("\C-c+" org-table-sum)
4038 ("\C-c=" org-table-eval-formula)
4039 ("\C-c'" org-table-edit-formulas)
4040 ("\C-c`" org-table-edit-field)
4041 ("\C-c*" org-table-recalculate)
4042 ("\C-c^" org-table-sort-lines)
4043 ("\M-a" org-table-beginning-of-field)
4044 ("\M-e" org-table-end-of-field)
4045 ([(control ?#)] org-table-rotate-recalc-marks)))
4046 elt key fun cmd)
4047 (while (setq elt (pop bindings))
4048 (setq nfunc (1+ nfunc))
4049 (setq key (org-key (car elt))
4050 fun (nth 1 elt)
4051 cmd (orgtbl-make-binding fun nfunc key))
4052 (org-defkey orgtbl-mode-map key cmd))
4054 ;; Special treatment needed for TAB and RET
4055 (org-defkey orgtbl-mode-map [(return)]
4056 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4057 (org-defkey orgtbl-mode-map "\C-m"
4058 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4060 (org-defkey orgtbl-mode-map [(tab)]
4061 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4062 (org-defkey orgtbl-mode-map "\C-i"
4063 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4065 (org-defkey orgtbl-mode-map [(shift tab)]
4066 (orgtbl-make-binding 'org-table-previous-field 104
4067 [(shift tab)] [(tab)] "\C-i"))
4070 (unless (featurep 'xemacs)
4071 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4072 (orgtbl-make-binding 'org-table-previous-field 107
4073 [S-iso-lefttab] [backtab] [(shift tab)]
4074 [(tab)] "\C-i")))
4076 (org-defkey orgtbl-mode-map [backtab]
4077 (orgtbl-make-binding 'org-table-previous-field 108
4078 [backtab] [S-iso-lefttab] [(shift tab)]
4079 [(tab)] "\C-i"))
4081 (org-defkey orgtbl-mode-map "\M-\C-m"
4082 (orgtbl-make-binding 'org-table-wrap-region 105
4083 "\M-\C-m" [(meta return)]))
4084 (org-defkey orgtbl-mode-map [(meta return)]
4085 (orgtbl-make-binding 'org-table-wrap-region 106
4086 [(meta return)] "\M-\C-m"))
4088 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4089 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4091 (when orgtbl-optimized
4092 ;; If the user wants maximum table support, we need to hijack
4093 ;; some standard editing functions
4094 (org-remap orgtbl-mode-map
4095 'self-insert-command 'orgtbl-self-insert-command
4096 'delete-char 'org-delete-char
4097 'delete-backward-char 'org-delete-backward-char)
4098 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4099 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4100 '("OrgTbl"
4101 ["Create or convert" org-table-create-or-convert-from-region
4102 :active (not (org-at-table-p)) :keys "C-c |" ]
4103 "--"
4104 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4105 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4106 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4107 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4108 "--"
4109 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4110 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4111 ["Copy Field from Above"
4112 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4113 "--"
4114 ("Column"
4115 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4116 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4117 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4118 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4119 ("Row"
4120 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4121 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4122 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4123 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4124 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4125 "--"
4126 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4127 ("Rectangle"
4128 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4129 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4130 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4131 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4132 "--"
4133 ("Radio tables"
4134 ["Insert table template" orgtbl-insert-radio-table
4135 (assq major-mode orgtbl-radio-table-templates)]
4136 ["Comment/uncomment table" orgtbl-toggle-comment t])
4137 "--"
4138 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4139 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4140 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4141 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4142 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4143 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4144 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4145 ["Sum Column/Rectangle" org-table-sum
4146 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4147 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4148 ["Debug Formulas"
4149 org-table-toggle-formula-debugger :active (org-at-table-p)
4150 :keys "C-c {"
4151 :style toggle :selected org-table-formula-debug]
4152 ["Show Col/Row Numbers"
4153 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4154 :keys "C-c }"
4155 :style toggle :selected org-table-overlay-coordinates]
4159 (defun orgtbl-ctrl-c-ctrl-c (arg)
4160 "If the cursor is inside a table, realign the table.
4161 If it is a table to be sent away to a receiver, do it.
4162 With prefix arg, also recompute table."
4163 (interactive "P")
4164 (let ((case-fold-search t) (pos (point)) action consts-str consts cst const-str)
4165 (save-excursion
4166 (beginning-of-line 1)
4167 (setq action (cond
4168 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4169 ((looking-at "[ \t]*|") pos)
4170 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4171 (cond
4172 ((integerp action)
4173 (goto-char action)
4174 (org-table-maybe-eval-formula)
4175 (if arg
4176 (call-interactively 'org-table-recalculate)
4177 (org-table-maybe-recalculate-line))
4178 (call-interactively 'org-table-align)
4179 (when (orgtbl-send-table 'maybe)
4180 (run-hooks 'orgtbl-after-send-table-hook)))
4181 ((eq action 'recalc)
4182 (save-excursion
4183 (goto-char (point-min))
4184 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4185 (setq const-str (substring-no-properties (match-string 1)))
4186 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4187 (when consts
4188 (let (e)
4189 (while (setq e (pop consts))
4190 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4191 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4192 (setq org-table-formula-constants-local cst)))))
4193 (save-excursion
4194 (beginning-of-line 1)
4195 (skip-chars-backward " \r\n\t")
4196 (if (org-at-table-p)
4197 (org-call-with-arg 'org-table-recalculate t))))
4198 (t (let (orgtbl-mode)
4199 (call-interactively (key-binding "\C-c\C-c")))))))
4201 (defun orgtbl-create-or-convert-from-region (arg)
4202 "Create table or convert region to table, if no conflicting binding.
4203 This installs the table binding `C-c |', but only if there is no
4204 conflicting binding to this key outside orgtbl-mode."
4205 (interactive "P")
4206 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4207 (if cmd
4208 (call-interactively cmd)
4209 (call-interactively 'org-table-create-or-convert-from-region))))
4211 (defun orgtbl-tab (arg)
4212 "Justification and field motion for `orgtbl-mode'."
4213 (interactive "P")
4214 (if arg (org-table-edit-field t)
4215 (org-table-justify-field-maybe)
4216 (org-table-next-field)))
4218 (defun orgtbl-ret ()
4219 "Justification and field motion for `orgtbl-mode'."
4220 (interactive)
4221 (if (bobp)
4222 (newline)
4223 (org-table-justify-field-maybe)
4224 (org-table-next-row)))
4226 (defun orgtbl-self-insert-command (N)
4227 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4228 If the cursor is in a table looking at whitespace, the whitespace is
4229 overwritten, and the table is not marked as requiring realignment."
4230 (interactive "p")
4231 (if (and (org-at-table-p)
4233 (and org-table-auto-blank-field
4234 (member last-command
4235 '(orgtbl-hijacker-command-100
4236 orgtbl-hijacker-command-101
4237 orgtbl-hijacker-command-102
4238 orgtbl-hijacker-command-103
4239 orgtbl-hijacker-command-104
4240 orgtbl-hijacker-command-105
4241 yas/expand))
4242 (org-table-blank-field))
4244 (eq N 1)
4245 (looking-at "[^|\n]* +|"))
4246 (let (org-table-may-need-update)
4247 (goto-char (1- (match-end 0)))
4248 (org-delete-backward-char 1)
4249 (goto-char (match-beginning 0))
4250 (self-insert-command N))
4251 (setq org-table-may-need-update t)
4252 (let* (orgtbl-mode
4254 (cmd (or (key-binding
4255 (or (and (listp function-key-map)
4256 (setq a (assoc last-input-event function-key-map))
4257 (cdr a))
4258 (vector last-input-event)))
4259 'self-insert-command)))
4260 (call-interactively cmd)
4261 (if (and org-self-insert-cluster-for-undo
4262 (eq cmd 'self-insert-command))
4263 (if (not (eq last-command 'orgtbl-self-insert-command))
4264 (setq org-self-insert-command-undo-counter 1)
4265 (if (>= org-self-insert-command-undo-counter 20)
4266 (setq org-self-insert-command-undo-counter 1)
4267 (and (> org-self-insert-command-undo-counter 0)
4268 buffer-undo-list
4269 (not (cadr buffer-undo-list)) ; remove nil entry
4270 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4271 (setq org-self-insert-command-undo-counter
4272 (1+ org-self-insert-command-undo-counter))))))))
4274 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4275 "Regular expression matching exponentials as produced by calc.")
4277 (defun orgtbl-export (table target)
4278 (require 'org-exp)
4279 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4280 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4281 org-table-last-alignment org-table-last-column-widths
4282 maxcol column)
4283 (if (not (fboundp func))
4284 (error "Cannot export orgtbl table to %s" target))
4285 (setq lines (org-table-clean-before-export lines))
4286 (setq table
4287 (mapcar
4288 (lambda (x)
4289 (if (string-match org-table-hline-regexp x)
4290 'hline
4291 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4292 lines))
4293 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4294 table)))
4295 (loop for i from (1- maxcol) downto 0 do
4296 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4297 (setq column (delq nil column))
4298 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4299 (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))
4300 (funcall func table nil)))
4302 (defun orgtbl-gather-send-defs ()
4303 "Gather a plist of :name, :transform, :params for each destination before
4304 a radio table."
4305 (save-excursion
4306 (goto-char (org-table-begin))
4307 (let (rtn)
4308 (beginning-of-line 0)
4309 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4310 (let ((name (org-no-properties (match-string 1)))
4311 (transform (intern (match-string 2)))
4312 (params (if (match-end 3)
4313 (read (concat "(" (match-string 3) ")")))))
4314 (push (list :name name :transform transform :params params)
4315 rtn)
4316 (beginning-of-line 0)))
4317 rtn)))
4319 (defun orgtbl-send-replace-tbl (name txt)
4320 "Find and replace table NAME with TXT."
4321 (save-excursion
4322 (goto-char (point-min))
4323 (unless (re-search-forward
4324 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4325 (error "Don't know where to insert translated table"))
4326 (goto-char (match-beginning 0))
4327 (beginning-of-line 2)
4328 (save-excursion
4329 (let ((beg (point)))
4330 (unless (re-search-forward
4331 (concat "END RECEIVE ORGTBL +" name) nil t)
4332 (error "Cannot find end of insertion region"))
4333 (beginning-of-line 1)
4334 (delete-region beg (point))))
4335 (insert txt "\n")))
4337 ;;;###autoload
4338 (defun org-table-to-lisp (&optional txt)
4339 "Convert the table at point to a Lisp structure.
4340 The structure will be a list. Each item is either the symbol `hline'
4341 for a horizontal separator line, or a list of field values as strings.
4342 The table is taken from the parameter TXT, or from the buffer at point."
4343 (unless txt
4344 (unless (org-at-table-p)
4345 (error "No table at point")))
4346 (let* ((txt (or txt
4347 (buffer-substring-no-properties (org-table-begin)
4348 (org-table-end))))
4349 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4351 (mapcar
4352 (lambda (x)
4353 (if (string-match org-table-hline-regexp x)
4354 'hline
4355 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4356 lines)))
4358 (defun orgtbl-send-table (&optional maybe)
4359 "Send a transformed version of this table to the receiver position.
4360 With argument MAYBE, fail quietly if no transformation is defined for
4361 this table."
4362 (interactive)
4363 (catch 'exit
4364 (unless (org-at-table-p) (error "Not at a table"))
4365 ;; when non-interactive, we assume align has just happened.
4366 (when (org-called-interactively-p 'any) (org-table-align))
4367 (let ((dests (orgtbl-gather-send-defs))
4368 (txt (buffer-substring-no-properties (org-table-begin)
4369 (org-table-end)))
4370 (ntbl 0))
4371 (unless dests (if maybe (throw 'exit nil)
4372 (error "Don't know how to transform this table")))
4373 (dolist (dest dests)
4374 (let* ((name (plist-get dest :name))
4375 (transform (plist-get dest :transform))
4376 (params (plist-get dest :params))
4377 (skip (plist-get params :skip))
4378 (skipcols (plist-get params :skipcols))
4379 (no-escape (plist-get params :no-escape))
4381 (lines (org-table-clean-before-export
4382 (nthcdr (or skip 0)
4383 (org-split-string txt "[ \t]*\n[ \t]*"))))
4384 (i0 (if org-table-clean-did-remove-column 2 1))
4385 (lines (if no-escape lines
4386 (mapcar (lambda(l) (replace-regexp-in-string
4387 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4388 (table (mapcar
4389 (lambda (x)
4390 (if (string-match org-table-hline-regexp x)
4391 'hline
4392 (org-remove-by-index
4393 (org-split-string (org-trim x) "\\s-*|\\s-*")
4394 skipcols i0)))
4395 lines))
4396 (fun (if (= i0 2) 'cdr 'identity))
4397 (org-table-last-alignment
4398 (org-remove-by-index (funcall fun org-table-last-alignment)
4399 skipcols i0))
4400 (org-table-last-column-widths
4401 (org-remove-by-index (funcall fun org-table-last-column-widths)
4402 skipcols i0))
4403 (txt (if (fboundp transform)
4404 (funcall transform table params)
4405 (error "No such transformation function %s" transform))))
4406 (orgtbl-send-replace-tbl name txt))
4407 (setq ntbl (1+ ntbl)))
4408 (message "Table converted and installed at %d receiver location%s"
4409 ntbl (if (> ntbl 1) "s" ""))
4410 (if (> ntbl 0)
4411 ntbl
4412 nil))))
4414 (defun org-remove-by-index (list indices &optional i0)
4415 "Remove the elements in LIST with indices in INDICES.
4416 First element has index 0, or I0 if given."
4417 (if (not indices)
4418 list
4419 (if (integerp indices) (setq indices (list indices)))
4420 (setq i0 (1- (or i0 0)))
4421 (delq :rm (mapcar (lambda (x)
4422 (setq i0 (1+ i0))
4423 (if (memq i0 indices) :rm x))
4424 list))))
4426 (defun orgtbl-toggle-comment ()
4427 "Comment or uncomment the orgtbl at point."
4428 (interactive)
4429 (let* ((case-fold-search t)
4430 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4431 (re2 (concat "^" orgtbl-line-start-regexp))
4432 (commented (save-excursion (beginning-of-line 1)
4433 (cond ((looking-at re1) t)
4434 ((looking-at re2) nil)
4435 (t (error "Not at an org table")))))
4436 (re (if commented re1 re2))
4437 beg end)
4438 (save-excursion
4439 (beginning-of-line 1)
4440 (while (looking-at re) (beginning-of-line 0))
4441 (beginning-of-line 2)
4442 (setq beg (point))
4443 (while (looking-at re) (beginning-of-line 2))
4444 (setq end (point)))
4445 (comment-region beg end (if commented '(4) nil))))
4447 (defun orgtbl-insert-radio-table ()
4448 "Insert a radio table template appropriate for this major mode."
4449 (interactive)
4450 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4451 (txt (nth 1 e))
4452 name pos)
4453 (unless e (error "No radio table setup defined for %s" major-mode))
4454 (setq name (read-string "Table name: "))
4455 (while (string-match "%n" txt)
4456 (setq txt (replace-match name t t txt)))
4457 (or (bolp) (insert "\n"))
4458 (setq pos (point))
4459 (insert txt)
4460 (goto-char pos)))
4462 ;; Dynamically bound input and output for table formatting.
4463 (defvar *orgtbl-table* nil
4464 "Carries the current table through formatting routines.")
4465 (defvar *orgtbl-rtn* nil
4466 "Formatting routines push the output lines here.")
4467 ;; Formatting parameters for the current table section.
4468 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4469 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4470 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4471 (defvar *orgtbl-fmt* nil "Format for each entry.")
4472 (defvar *orgtbl-efmt* nil "Format for numbers.")
4473 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4474 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4475 (defvar *orgtbl-lstart* nil "Text starting a row.")
4476 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4477 (defvar *orgtbl-lend* nil "Text ending a row.")
4478 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4480 (defsubst orgtbl-get-fmt (fmt i)
4481 "Retrieve the format from FMT corresponding to the Ith column."
4482 (if (and (not (functionp fmt)) (consp fmt))
4483 (plist-get fmt i)
4484 fmt))
4486 (defsubst orgtbl-apply-fmt (fmt &rest args)
4487 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4488 (cond ((functionp fmt) (apply fmt args))
4489 (fmt (apply 'format fmt args))
4490 (args (car args))
4491 (t args)))
4493 (defsubst orgtbl-eval-str (str)
4494 "If STR is a function, evaluate it with no arguments."
4495 (if (functionp str)
4496 (funcall str)
4497 str))
4499 (defun orgtbl-format-line (line)
4500 "Format LINE as a table row."
4501 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4502 (let* ((i 0)
4503 (line
4504 (mapcar
4505 (lambda (f)
4506 (setq i (1+ i))
4507 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4508 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4509 (orgtbl-apply-fmt efmt (match-string 1 f)
4510 (match-string 2 f))
4511 f)))
4512 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4513 *orgtbl-default-fmt*)
4514 f)))
4515 line)))
4516 (push (if *orgtbl-lfmt*
4517 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4518 (concat (orgtbl-eval-str *orgtbl-lstart*)
4519 (mapconcat 'identity line *orgtbl-sep*)
4520 (orgtbl-eval-str *orgtbl-lend*)))
4521 *orgtbl-rtn*))))
4523 (defun orgtbl-format-section (section-stopper)
4524 "Format lines until the first occurrence of SECTION-STOPPER."
4525 (let (prevline)
4526 (progn
4527 (while (not (eq (car *orgtbl-table*) section-stopper))
4528 (if prevline (orgtbl-format-line prevline))
4529 (setq prevline (pop *orgtbl-table*)))
4530 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4531 (*orgtbl-lend* *orgtbl-llend*)
4532 (*orgtbl-lfmt* *orgtbl-llfmt*))
4533 (orgtbl-format-line prevline))))))
4535 ;;;###autoload
4536 (defun orgtbl-to-generic (table params)
4537 "Convert the orgtbl-mode TABLE to some other format.
4538 This generic routine can be used for many standard cases.
4539 TABLE is a list, each entry either the symbol `hline' for a horizontal
4540 separator line, or a list of fields for that line.
4541 PARAMS is a property list of parameters that can influence the conversion.
4542 For the generic converter, some parameters are obligatory: you need to
4543 specify either :lfmt, or all of (:lstart :lend :sep).
4545 Valid parameters are:
4547 :splice When set to t, return only table body lines, don't wrap
4548 them into :tstart and :tend. Default is nil. When :splice
4549 is non-nil, this also means that the exporter should not look
4550 for and interpret header and footer sections.
4552 :hline String to be inserted on horizontal separation lines.
4553 May be nil to ignore hlines.
4555 :sep Separator between two fields
4556 :remove-nil-lines Do not include lines that evaluate to nil.
4558 Each in the following group may be either a string or a function
4559 of no arguments returning a string:
4561 :tstart String to start the table. Ignored when :splice is t.
4562 :tend String to end the table. Ignored when :splice is t.
4563 :lstart String to start a new table line.
4564 :llstart String to start the last table line, defaults to :lstart.
4565 :lend String to end a table line
4566 :llend String to end the last table line, defaults to :lend.
4568 Each in the following group may be a string, a function of one
4569 argument (the field or line) returning a string, or a plist
4570 mapping columns to either of the above:
4572 :lfmt Format for entire line, with enough %s to capture all fields.
4573 If this is present, :lstart, :lend, and :sep are ignored.
4574 :llfmt Format for the entire last line, defaults to :lfmt.
4575 :fmt A format to be used to wrap the field, should contain
4576 %s for the original field value. For example, to wrap
4577 everything in dollars, you could use :fmt \"$%s$\".
4578 This may also be a property list with column numbers and
4579 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4580 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4581 Same as above, specific for the header lines in the table.
4582 All lines before the first hline are treated as header.
4583 If any of these is not present, the data line value is used.
4585 This may be either a string or a function of two arguments:
4587 :efmt Use this format to print numbers with exponentials.
4588 The format should have %s twice for inserting mantissa
4589 and exponent, for example \"%s\\\\times10^{%s}\". This
4590 may also be a property list with column numbers and
4591 formats. :fmt will still be applied after :efmt.
4593 In addition to this, the parameters :skip and :skipcols are always handled
4594 directly by `orgtbl-send-table'. See manual."
4595 (let* ((splicep (plist-get params :splice))
4596 (hline (plist-get params :hline))
4597 (skipheadrule (plist-get params :skipheadrule))
4598 (remove-nil-linesp (plist-get params :remove-nil-lines))
4599 (remove-newlines (plist-get params :remove-newlines))
4600 (*orgtbl-hline* hline)
4601 (*orgtbl-table* table)
4602 (*orgtbl-sep* (plist-get params :sep))
4603 (*orgtbl-efmt* (plist-get params :efmt))
4604 (*orgtbl-lstart* (plist-get params :lstart))
4605 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4606 (*orgtbl-lend* (plist-get params :lend))
4607 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4608 (*orgtbl-lfmt* (plist-get params :lfmt))
4609 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4610 (*orgtbl-fmt* (plist-get params :fmt))
4611 *orgtbl-rtn*)
4613 ;; Put header
4614 (unless splicep
4615 (when (plist-member params :tstart)
4616 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4617 (if tstart (push tstart *orgtbl-rtn*)))))
4619 ;; Do we have a heading section? If so, format it and handle the
4620 ;; trailing hline.
4621 (if (and (not splicep)
4622 (or (consp (car *orgtbl-table*))
4623 (consp (nth 1 *orgtbl-table*)))
4624 (memq 'hline (cdr *orgtbl-table*)))
4625 (progn
4626 (when (eq 'hline (car *orgtbl-table*))
4627 ;; there is a hline before the first data line
4628 (and hline (push hline *orgtbl-rtn*))
4629 (pop *orgtbl-table*))
4630 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4631 *orgtbl-lstart*))
4632 (*orgtbl-llstart* (or (plist-get params :hllstart)
4633 *orgtbl-llstart*))
4634 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4635 (*orgtbl-llend* (or (plist-get params :hllend)
4636 (plist-get params :hlend) *orgtbl-llend*))
4637 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4638 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4639 (plist-get params :hlfmt) *orgtbl-llfmt*))
4640 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4641 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4642 (orgtbl-format-section 'hline))
4643 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4644 (pop *orgtbl-table*)))
4646 ;; Now format the main section.
4647 (orgtbl-format-section nil)
4649 (unless splicep
4650 (when (plist-member params :tend)
4651 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4652 (if tend (push tend *orgtbl-rtn*)))))
4654 (mapconcat (if remove-newlines
4655 (lambda (tend)
4656 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4657 'identity)
4658 (nreverse (if remove-nil-linesp
4659 (remq nil *orgtbl-rtn*)
4660 *orgtbl-rtn*)) "\n")))
4662 ;;;###autoload
4663 (defun orgtbl-to-tsv (table params)
4664 "Convert the orgtbl-mode table to TAB separated material."
4665 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4666 ;;;###autoload
4667 (defun orgtbl-to-csv (table params)
4668 "Convert the orgtbl-mode table to CSV material.
4669 This does take care of the proper quoting of fields with comma or quotes."
4670 (orgtbl-to-generic table (org-combine-plists
4671 '(:sep "," :fmt org-quote-csv-field)
4672 params)))
4674 ;;;###autoload
4675 (defun orgtbl-to-latex (table params)
4676 "Convert the orgtbl-mode TABLE to LaTeX.
4677 TABLE is a list, each entry either the symbol `hline' for a horizontal
4678 separator line, or a list of fields for that line.
4679 PARAMS is a property list of parameters that can influence the conversion.
4680 Supports all parameters from `orgtbl-to-generic'. Most important for
4681 LaTeX are:
4683 :splice When set to t, return only table body lines, don't wrap
4684 them into a tabular environment. Default is nil.
4686 :fmt A format to be used to wrap the field, should contain %s for the
4687 original field value. For example, to wrap everything in dollars,
4688 use :fmt \"$%s$\". This may also be a property list with column
4689 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4690 The format may also be a function that formats its one argument.
4692 :efmt Format for transforming numbers with exponentials. The format
4693 should have %s twice for inserting mantissa and exponent, for
4694 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4695 This may also be a property list with column numbers and formats.
4696 The format may also be a function that formats its two arguments.
4698 :llend If you find too much space below the last line of a table,
4699 pass a value of \"\" for :llend to suppress the final \\\\.
4701 The general parameters :skip and :skipcols have already been applied when
4702 this function is called."
4703 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4704 org-table-last-alignment ""))
4705 (params2
4706 (list
4707 :tstart (concat "\\begin{tabular}{" alignment "}")
4708 :tend "\\end{tabular}"
4709 :lstart "" :lend " \\\\" :sep " & "
4710 :efmt "%s\\,(%s)" :hline "\\hline")))
4711 (orgtbl-to-generic table (org-combine-plists params2 params))))
4713 ;;;###autoload
4714 (defun orgtbl-to-html (table params)
4715 "Convert the orgtbl-mode TABLE to HTML.
4716 TABLE is a list, each entry either the symbol `hline' for a horizontal
4717 separator line, or a list of fields for that line.
4718 PARAMS is a property list of parameters that can influence the conversion.
4719 Currently this function recognizes the following parameters:
4721 :splice When set to t, return only table body lines, don't wrap
4722 them into a <table> environment. Default is nil.
4724 The general parameters :skip and :skipcols have already been applied when
4725 this function is called. The function does *not* use `orgtbl-to-generic',
4726 so you cannot specify parameters for it."
4727 (let* ((splicep (plist-get params :splice))
4728 (html-table-tag org-export-html-table-tag)
4729 html)
4730 ;; Just call the formatter we already have
4731 ;; We need to make text lines for it, so put the fields back together.
4732 (setq html (org-format-org-table-html
4733 (mapcar
4734 (lambda (x)
4735 (if (eq x 'hline)
4736 "|----+----|"
4737 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4738 table)
4739 splicep))
4740 (if (string-match "\n+\\'" html)
4741 (setq html (replace-match "" t t html)))
4742 html))
4744 ;;;###autoload
4745 (defun orgtbl-to-texinfo (table params)
4746 "Convert the orgtbl-mode TABLE to TeXInfo.
4747 TABLE is a list, each entry either the symbol `hline' for a horizontal
4748 separator line, or a list of fields for that line.
4749 PARAMS is a property list of parameters that can influence the conversion.
4750 Supports all parameters from `orgtbl-to-generic'. Most important for
4751 TeXInfo are:
4753 :splice nil/t When set to t, return only table body lines, don't wrap
4754 them into a multitable environment. Default is nil.
4756 :fmt fmt A format to be used to wrap the field, should contain
4757 %s for the original field value. For example, to wrap
4758 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4759 This may also be a property list with column numbers and
4760 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4761 Each format also may be a function that formats its one
4762 argument.
4764 :cf \"f1 f2..\" The column fractions for the table. By default these
4765 are computed automatically from the width of the columns
4766 under org-mode.
4768 The general parameters :skip and :skipcols have already been applied when
4769 this function is called."
4770 (let* ((total (float (apply '+ org-table-last-column-widths)))
4771 (colfrac (or (plist-get params :cf)
4772 (mapconcat
4773 (lambda (x) (format "%.3f" (/ (float x) total)))
4774 org-table-last-column-widths " ")))
4775 (params2
4776 (list
4777 :tstart (concat "@multitable @columnfractions " colfrac)
4778 :tend "@end multitable"
4779 :lstart "@item " :lend "" :sep " @tab "
4780 :hlstart "@headitem ")))
4781 (orgtbl-to-generic table (org-combine-plists params2 params))))
4783 ;;;###autoload
4784 (defun orgtbl-to-orgtbl (table params)
4785 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4786 Useful when slicing one table into many. The :hline, :sep,
4787 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4788 and :tend suppress strings without splicing; they can be set to
4789 provide ORGTBL directives for the generated table."
4790 (let* ((params2
4791 (list
4792 :remove-newlines t
4793 :tstart nil :tend nil
4794 :hline "|---"
4795 :sep " | "
4796 :lstart "| "
4797 :lend " |"))
4798 (params (org-combine-plists params2 params)))
4799 (with-temp-buffer
4800 (insert (orgtbl-to-generic table params))
4801 (goto-char (point-min))
4802 (while (re-search-forward org-table-hline-regexp nil t)
4803 (org-table-align))
4804 (buffer-substring 1 (buffer-size)))))
4806 (defun orgtbl-to-table.el (table params)
4807 "Convert the orgtbl-mode TABLE into a table.el table."
4808 (with-temp-buffer
4809 (insert (orgtbl-to-orgtbl table params))
4810 (org-table-align)
4811 (replace-regexp-in-string
4812 "-|" "-+"
4813 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4815 (defun orgtbl-to-unicode (table params)
4816 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4817 You need the ascii-art-to-unicode.el package for this. You can download
4818 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4819 (with-temp-buffer
4820 (insert (orgtbl-to-table.el table params))
4821 (goto-char (point-min))
4822 (if (or (featurep 'ascii-art-to-unicode)
4823 (require 'ascii-art-to-unicode nil t))
4824 (aa2u)
4825 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4826 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4827 "Link to ascii-art-to-unicode.el") org-stored-links))
4828 (error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4829 (buffer-string)))
4831 (defun org-table-get-remote-range (name-or-id form)
4832 "Get a field value or a list of values in a range from table at ID.
4834 NAME-OR-ID may be the name of a table in the current file as set by
4835 a \"#+TBLNAME:\" directive. The first table following this line
4836 will then be used. Alternatively, it may be an ID referring to
4837 any entry, also in a different file. In this case, the first table
4838 in that entry will be referenced.
4839 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4840 \"@I$2..@II$2\". All the references must be absolute, not relative.
4842 The return value is either a single string for a single field, or a
4843 list of the fields in the rectangle ."
4844 (save-match-data
4845 (let ((case-fold-search t) (id-loc nil)
4846 ;; Protect a bunch of variables from being overwritten
4847 ;; by the context of the remote table
4848 org-table-column-names org-table-column-name-regexp
4849 org-table-local-parameters org-table-named-field-locations
4850 org-table-current-line-types org-table-current-begin-line
4851 org-table-current-begin-pos org-table-dlines
4852 org-table-current-ncol
4853 org-table-hlines org-table-last-alignment
4854 org-table-last-column-widths org-table-last-alignment
4855 org-table-last-column-widths tbeg
4856 buffer loc)
4857 (setq form (org-table-convert-refs-to-rc form))
4858 (save-excursion
4859 (save-restriction
4860 (widen)
4861 (save-excursion
4862 (goto-char (point-min))
4863 (if (re-search-forward
4864 (concat "^[ \t]*#\\+tblname:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4865 nil t)
4866 (setq buffer (current-buffer) loc (match-beginning 0))
4867 (setq id-loc (org-id-find name-or-id 'marker))
4868 (unless (and id-loc (markerp id-loc))
4869 (error "Can't find remote table \"%s\"" name-or-id))
4870 (setq buffer (marker-buffer id-loc)
4871 loc (marker-position id-loc))
4872 (move-marker id-loc nil)))
4873 (with-current-buffer buffer
4874 (save-excursion
4875 (save-restriction
4876 (widen)
4877 (goto-char loc)
4878 (forward-char 1)
4879 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4880 (not (match-beginning 1)))
4881 (error "Cannot find a table at NAME or ID %s" name-or-id))
4882 (setq tbeg (point-at-bol))
4883 (org-table-get-specials)
4884 (setq form (org-table-formula-substitute-names
4885 (org-table-formula-handle-first/last-rc form)))
4886 (if (and (string-match org-table-range-regexp form)
4887 (> (length (match-string 0 form)) 1))
4888 (save-match-data
4889 (org-table-get-range (match-string 0 form) tbeg 1))
4890 form)))))))))
4892 (defmacro org-define-lookup-function (mode)
4893 (let ((mode-str (symbol-name mode))
4894 (first-p (equal mode 'first))
4895 (all-p (equal mode 'all)))
4896 (let ((plural-str (if all-p "s" "")))
4897 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4898 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4899 If R-LIST is nil, return matching element%s of S-LIST.
4900 If PREDICATE is not nil, use it instead of `equal' to match VAL.
4901 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
4902 This function is generated by a call to the macro `org-define-lookup-function'."
4903 mode-str plural-str plural-str plural-str)
4904 (let ,(let ((lvars '((p (or predicate 'equal))
4905 (sl s-list)
4906 (rl (or r-list s-list))
4907 (ret nil))))
4908 (if first-p (add-to-list 'lvars '(match-p nil)))
4909 lvars)
4910 (while ,(if first-p '(and (not match-p) sl) 'sl)
4911 (progn
4912 (if (funcall p val (car sl))
4913 (progn
4914 ,(if first-p '(setq match-p t))
4915 (let ((rval (car rl)))
4916 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
4917 (setq sl (cdr sl) rl (cdr rl))))
4918 ret)))))
4920 (org-define-lookup-function first)
4921 (org-define-lookup-function last)
4922 (org-define-lookup-function all)
4924 (provide 'org-table)
4926 ;; Local variables:
4927 ;; generated-autoload-file: "org-loaddefs.el"
4928 ;; End:
4930 ;;; org-table.el ends here