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