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