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