org.texi: document header-args[:lang] properties
[org-mode.git] / lisp / org-table.el
blobaec0165088e2bd19d3c03dcbe0a7f5cd85b0bb7a
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 ((contents
1833 (apply #'mapcar* #'list
1834 ;; remove 'hline from list
1835 (delq nil (mapcar (lambda (x) (when (listp x) x))
1836 (org-table-to-lisp))))))
1837 (delete-region (org-table-begin) (org-table-end))
1838 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1839 contents ""))
1840 (org-table-align)))
1842 ;;;###autoload
1843 (defun org-table-wrap-region (arg)
1844 "Wrap several fields in a column like a paragraph.
1845 This is useful if you'd like to spread the contents of a field over several
1846 lines, in order to keep the table compact.
1848 If there is an active region, and both point and mark are in the same column,
1849 the text in the column is wrapped to minimum width for the given number of
1850 lines. Generally, this makes the table more compact. A prefix ARG may be
1851 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1852 formats the selected text to two lines. If the region was longer than two
1853 lines, the remaining lines remain empty. A negative prefix argument reduces
1854 the current number of lines by that amount. The wrapped text is pasted back
1855 into the table. If you formatted it to more lines than it was before, fields
1856 further down in the table get overwritten - so you might need to make space in
1857 the table first.
1859 If there is no region, the current field is split at the cursor position and
1860 the text fragment to the right of the cursor is prepended to the field one
1861 line down.
1863 If there is no region, but you specify a prefix ARG, the current field gets
1864 blank, and the content is appended to the field above."
1865 (interactive "P")
1866 (org-table-check-inside-data-field)
1867 (if (org-region-active-p)
1868 ;; There is a region: fill as a paragraph
1869 (let* ((beg (region-beginning))
1870 (cline (save-excursion (goto-char beg) (org-current-line)))
1871 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1872 nlines)
1873 (org-table-cut-region (region-beginning) (region-end))
1874 (if (> (length (car org-table-clip)) 1)
1875 (user-error "Region must be limited to single column"))
1876 (setq nlines (if arg
1877 (if (< arg 1)
1878 (+ (length org-table-clip) arg)
1879 arg)
1880 (length org-table-clip)))
1881 (setq org-table-clip
1882 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1883 nil nlines)))
1884 (org-goto-line cline)
1885 (org-table-goto-column ccol)
1886 (org-table-paste-rectangle))
1887 ;; No region, split the current field at point
1888 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1889 (skip-chars-forward "^\r\n|"))
1890 (if arg
1891 ;; combine with field above
1892 (let ((s (org-table-blank-field))
1893 (col (org-table-current-column)))
1894 (beginning-of-line 0)
1895 (while (org-at-table-hline-p) (beginning-of-line 0))
1896 (org-table-goto-column col)
1897 (skip-chars-forward "^|")
1898 (skip-chars-backward " ")
1899 (insert " " (org-trim s))
1900 (org-table-align))
1901 ;; split field
1902 (if (looking-at "\\([^|]+\\)+|")
1903 (let ((s (match-string 1)))
1904 (replace-match " |")
1905 (goto-char (match-beginning 0))
1906 (org-table-next-row)
1907 (insert (org-trim s) " ")
1908 (org-table-align))
1909 (org-table-next-row)))))
1911 (defvar org-field-marker nil)
1913 ;;;###autoload
1914 (defun org-table-edit-field (arg)
1915 "Edit table field in a different window.
1916 This is mainly useful for fields that contain hidden parts.
1917 When called with a \\[universal-argument] prefix, just make the full field visible so that
1918 it can be edited in place."
1919 (interactive "P")
1920 (cond
1921 ((equal arg '(16))
1922 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1923 (arg
1924 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1925 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1926 (remove-text-properties b e '(org-cwidth t invisible t
1927 display t intangible t))
1928 (if (and (boundp 'font-lock-mode) font-lock-mode)
1929 (font-lock-fontify-block))))
1931 (let ((pos (point-marker))
1932 (coord
1933 (if (eq org-table-use-standard-references t)
1934 (concat (org-number-to-letters (org-table-current-column))
1935 (int-to-string (org-table-current-dline)))
1936 (concat "@" (int-to-string (org-table-current-dline))
1937 "$" (int-to-string (org-table-current-column)))))
1938 (field (org-table-get-field))
1939 (cw (current-window-configuration))
1941 (goto-char pos)
1942 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1943 (when (and (local-variable-p 'org-field-marker)
1944 (markerp org-field-marker))
1945 (move-marker org-field-marker nil))
1946 (erase-buffer)
1947 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
1948 (let ((org-inhibit-startup t)) (org-mode))
1949 (auto-fill-mode -1)
1950 (setq truncate-lines nil)
1951 (setq word-wrap t)
1952 (goto-char (setq p (point-max)))
1953 (insert (org-trim field))
1954 (remove-text-properties p (point-max)
1955 '(invisible t org-cwidth t display t
1956 intangible t))
1957 (goto-char p)
1958 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
1959 (org-set-local 'org-window-configuration cw)
1960 (org-set-local 'org-field-marker pos)
1961 (message "Edit and finish with C-c C-c")))))
1963 (defun org-table-finish-edit-field ()
1964 "Finish editing a table data field.
1965 Remove all newline characters, insert the result into the table, realign
1966 the table and kill the editing buffer."
1967 (let ((pos org-field-marker)
1968 (cw org-window-configuration)
1969 (cb (current-buffer))
1970 text)
1971 (goto-char (point-min))
1972 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
1973 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
1974 (replace-match " "))
1975 (setq text (org-trim (buffer-string)))
1976 (set-window-configuration cw)
1977 (kill-buffer cb)
1978 (select-window (get-buffer-window (marker-buffer pos)))
1979 (goto-char pos)
1980 (move-marker pos nil)
1981 (org-table-check-inside-data-field)
1982 (org-table-get-field nil text)
1983 (org-table-align)
1984 (message "New field value inserted")))
1986 (define-minor-mode org-table-follow-field-mode
1987 "Minor mode to make the table field editor window follow the cursor.
1988 When this mode is active, the field editor window will always show the
1989 current field. The mode exits automatically when the cursor leaves the
1990 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1991 nil " TblFollow" nil
1992 (if org-table-follow-field-mode
1993 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
1994 'append 'local)
1995 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
1996 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1997 (win (and buf (get-buffer-window buf))))
1998 (when win (delete-window win))
1999 (when buf
2000 (with-current-buffer buf
2001 (move-marker org-field-marker nil))
2002 (kill-buffer buf)))))
2004 (defun org-table-follow-fields-with-editor ()
2005 (if (and org-table-exit-follow-field-mode-when-leaving-table
2006 (not (org-at-table-p)))
2007 ;; We have left the table, exit the follow mode
2008 (org-table-follow-field-mode -1)
2009 (when (org-table-check-inside-data-field 'noerror)
2010 (let ((win (selected-window)))
2011 (org-table-edit-field nil)
2012 (org-fit-window-to-buffer)
2013 (select-window win)))))
2015 (defvar org-timecnt) ; dynamically scoped parameter
2017 ;;;###autoload
2018 (defun org-table-sum (&optional beg end nlast)
2019 "Sum numbers in region of current table column.
2020 The result will be displayed in the echo area, and will be available
2021 as kill to be inserted with \\[yank].
2023 If there is an active region, it is interpreted as a rectangle and all
2024 numbers in that rectangle will be summed. If there is no active
2025 region and point is located in a table column, sum all numbers in that
2026 column.
2028 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2029 numbers are assumed to be times as well (in decimal hours) and the
2030 numbers are added as such.
2032 If NLAST is a number, only the NLAST fields will actually be summed."
2033 (interactive)
2034 (save-excursion
2035 (let (col (org-timecnt 0) diff h m s org-table-clip)
2036 (cond
2037 ((and beg end)) ; beg and end given explicitly
2038 ((org-region-active-p)
2039 (setq beg (region-beginning) end (region-end)))
2041 (setq col (org-table-current-column))
2042 (goto-char (org-table-begin))
2043 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2044 (user-error "No table data"))
2045 (org-table-goto-column col)
2046 (setq beg (point))
2047 (goto-char (org-table-end))
2048 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2049 (user-error "No table data"))
2050 (org-table-goto-column col)
2051 (setq end (point))))
2052 (let* ((items (apply 'append (org-table-copy-region beg end)))
2053 (items1 (cond ((not nlast) items)
2054 ((>= nlast (length items)) items)
2055 (t (setq items (reverse items))
2056 (setcdr (nthcdr (1- nlast) items) nil)
2057 (nreverse items))))
2058 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2059 items1)))
2060 (res (apply '+ numbers))
2061 (sres (if (= org-timecnt 0)
2062 (number-to-string res)
2063 (setq diff (* 3600 res)
2064 h (floor (/ diff 3600)) diff (mod diff 3600)
2065 m (floor (/ diff 60)) diff (mod diff 60)
2066 s diff)
2067 (format "%d:%02d:%02d" h m s))))
2068 (kill-new sres)
2069 (if (org-called-interactively-p 'interactive)
2070 (message "%s"
2071 (substitute-command-keys
2072 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2073 (length numbers) sres))))
2074 sres))))
2076 (defun org-table-get-number-for-summing (s)
2077 (let (n)
2078 (if (string-match "^ *|? *" s)
2079 (setq s (replace-match "" nil nil s)))
2080 (if (string-match " *|? *$" s)
2081 (setq s (replace-match "" nil nil s)))
2082 (setq n (string-to-number s))
2083 (cond
2084 ((and (string-match "0" s)
2085 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2086 ((string-match "\\`[ \t]+\\'" s) nil)
2087 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2088 (let ((h (string-to-number (or (match-string 1 s) "0")))
2089 (m (string-to-number (or (match-string 2 s) "0")))
2090 (s (string-to-number (or (match-string 4 s) "0"))))
2091 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2092 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2093 ((equal n 0) nil)
2094 (t n))))
2096 (defun org-table-current-field-formula (&optional key noerror)
2097 "Return the formula active for the current field.
2098 Assumes that specials are in place.
2099 If KEY is given, return the key to this formula.
2100 Otherwise return the formula preceded with \"=\" or \":=\"."
2101 (let* ((name (car (rassoc (list (org-current-line)
2102 (org-table-current-column))
2103 org-table-named-field-locations)))
2104 (col (org-table-current-column))
2105 (scol (int-to-string col))
2106 (ref (format "@%d$%d" (org-table-current-dline) col))
2107 (stored-list (org-table-get-stored-formulas noerror))
2108 (ass (or (assoc name stored-list)
2109 (assoc ref stored-list)
2110 (assoc scol stored-list))))
2111 (if key
2112 (car ass)
2113 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2114 (cdr ass))))))
2116 (defun org-table-get-formula (&optional equation named)
2117 "Read a formula from the minibuffer, offer stored formula as default.
2118 When NAMED is non-nil, look for a named equation."
2119 (let* ((stored-list (org-table-get-stored-formulas))
2120 (name (car (rassoc (list (org-current-line)
2121 (org-table-current-column))
2122 org-table-named-field-locations)))
2123 (ref (format "@%d$%d" (org-table-current-dline)
2124 (org-table-current-column)))
2125 (refass (assoc ref stored-list))
2126 (nameass (assoc name stored-list))
2127 (scol (if named
2128 (if (and name (not (string-match "^LR[0-9]+$" name)))
2129 name
2130 ref)
2131 (int-to-string (org-table-current-column))))
2132 (dummy (and (or nameass refass) (not named)
2133 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2134 (message "Formula not replaced")))
2135 (name (or name ref))
2136 (org-table-may-need-update nil)
2137 (stored (cdr (assoc scol stored-list)))
2138 (eq (cond
2139 ((and stored equation (string-match "^ *=? *$" equation))
2140 stored)
2141 ((stringp equation)
2142 equation)
2143 (t (org-table-formula-from-user
2144 (read-string
2145 (org-table-formula-to-user
2146 (format "%s formula %s%s="
2147 (if named "Field" "Column")
2148 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2149 scol))
2150 (if stored (org-table-formula-to-user stored) "")
2151 'org-table-formula-history
2152 )))))
2153 mustsave)
2154 (when (not (string-match "\\S-" eq))
2155 ;; remove formula
2156 (setq stored-list (delq (assoc scol stored-list) stored-list))
2157 (org-table-store-formulas stored-list)
2158 (user-error "Formula removed"))
2159 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2160 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2161 (if (and name (not named))
2162 ;; We set the column equation, delete the named one.
2163 (setq stored-list (delq (assoc name stored-list) stored-list)
2164 mustsave t))
2165 (if stored
2166 (setcdr (assoc scol stored-list) eq)
2167 (setq stored-list (cons (cons scol eq) stored-list)))
2168 (if (or mustsave (not (equal stored eq)))
2169 (org-table-store-formulas stored-list))
2170 eq))
2172 (defun org-table-store-formulas (alist)
2173 "Store the list of formulas below the current table."
2174 (setq alist (sort alist 'org-table-formula-less-p))
2175 (let ((case-fold-search t))
2176 (save-excursion
2177 (goto-char (org-table-end))
2178 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2179 (progn
2180 ;; don't overwrite TBLFM, we might use text properties to store stuff
2181 (goto-char (match-beginning 3))
2182 (delete-region (match-beginning 3) (match-end 0)))
2183 (org-indent-line)
2184 (insert (or (match-string 2) "#+TBLFM:")))
2185 (insert " "
2186 (mapconcat (lambda (x)
2187 (concat
2188 (if (equal (string-to-char (car x)) ?@) "" "$")
2189 (car x) "=" (cdr x)))
2190 alist "::")
2191 "\n"))))
2193 (defsubst org-table-formula-make-cmp-string (a)
2194 (when (string-match "\\`$[<>]" a)
2195 (let ((arrow (string-to-char (substring a 1))))
2196 ;; Fake a high number to make sure this is sorted at the end.
2197 (setq a (org-table-formula-handle-first/last-rc a))
2198 (setq a (format "$%d" (+ 10000
2199 (if (= arrow ?<) -1000 0)
2200 (string-to-number (substring a 1)))))))
2201 (when (string-match
2202 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2204 (concat
2205 (if (match-end 2)
2206 (format "@%05d" (string-to-number (match-string 2 a))) "")
2207 (if (match-end 4)
2208 (format "$%05d" (string-to-number (match-string 4 a))) "")
2209 (if (match-end 5)
2210 (concat "@@" (match-string 5 a))))))
2212 (defun org-table-formula-less-p (a b)
2213 "Compare two formulas for sorting."
2214 (let ((as (org-table-formula-make-cmp-string (car a)))
2215 (bs (org-table-formula-make-cmp-string (car b))))
2216 (and as bs (string< as bs))))
2218 ;;;###autoload
2219 (defun org-table-get-stored-formulas (&optional noerror)
2220 "Return an alist with the stored formulas directly after current table."
2221 (interactive) ;; FIXME interactive?
2222 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2223 (save-excursion
2224 (goto-char (org-table-end))
2225 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2226 (setq strings (org-split-string (org-match-string-no-properties 2)
2227 " *:: *"))
2228 (while (setq string (pop strings))
2229 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2230 (setq scol (if (match-end 2)
2231 (match-string 2 string)
2232 (match-string 1 string))
2233 scol (if (member (string-to-char scol) '(?< ?>))
2234 (concat "$" scol) scol)
2235 eq (match-string 3 string)
2236 eq-alist (cons (cons scol eq) eq-alist))
2237 (if (member scol seen)
2238 (if noerror
2239 (progn
2240 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2241 (ding)
2242 (sit-for 2))
2243 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2244 (push scol seen))))))
2245 (nreverse eq-alist)))
2247 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2248 "Modify the equations after the table structure has been edited.
2249 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2250 For all numbers larger than LIMIT, shift them by DELTA."
2251 (save-excursion
2252 (goto-char (org-table-end))
2253 (when (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2254 (let ((msg "The formulas in #+TBLFM have been updated")
2255 (re (concat key "\\([0-9]+\\)"))
2256 (re2
2257 (when remove
2258 (if (or (equal key "$") (equal key "$LR"))
2259 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2260 (regexp-quote key) remove)
2261 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2262 s n a)
2263 (when remove
2264 (while (re-search-forward re2 (point-at-eol) t)
2265 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2266 (if (equal (char-before (match-beginning 0)) ?.)
2267 (user-error "Change makes TBLFM term %s invalid, use undo to recover"
2268 (match-string 0))
2269 (replace-match "")))))
2270 (while (re-search-forward re (point-at-eol) t)
2271 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2272 (setq s (match-string 1) n (string-to-number s))
2273 (cond
2274 ((setq a (assoc s replace))
2275 (replace-match (concat key (cdr a)) t t)
2276 (message msg))
2277 ((and limit (> n limit))
2278 (replace-match (concat key (int-to-string (+ n delta))) t t)
2279 (message msg)))))))))
2281 (defun org-table-get-specials ()
2282 "Get the column names and local parameters for this table."
2283 (save-excursion
2284 (let ((beg (org-table-begin)) (end (org-table-end))
2285 names name fields fields1 field cnt
2286 c v l line col types dlines hlines last-dline)
2287 (setq org-table-column-names nil
2288 org-table-local-parameters nil
2289 org-table-named-field-locations nil
2290 org-table-current-begin-line nil
2291 org-table-current-begin-pos nil
2292 org-table-current-line-types nil
2293 org-table-current-ncol 0)
2294 (goto-char beg)
2295 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2296 (setq names (org-split-string (match-string 1) " *| *")
2297 cnt 1)
2298 (while (setq name (pop names))
2299 (setq cnt (1+ cnt))
2300 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
2301 (push (cons name (int-to-string cnt)) org-table-column-names))))
2302 (setq org-table-column-names (nreverse org-table-column-names))
2303 (setq org-table-column-name-regexp
2304 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2305 (goto-char beg)
2306 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2307 (setq fields (org-split-string (match-string 1) " *| *"))
2308 (while (setq field (pop fields))
2309 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2310 (push (cons (match-string 1 field) (match-string 2 field))
2311 org-table-local-parameters))))
2312 (goto-char beg)
2313 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2314 (setq c (match-string 1)
2315 fields (org-split-string (match-string 2) " *| *"))
2316 (save-excursion
2317 (beginning-of-line (if (equal c "_") 2 0))
2318 (setq line (org-current-line) col 1)
2319 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2320 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2321 (while (and fields1 (setq field (pop fields)))
2322 (setq v (pop fields1) col (1+ col))
2323 (when (and (stringp field) (stringp v)
2324 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
2325 (push (cons field v) org-table-local-parameters)
2326 (push (list field line col) org-table-named-field-locations))))
2327 ;; Analyse the line types
2328 (goto-char beg)
2329 (setq org-table-current-begin-line (org-current-line)
2330 org-table-current-begin-pos (point)
2331 l org-table-current-begin-line)
2332 (while (looking-at "[ \t]*|\\(-\\)?")
2333 (push (if (match-end 1) 'hline 'dline) types)
2334 (if (match-end 1) (push l hlines) (push l dlines))
2335 (beginning-of-line 2)
2336 (setq l (1+ l)))
2337 (push 'hline types) ;; add an imaginary extra hline to the end
2338 (setq org-table-current-line-types (apply 'vector (nreverse types))
2339 last-dline (car dlines)
2340 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2341 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2342 (org-goto-line last-dline)
2343 (let* ((l last-dline)
2344 (fields (org-split-string
2345 (buffer-substring (point-at-bol) (point-at-eol))
2346 "[ \t]*|[ \t]*"))
2347 (nfields (length fields))
2348 al al2)
2349 (setq org-table-current-ncol nfields)
2350 (loop for i from 1 to nfields do
2351 (push (list (format "LR%d" i) l i) al)
2352 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2353 (setq org-table-named-field-locations
2354 (append org-table-named-field-locations al))
2355 (setq org-table-local-parameters
2356 (append org-table-local-parameters al2))))))
2358 ;;;###autoload
2359 (defun org-table-maybe-eval-formula ()
2360 "Check if the current field starts with \"=\" or \":=\".
2361 If yes, store the formula and apply it."
2362 ;; We already know we are in a table. Get field will only return a formula
2363 ;; when appropriate. It might return a separator line, but no problem.
2364 (when org-table-formula-evaluate-inline
2365 (let* ((field (org-trim (or (org-table-get-field) "")))
2366 named eq)
2367 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2368 (setq named (equal (string-to-char field) ?:)
2369 eq (match-string 1 field))
2370 (if (or (fboundp 'calc-eval)
2371 (equal (substring eq 0 (min 2 (length eq))) "'("))
2372 (org-table-eval-formula (if named '(4) nil)
2373 (org-table-formula-from-user eq))
2374 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2376 (defvar org-recalc-commands nil
2377 "List of commands triggering the recalculation of a line.
2378 Will be filled automatically during use.")
2380 (defvar org-recalc-marks
2381 '((" " . "Unmarked: no special line, no automatic recalculation")
2382 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2383 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2384 ("!" . "Column name definition line. Reference in formula as $name.")
2385 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2386 ("_" . "Names for values in row below this one.")
2387 ("^" . "Names for values in row above this one.")))
2389 ;;;###autoload
2390 (defun org-table-rotate-recalc-marks (&optional newchar)
2391 "Rotate the recalculation mark in the first column.
2392 If in any row, the first field is not consistent with a mark,
2393 insert a new column for the markers.
2394 When there is an active region, change all the lines in the region,
2395 after prompting for the marking character.
2396 After each change, a message will be displayed indicating the meaning
2397 of the new mark."
2398 (interactive)
2399 (unless (org-at-table-p) (user-error "Not at a table"))
2400 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2401 (beg (org-table-begin))
2402 (end (org-table-end))
2403 (l (org-current-line))
2404 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2405 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2406 (have-col
2407 (save-excursion
2408 (goto-char beg)
2409 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2410 (col (org-table-current-column))
2411 (forcenew (car (assoc newchar org-recalc-marks)))
2412 epos new)
2413 (when l1
2414 (message "Change region to what mark? Type # * ! $ or SPC: ")
2415 (setq newchar (char-to-string (read-char-exclusive))
2416 forcenew (car (assoc newchar org-recalc-marks))))
2417 (if (and newchar (not forcenew))
2418 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2419 newchar))
2420 (if l1 (org-goto-line l1))
2421 (save-excursion
2422 (beginning-of-line 1)
2423 (unless (looking-at org-table-dataline-regexp)
2424 (user-error "Not at a table data line")))
2425 (unless have-col
2426 (org-table-goto-column 1)
2427 (org-table-insert-column)
2428 (org-table-goto-column (1+ col)))
2429 (setq epos (point-at-eol))
2430 (save-excursion
2431 (beginning-of-line 1)
2432 (org-table-get-field
2433 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2434 (concat " "
2435 (setq new (or forcenew
2436 (cadr (member (match-string 1) marks))))
2437 " ")
2438 " # ")))
2439 (if (and l1 l2)
2440 (progn
2441 (org-goto-line l1)
2442 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2443 (and (looking-at org-table-dataline-regexp)
2444 (org-table-get-field 1 (concat " " new " "))))
2445 (org-goto-line l1)))
2446 (if (not (= epos (point-at-eol))) (org-table-align))
2447 (org-goto-line l)
2448 (and (org-called-interactively-p 'interactive)
2449 (message "%s" (cdr (assoc new org-recalc-marks))))))
2451 ;;;###autoload
2452 (defun org-table-maybe-recalculate-line ()
2453 "Recompute the current line if marked for it, and if we haven't just done it."
2454 (interactive)
2455 (and org-table-allow-automatic-line-recalculation
2456 (not (and (memq last-command org-recalc-commands)
2457 (equal org-last-recalc-line (org-current-line))))
2458 (save-excursion (beginning-of-line 1)
2459 (looking-at org-table-auto-recalculate-regexp))
2460 (org-table-recalculate) t))
2462 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2463 (defsubst org-set-calc-mode (var &optional value)
2464 (if (stringp var)
2465 (setq var (assoc var '(("D" calc-angle-mode deg)
2466 ("R" calc-angle-mode rad)
2467 ("F" calc-prefer-frac t)
2468 ("S" calc-symbolic-mode t)))
2469 value (nth 2 var) var (nth 1 var)))
2470 (if (memq var org-tbl-calc-modes)
2471 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2472 (cons var (cons value org-tbl-calc-modes)))
2473 org-tbl-calc-modes)
2475 ;;;###autoload
2476 (defun org-table-eval-formula (&optional arg equation
2477 suppress-align suppress-const
2478 suppress-store suppress-analysis)
2479 "Replace the table field value at the cursor by the result of a calculation.
2481 This function makes use of Dave Gillespie's Calc package, in my view the
2482 most exciting program ever written for GNU Emacs. So you need to have Calc
2483 installed in order to use this function.
2485 In a table, this command replaces the value in the current field with the
2486 result of a formula. It also installs the formula as the \"current\" column
2487 formula, by storing it in a special line below the table. When called
2488 with a `C-u' prefix, the current field must be a named field, and the
2489 formula is installed as valid in only this specific field.
2491 When called with two `C-u' prefixes, insert the active equation
2492 for the field back into the current field, so that it can be
2493 edited there. This is useful in order to use \\[org-table-show-reference]
2494 to check the referenced fields.
2496 When called, the command first prompts for a formula, which is read in
2497 the minibuffer. Previously entered formulas are available through the
2498 history list, and the last used formula is offered as a default.
2499 These stored formulas are adapted correctly when moving, inserting, or
2500 deleting columns with the corresponding commands.
2502 The formula can be any algebraic expression understood by the Calc package.
2503 For details, see the Org-mode manual.
2505 This function can also be called from Lisp programs and offers
2506 additional arguments: EQUATION can be the formula to apply. If this
2507 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2508 used to speed-up recursive calls by by-passing unnecessary aligns.
2509 SUPPRESS-CONST suppresses the interpretation of constants in the
2510 formula, assuming that this has been done already outside the function.
2511 SUPPRESS-STORE means the formula should not be stored, either because
2512 it is already stored, or because it is a modified equation that should
2513 not overwrite the stored one."
2514 (interactive "P")
2515 (org-table-check-inside-data-field)
2516 (or suppress-analysis (org-table-get-specials))
2517 (if (equal arg '(16))
2518 (let ((eq (org-table-current-field-formula)))
2519 (or eq (user-error "No equation active for current field"))
2520 (org-table-get-field nil eq)
2521 (org-table-align)
2522 (setq org-table-may-need-update t))
2523 (let* (fields
2524 (ndown (if (integerp arg) arg 1))
2525 (org-table-automatic-realign nil)
2526 (case-fold-search nil)
2527 (down (> ndown 1))
2528 (formula (if (and equation suppress-store)
2529 equation
2530 (org-table-get-formula equation (equal arg '(4)))))
2531 (n0 (org-table-current-column))
2532 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2533 (numbers nil) ; was a variable, now fixed default
2534 (keep-empty nil)
2535 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2536 duration duration-output-format)
2537 ;; Parse the format string. Since we have a lot of modes, this is
2538 ;; a lot of work. However, I think calc still uses most of the time.
2539 (if (string-match ";" formula)
2540 (let ((tmp (org-split-string formula ";")))
2541 (setq formula (car tmp)
2542 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2543 (nth 1 tmp)))
2544 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2545 (setq c (string-to-char (match-string 1 fmt))
2546 n (string-to-number (match-string 2 fmt)))
2547 (if (= c ?p)
2548 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2549 (setq org-tbl-calc-modes
2550 (org-set-calc-mode
2551 'calc-float-format
2552 (list (cdr (assoc c '((?n . float) (?f . fix)
2553 (?s . sci) (?e . eng))))
2554 n))))
2555 (setq fmt (replace-match "" t t fmt)))
2556 (if (string-match "T" fmt)
2557 (setq duration t numbers t
2558 duration-output-format nil
2559 fmt (replace-match "" t t fmt)))
2560 (if (string-match "t" fmt)
2561 (setq duration t
2562 duration-output-format org-table-duration-custom-format
2563 numbers t
2564 fmt (replace-match "" t t fmt)))
2565 (if (string-match "N" fmt)
2566 (setq numbers t
2567 fmt (replace-match "" t t fmt)))
2568 (if (string-match "L" fmt)
2569 (setq literal t
2570 fmt (replace-match "" t t fmt)))
2571 (if (string-match "E" fmt)
2572 (setq keep-empty t
2573 fmt (replace-match "" t t fmt)))
2574 (while (string-match "[DRFS]" fmt)
2575 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2576 (setq fmt (replace-match "" t t fmt)))
2577 (unless (string-match "\\S-" fmt)
2578 (setq fmt nil))))
2579 (if (and (not suppress-const) org-table-formula-use-constants)
2580 (setq formula (org-table-formula-substitute-names formula)))
2581 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2582 (while (> ndown 0)
2583 (setq fields (org-split-string
2584 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2585 " *| *"))
2586 ;; replace fields with duration values if relevant
2587 (if duration
2588 (setq fields
2589 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2590 fields)))
2591 (if (eq numbers t)
2592 (setq fields (mapcar
2593 (lambda (x)
2594 (if (string-match "\\S-" x)
2595 (number-to-string (string-to-number x))
2597 fields)))
2598 (setq ndown (1- ndown))
2599 (setq form (copy-sequence formula)
2600 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2601 (if (and lispp literal) (setq lispp 'literal))
2603 ;; Insert row and column number of formula result field
2604 (while (string-match "[@$]#" form)
2605 (setq form
2606 (replace-match
2607 (format "%d"
2608 (save-match-data
2609 (if (equal (substring form (match-beginning 0)
2610 (1+ (match-beginning 0)))
2611 "@")
2612 (org-table-current-dline)
2613 (org-table-current-column))))
2614 t t form)))
2616 ;; Check for old vertical references
2617 (setq form (org-table-rewrite-old-row-references form))
2618 ;; Insert remote references
2619 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2620 (setq form
2621 (replace-match
2622 (save-match-data
2623 (org-table-make-reference
2624 (let ((rmtrng (org-table-get-remote-range
2625 (match-string 1 form) (match-string 2 form))))
2626 (if duration
2627 (if (listp rmtrng)
2628 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2629 (org-table-time-string-to-seconds rmtrng))
2630 rmtrng))
2631 keep-empty numbers lispp))
2632 t t form)))
2633 ;; Insert complex ranges
2634 (while (and (string-match org-table-range-regexp form)
2635 (> (length (match-string 0 form)) 1))
2636 (setq formrg (save-match-data
2637 (org-table-get-range (match-string 0 form) nil n0)))
2638 (setq formrpl
2639 (save-match-data
2640 (org-table-make-reference
2641 ;; possibly handle durations
2642 (if duration
2643 (if (listp formrg)
2644 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2645 (org-table-time-string-to-seconds formrg))
2646 formrg)
2647 keep-empty numbers lispp)))
2648 (if (not (save-match-data
2649 (string-match (regexp-quote form) formrpl)))
2650 (setq form (replace-match formrpl t t form))
2651 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2652 ;; Insert simple ranges
2653 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2654 (setq form
2655 (replace-match
2656 (save-match-data
2657 (org-table-make-reference
2658 (org-sublist
2659 fields (string-to-number (match-string 1 form))
2660 (string-to-number (match-string 2 form)))
2661 keep-empty numbers lispp))
2662 t t form)))
2663 (setq form0 form)
2664 ;; Insert the references to fields in same row
2665 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2666 (setq n (+ (string-to-number (match-string 1 form))
2667 (if (match-end 2) n0 0))
2668 x (nth (1- (if (= n 0) n0 (max n 1))) fields))
2669 (unless x (user-error "Invalid field specifier \"%s\""
2670 (match-string 0 form)))
2671 (setq form (replace-match
2672 (save-match-data
2673 (org-table-make-reference
2674 x keep-empty numbers lispp))
2675 t t form)))
2677 (if lispp
2678 (setq ev (condition-case nil
2679 (eval (eval (read form)))
2680 (error "#ERROR"))
2681 ev (if (numberp ev) (number-to-string ev) ev)
2682 ev (if duration (org-table-time-seconds-to-string
2683 (string-to-number ev)
2684 duration-output-format) ev))
2685 (or (fboundp 'calc-eval)
2686 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2687 ;; Use <...> time-stamps so that Calc can handle them
2688 (setq form (replace-regexp-in-string org-ts-regexp3 "<\\1>" form))
2689 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2690 (when (string-match org-ts-regexp2 form)
2691 (let* ((ts (match-string 0 form))
2692 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2693 (system-time-locale "C")
2694 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2695 (cdr org-time-stamp-formats))
2696 (car org-time-stamp-formats))))
2697 (setq form (replace-match (format-time-string tf tsp) t t form))))
2699 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2700 form
2701 (calc-eval (cons form org-tbl-calc-modes)
2702 (when (and (not keep-empty) numbers) 'num)))
2703 ev (if duration (org-table-time-seconds-to-string
2704 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2705 (string-to-number (org-table-time-string-to-seconds ev))
2706 (string-to-number ev))
2707 duration-output-format)
2708 ev)))
2710 (when org-table-formula-debug
2711 (with-output-to-temp-buffer "*Substitution History*"
2712 (princ (format "Substitution history of formula
2713 Orig: %s
2714 $xyz-> %s
2715 @r$c-> %s
2716 $1-> %s\n" orig formula form0 form))
2717 (if (listp ev)
2718 (princ (format " %s^\nError: %s"
2719 (make-string (car ev) ?\-) (nth 1 ev)))
2720 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2721 ev (or fmt "NONE")
2722 (if fmt (format fmt (string-to-number ev)) ev)))))
2723 (setq bw (get-buffer-window "*Substitution History*"))
2724 (org-fit-window-to-buffer bw)
2725 (unless (and (org-called-interactively-p 'any) (not ndown))
2726 (unless (let (inhibit-redisplay)
2727 (y-or-n-p "Debugging Formula. Continue to next? "))
2728 (org-table-align)
2729 (user-error "Abort"))
2730 (delete-window bw)
2731 (message "")))
2732 (if (listp ev) (setq fmt nil ev "#ERROR"))
2733 (org-table-justify-field-maybe
2734 (format org-table-formula-field-format
2735 (if fmt (format fmt (string-to-number ev)) ev)))
2736 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2737 (call-interactively 'org-return)
2738 (setq ndown 0)))
2739 (and down (org-table-maybe-recalculate-line))
2740 (or suppress-align (and org-table-may-need-update
2741 (org-table-align))))))
2743 (defun org-table-put-field-property (prop value)
2744 (save-excursion
2745 (put-text-property (progn (skip-chars-backward "^|") (point))
2746 (progn (skip-chars-forward "^|") (point))
2747 prop value)))
2749 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2750 "Get a calc vector from a column, according to descriptor DESC.
2751 Optional arguments TBEG and COL can give the beginning of the table and
2752 the current column, to avoid unnecessary parsing.
2754 HIGHLIGHT means just highlight the range.
2756 When CORNERS-ONLY is set, only return the corners of the range as
2757 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2758 in the buffer and column1 and column2 are table column numbers."
2759 (if (not (equal (string-to-char desc) ?@))
2760 (setq desc (concat "@" desc)))
2761 (save-excursion
2762 (or tbeg (setq tbeg (org-table-begin)))
2763 (or col (setq col (org-table-current-column)))
2764 (let ((thisline (org-current-line))
2765 beg end c1 c2 r1 r2 rangep tmp)
2766 (unless (string-match org-table-range-regexp desc)
2767 (user-error "Invalid table range specifier `%s'" desc))
2768 (setq rangep (match-end 3)
2769 r1 (and (match-end 1) (match-string 1 desc))
2770 r2 (and (match-end 4) (match-string 4 desc))
2771 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2772 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2774 (and c1 (setq c1 (+ (string-to-number c1)
2775 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2776 (and c2 (setq c2 (+ (string-to-number c2)
2777 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2778 (if (equal r1 "") (setq r1 nil))
2779 (if (equal r2 "") (setq r2 nil))
2780 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2781 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2782 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2783 (if (not r1) (setq r1 thisline))
2784 (if (not r2) (setq r2 thisline))
2785 (if (or (not c1) (= 0 c1)) (setq c1 col))
2786 (if (or (not c2) (= 0 c2)) (setq c2 col))
2787 (if (and (not corners-only)
2788 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2789 ;; just one field
2790 (progn
2791 (org-goto-line r1)
2792 (while (not (looking-at org-table-dataline-regexp))
2793 (beginning-of-line 2))
2794 (prog1 (org-trim (org-table-get-field c1))
2795 (if highlight (org-table-highlight-rectangle (point) (point)))))
2796 ;; A range, return a vector
2797 ;; First sort the numbers to get a regular rectangle
2798 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2799 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2800 (if corners-only
2801 ;; Only return the corners of the range
2802 (list r1 c1 r2 c2)
2803 ;; Copy the range values into a list
2804 (org-goto-line r1)
2805 (while (not (looking-at org-table-dataline-regexp))
2806 (beginning-of-line 2))
2807 (org-table-goto-column c1)
2808 (setq beg (point))
2809 (org-goto-line r2)
2810 (while (not (looking-at org-table-dataline-regexp))
2811 (beginning-of-line 0))
2812 (org-table-goto-column c2)
2813 (setq end (point))
2814 (if highlight
2815 (org-table-highlight-rectangle
2816 beg (progn (skip-chars-forward "^|\n") (point))))
2817 ;; return string representation of calc vector
2818 (mapcar 'org-trim
2819 (apply 'append (org-table-copy-region beg end))))))))
2821 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2822 "Analyze descriptor DESC and retrieve the corresponding line number.
2823 The cursor is currently in line CLINE, the table begins in line BLINE,
2824 and TABLE is a vector with line types."
2825 (if (string-match "^[0-9]+$" desc)
2826 (aref org-table-dlines (string-to-number desc))
2827 (setq cline (or cline (org-current-line))
2828 bline (or bline org-table-current-begin-line)
2829 table (or table org-table-current-line-types))
2830 (if (or
2831 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2832 ;; 1 2 3 4 5 6
2833 (and (not (match-end 3)) (not (match-end 6)))
2834 (and (match-end 3) (match-end 6) (not (match-end 5))))
2835 (user-error "Invalid row descriptor `%s'" desc))
2836 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2837 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2838 (odir (and (match-end 5) (match-string 5 desc)))
2839 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2840 (i (- cline bline))
2841 (rel (and (match-end 6)
2842 (or (and (match-end 1) (not (match-end 3)))
2843 (match-end 5)))))
2844 (if (and hn (not hdir))
2845 (progn
2846 (setq i 0 hdir "+")
2847 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2848 (if (and (not hn) on (not odir))
2849 (user-error "Should never happen");;(aref org-table-dlines on)
2850 (if (and hn (> hn 0))
2851 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2852 nil hn cline desc)))
2853 (if on
2854 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2855 rel on cline desc)))
2856 (+ bline i)))))
2858 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2859 "FIXME: Needs more documentation."
2860 (let ((l (length table)))
2861 (while (> n 0)
2862 (while (and (setq i (+ i (if backwards -1 1)))
2863 (>= i 0) (< i l)
2864 (not (eq (aref table i) type))
2865 (if (and relative (eq (aref table i) 'hline))
2866 (cond
2867 ((eq org-table-relative-ref-may-cross-hline t) t)
2868 ((eq org-table-relative-ref-may-cross-hline 'error)
2869 (user-error "Row descriptor %s used in line %d crosses hline" desc cline))
2870 (t (setq i (- i (if backwards -1 1))
2871 n 1)
2872 nil))
2873 t)))
2874 (setq n (1- n)))
2875 (if (or (< i 0) (>= i l))
2876 (user-error "Row descriptor %s used in line %d leads outside table"
2877 desc cline)
2878 i)))
2880 (defun org-table-rewrite-old-row-references (s)
2881 (if (string-match "&[-+0-9I]" s)
2882 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2885 (defun org-table-make-reference (elements keep-empty numbers lispp)
2886 "Convert list ELEMENTS to something appropriate to insert into formula.
2887 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2888 NUMBERS indicates that everything should be converted to numbers.
2889 LISPP non-nil means to return something appropriate for a Lisp
2890 list, 'literal is for the format specifier L."
2891 ;; Calc nan (not a number) is used for the conversion of the empty
2892 ;; field to a reference for several reasons: (i) It is accepted in a
2893 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2894 ;; (ii) In a single field (not in range) it can be distinguished
2895 ;; from "(nan)" which is the reference made from a single field
2896 ;; containing "nan".
2897 (if (stringp elements)
2898 ;; field reference
2899 (if lispp
2900 (if (eq lispp 'literal)
2901 elements
2902 (if (and (eq elements "") (not keep-empty))
2904 (prin1-to-string
2905 (if numbers (string-to-number elements) elements))))
2906 (if (string-match "\\S-" elements)
2907 (progn
2908 (when numbers (setq elements (number-to-string
2909 (string-to-number elements))))
2910 (concat "(" elements ")"))
2911 (if (or (not keep-empty) numbers) "(0)" "nan")))
2912 ;; range reference
2913 (unless keep-empty
2914 (setq elements
2915 (delq nil
2916 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2917 elements))))
2918 (setq elements (or elements '())) ; if delq returns nil then we need '()
2919 (if lispp
2920 (mapconcat
2921 (lambda (x)
2922 (if (eq lispp 'literal)
2924 (prin1-to-string (if numbers (string-to-number x) x))))
2925 elements " ")
2926 (concat "[" (mapconcat
2927 (lambda (x)
2928 (if (string-match "\\S-" x)
2929 (if numbers
2930 (number-to-string (string-to-number x))
2932 (if (or (not keep-empty) numbers) "0" "nan")))
2933 elements
2934 ",") "]"))))
2936 ;;;###autoload
2937 (defun org-table-set-constants ()
2938 "Set `org-table-formula-constants-local' in the current buffer."
2939 (let (cst consts const-str)
2940 (save-excursion
2941 (goto-char (point-min))
2942 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
2943 (setq const-str (substring-no-properties (match-string 1)))
2944 (setq consts (append consts (org-split-string const-str "[ \t]+")))
2945 (when consts
2946 (let (e)
2947 (while (setq e (pop consts))
2948 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2949 (if (assoc-string (match-string 1 e) cst)
2950 (setq cst (delete (assoc-string (match-string 1 e) cst) cst)))
2951 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2952 (setq org-table-formula-constants-local cst)))))))
2954 ;;;###autoload
2955 (defun org-table-recalculate (&optional all noalign)
2956 "Recalculate the current table line by applying all stored formulas.
2957 With prefix arg ALL, do this for all lines in the table.
2958 With the prefix argument ALL is `(16)' \
2959 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2960 it is the symbol `iterate', recompute the table until it no longer changes.
2961 If NOALIGN is not nil, do not re-align the table after the computations
2962 are done. This is typically used internally to save time, if it is
2963 known that the table will be realigned a little later anyway."
2964 (interactive "P")
2965 (or (memq this-command org-recalc-commands)
2966 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2967 (unless (org-at-table-p) (user-error "Not at a table"))
2968 (if (or (eq all 'iterate) (equal all '(16)))
2969 (org-table-iterate)
2970 (org-table-get-specials)
2971 (let* ((eqlist (sort (org-table-get-stored-formulas)
2972 (lambda (a b) (string< (car a) (car b)))))
2973 (eqlist1 (copy-sequence eqlist))
2974 (inhibit-redisplay (not debug-on-error))
2975 (line-re org-table-dataline-regexp)
2976 (thisline (org-current-line))
2977 (thiscol (org-table-current-column))
2978 seen-fields lhs1
2979 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
2980 ;; Insert constants in all formulas
2981 (setq eqlist
2982 (mapcar (lambda (x)
2983 (when (string-match "\\`$[<>]" (car x))
2984 (setq lhs1 (car x))
2985 (setq x (cons (substring
2986 (org-table-formula-handle-first/last-rc
2987 (car x)) 1)
2988 (cdr x)))
2989 (if (assoc (car x) eqlist1)
2990 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
2991 lhs1 (car x))))
2992 (cons
2993 (org-table-formula-handle-first/last-rc (car x))
2994 (org-table-formula-substitute-names
2995 (org-table-formula-handle-first/last-rc (cdr x)))))
2996 eqlist))
2997 ;; Split the equation list
2998 (while (setq eq (pop eqlist))
2999 (if (<= (string-to-char (car eq)) ?9)
3000 (push eq eqlnum)
3001 (push eq eqlname)))
3002 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
3003 ;; Expand ranges in lhs of formulas
3004 (setq eqlname (org-table-expand-lhs-ranges eqlname))
3006 ;; Get the correct line range to process
3007 (if all
3008 (progn
3009 (setq end (move-marker (make-marker) (1+ (org-table-end))))
3010 (goto-char (setq beg (org-table-begin)))
3011 (if (re-search-forward org-table-calculate-mark-regexp end t)
3012 ;; This is a table with marked lines, compute selected lines
3013 (setq line-re org-table-recalculate-regexp)
3014 ;; Move forward to the first non-header line
3015 (if (and (re-search-forward org-table-dataline-regexp end t)
3016 (re-search-forward org-table-hline-regexp end t)
3017 (re-search-forward org-table-dataline-regexp end t))
3018 (setq beg (match-beginning 0))
3019 nil))) ;; just leave beg where it is
3020 (setq beg (point-at-bol)
3021 end (move-marker (make-marker) (1+ (point-at-eol)))))
3022 (goto-char beg)
3023 (and all (message "Re-applying formulas to full table..."))
3025 ;; First find the named fields, and mark them untouchable.
3026 ;; Also check if several field/range formulas try to set the same field.
3027 (remove-text-properties beg end '(org-untouchable t))
3028 (while (setq eq (pop eqlname))
3029 (setq name (car eq)
3030 a (assoc name org-table-named-field-locations))
3031 (setq name1 name)
3032 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
3033 (nth 2 a))))
3034 (when (member name1 seen-fields)
3035 (user-error "Several field/range formulas try to set %s" name1))
3036 (push name1 seen-fields)
3038 (and (not a)
3039 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
3040 (setq a (list name
3041 (condition-case nil
3042 (aref org-table-dlines
3043 (string-to-number (match-string 1 name)))
3044 (error (user-error "Invalid row number in %s"
3045 name)))
3046 (string-to-number (match-string 2 name)))))
3047 (when (and a (or all (equal (nth 1 a) thisline)))
3048 (message "Re-applying formula to field: %s" name)
3049 (org-goto-line (nth 1 a))
3050 (org-table-goto-column (nth 2 a))
3051 (push (append a (list (cdr eq))) eqlname1)
3052 (org-table-put-field-property :org-untouchable t)))
3053 (setq eqlname1 (nreverse eqlname1))
3055 ;; Now evaluate the column formulas, but skip fields covered by
3056 ;; field formulas
3057 (goto-char beg)
3058 (while (re-search-forward line-re end t)
3059 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3060 ;; Unprotected line, recalculate
3061 (and all (message "Re-applying formulas to full table...(line %d)"
3062 (setq cnt (1+ cnt))))
3063 (setq org-last-recalc-line (org-current-line))
3064 (setq eql eqlnum)
3065 (while (setq entry (pop eql))
3066 (org-goto-line org-last-recalc-line)
3067 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3068 (unless (get-text-property (point) :org-untouchable)
3069 (org-table-eval-formula nil (cdr entry)
3070 'noalign 'nocst 'nostore 'noanalysis)))))
3072 ;; Now evaluate the field formulas
3073 (while (setq eq (pop eqlname1))
3074 (message "Re-applying formula to field: %s" (car eq))
3075 (org-goto-line (nth 1 eq))
3076 (org-table-goto-column (nth 2 eq))
3077 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
3078 'nostore 'noanalysis))
3080 (org-goto-line thisline)
3081 (org-table-goto-column thiscol)
3082 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3083 (or noalign (and org-table-may-need-update (org-table-align))
3084 (and all (message "Re-applying formulas to %d lines...done" cnt)))
3086 ;; back to initial position
3087 (message "Re-applying formulas...done")
3088 (org-goto-line thisline)
3089 (org-table-goto-column thiscol)
3090 (or noalign (and org-table-may-need-update (org-table-align))
3091 (and all (message "Re-applying formulas...done"))))))
3093 ;;;###autoload
3094 (defun org-table-iterate (&optional arg)
3095 "Recalculate the table until it does not change anymore.
3096 The maximum number of iterations is 10, but you can choose a different value
3097 with the prefix ARG."
3098 (interactive "P")
3099 (let ((imax (if arg (prefix-numeric-value arg) 10))
3100 (i 0)
3101 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3102 thistbl)
3103 (catch 'exit
3104 (while (< i imax)
3105 (setq i (1+ i))
3106 (org-table-recalculate 'all)
3107 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3108 (if (not (string= lasttbl thistbl))
3109 (setq lasttbl thistbl)
3110 (if (> i 1)
3111 (message "Convergence after %d iterations" i)
3112 (message "Table was already stable"))
3113 (throw 'exit t)))
3114 (user-error "No convergence after %d iterations" i))))
3116 ;;;###autoload
3117 (defun org-table-recalculate-buffer-tables ()
3118 "Recalculate all tables in the current buffer."
3119 (interactive)
3120 (save-excursion
3121 (save-restriction
3122 (widen)
3123 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3125 ;;;###autoload
3126 (defun org-table-iterate-buffer-tables ()
3127 "Iterate all tables in the buffer, to converge inter-table dependencies."
3128 (interactive)
3129 (let* ((imax 10)
3130 (i imax)
3131 (checksum (md5 (buffer-string)))
3133 (save-excursion
3134 (save-restriction
3135 (widen)
3136 (catch 'exit
3137 (while (> i 0)
3138 (setq i (1- i))
3139 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3140 (if (equal checksum (setq c1 (md5 (buffer-string))))
3141 (progn
3142 (message "Convergence after %d iterations" (- imax i))
3143 (throw 'exit t))
3144 (setq checksum c1)))
3145 (user-error "No convergence after %d iterations" imax))))))
3147 (defun org-table-calc-current-TBLFM (&optional arg)
3148 "Apply the #+TBLFM in the line at point to the table."
3149 (interactive "P")
3150 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3151 (let ((formula (buffer-substring
3152 (point-at-bol)
3153 (point-at-eol)))
3154 s e)
3155 (save-excursion
3156 ;; Insert a temporary formula at right after the table
3157 (goto-char (org-table-TBLFM-begin))
3158 (setq s (set-marker (make-marker) (point)))
3159 (insert (concat formula "\n"))
3160 (setq e (set-marker (make-marker) (point)))
3161 ;; Recalculate the table
3162 (beginning-of-line 0) ; move to the inserted line
3163 (skip-chars-backward " \r\n\t")
3164 (if (org-at-table-p)
3165 (unwind-protect
3166 (org-call-with-arg 'org-table-recalculate (or arg t))
3167 ;; delete the formula inserted temporarily
3168 (delete-region s e))))))
3170 (defun org-table-TBLFM-begin ()
3171 "Find the beginning of the TBLFM lines and return its position.
3172 Return nil when the beginning of TBLFM line was not found."
3173 (save-excursion
3174 (when (progn (forward-line 1)
3175 (re-search-backward
3176 org-table-TBLFM-begin-regexp
3177 nil t))
3178 (point-at-bol 2))))
3180 (defun org-table-expand-lhs-ranges (equations)
3181 "Expand list of formulas.
3182 If some of the RHS in the formulas are ranges or a row reference, expand
3183 them to individual field equations for each field."
3184 (let (e res lhs rhs range r1 r2 c1 c2)
3185 (while (setq e (pop equations))
3186 (setq lhs (car e) rhs (cdr e))
3187 (cond
3188 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3189 ;; This just refers to one fixed field
3190 (push e res))
3191 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3192 ;; This just refers to one fixed named field
3193 (push e res))
3194 ((string-match "^@[0-9]+$" lhs)
3195 (loop for ic from 1 to org-table-current-ncol do
3196 (push (cons (format "%s$%d" lhs ic) rhs) res)
3197 (put-text-property 0 (length (caar res))
3198 :orig-eqn e (caar res))))
3200 (setq range (org-table-get-range lhs org-table-current-begin-pos
3201 1 nil 'corners))
3202 (setq r1 (nth 0 range) c1 (nth 1 range)
3203 r2 (nth 2 range) c2 (nth 3 range))
3204 (setq r1 (org-table-line-to-dline r1))
3205 (setq r2 (org-table-line-to-dline r2 'above))
3206 (loop for ir from r1 to r2 do
3207 (loop for ic from c1 to c2 do
3208 (push (cons (format "@%d$%d" ir ic) rhs) res)
3209 (put-text-property 0 (length (caar res))
3210 :orig-eqn e (caar res)))))))
3211 (nreverse res)))
3213 (defun org-table-formula-handle-first/last-rc (s)
3214 "Replace @<, @>, $<, $> with first/last row/column of the table.
3215 So @< and $< will always be replaced with @1 and $1, respectively.
3216 The advantage of these special markers are that structure editing of
3217 the table will not change them, while @1 and $1 will be modified
3218 when a line/row is swapped out of that privileged position. So for
3219 formulas that use a range of rows or columns, it may often be better
3220 to anchor the formula with \"I\" row markers, or to offset from the
3221 borders of the table using the @< @> $< $> makers."
3222 (let (n nmax len char (start 0))
3223 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3224 s start)
3225 (if (match-end 3)
3226 (setq start (match-end 3))
3227 (setq nmax (if (equal (match-string 1 s) "@")
3228 (1- (length org-table-dlines))
3229 org-table-current-ncol)
3230 len (- (match-end 2) (match-beginning 2))
3231 char (string-to-char (match-string 2 s))
3232 n (if (= char ?<)
3234 (- nmax len -1)))
3235 (if (or (< n 1) (> n nmax))
3236 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3237 (match-string 0 s) s))
3238 (setq start (match-beginning 0))
3239 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3242 (defun org-table-formula-substitute-names (f)
3243 "Replace $const with values in string F."
3244 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3245 ;; First, check for column names
3246 (while (setq start (string-match org-table-column-name-regexp f start))
3247 (setq start (1+ start))
3248 (setq a (assoc (match-string 1 f) org-table-column-names))
3249 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3250 ;; Parameters and constants
3251 (setq start 0)
3252 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3253 (if (match-end 2)
3254 (setq start (match-end 2))
3255 (setq start (1+ start))
3256 (if (setq a (save-match-data
3257 (org-table-get-constant (match-string 1 f))))
3258 (setq f (replace-match
3259 (concat (if pp "(") a (if pp ")")) t t f)))))
3260 (if org-table-formula-debug
3261 (put-text-property 0 (length f) :orig-formula f1 f))
3264 (defun org-table-get-constant (const)
3265 "Find the value for a parameter or constant in a formula.
3266 Parameters get priority."
3267 (or (cdr (assoc const org-table-local-parameters))
3268 (cdr (assoc const org-table-formula-constants-local))
3269 (cdr (assoc const org-table-formula-constants))
3270 (and (fboundp 'constants-get) (constants-get const))
3271 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3272 (org-entry-get nil (substring const 5) 'inherit))
3273 "#UNDEFINED_NAME"))
3275 (defvar org-table-fedit-map
3276 (let ((map (make-sparse-keymap)))
3277 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3278 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3279 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3280 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3281 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3282 (org-defkey map "\C-c?" 'org-table-show-reference)
3283 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3284 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3285 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3286 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3287 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3288 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3289 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3290 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3291 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3292 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3293 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3294 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3295 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3296 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3297 map))
3299 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3300 '("Edit-Formulas"
3301 ["Finish and Install" org-table-fedit-finish t]
3302 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3303 ["Abort" org-table-fedit-abort t]
3304 "--"
3305 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3306 ["Complete Lisp Symbol" lisp-complete-symbol t]
3307 "--"
3308 "Shift Reference at Point"
3309 ["Up" org-table-fedit-ref-up t]
3310 ["Down" org-table-fedit-ref-down t]
3311 ["Left" org-table-fedit-ref-left t]
3312 ["Right" org-table-fedit-ref-right t]
3314 "Change Test Row for Column Formulas"
3315 ["Up" org-table-fedit-line-up t]
3316 ["Down" org-table-fedit-line-down t]
3317 "--"
3318 ["Scroll Table Window" org-table-fedit-scroll t]
3319 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3320 ["Show Table Grid" org-table-fedit-toggle-coordinates
3321 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3322 org-table-overlay-coordinates)]
3323 "--"
3324 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3325 :style toggle :selected org-table-buffer-is-an]))
3327 (defvar org-pos)
3329 ;;;###autoload
3330 (defun org-table-edit-formulas ()
3331 "Edit the formulas of the current table in a separate buffer."
3332 (interactive)
3333 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3334 (beginning-of-line 0))
3335 (unless (org-at-table-p) (user-error "Not at a table"))
3336 (org-table-get-specials)
3337 (let ((key (org-table-current-field-formula 'key 'noerror))
3338 (eql (sort (org-table-get-stored-formulas 'noerror)
3339 'org-table-formula-less-p))
3340 (pos (point-marker))
3341 (startline 1)
3342 (wc (current-window-configuration))
3343 (sel-win (selected-window))
3344 (titles '((column . "# Column Formulas\n")
3345 (field . "# Field and Range Formulas\n")
3346 (named . "# Named Field Formulas\n")))
3347 entry s type title)
3348 (org-switch-to-buffer-other-window "*Edit Formulas*")
3349 (erase-buffer)
3350 ;; Keep global-font-lock-mode from turning on font-lock-mode
3351 (let ((font-lock-global-modes '(not fundamental-mode)))
3352 (fundamental-mode))
3353 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3354 (org-set-local 'org-pos pos)
3355 (org-set-local 'org-window-configuration wc)
3356 (org-set-local 'org-selected-window sel-win)
3357 (use-local-map org-table-fedit-map)
3358 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3359 (easy-menu-add org-table-fedit-menu)
3360 (setq startline (org-current-line))
3361 (while (setq entry (pop eql))
3362 (setq type (cond
3363 ((string-match "\\`$[<>]" (car entry)) 'column)
3364 ((equal (string-to-char (car entry)) ?@) 'field)
3365 ((string-match "^[0-9]" (car entry)) 'column)
3366 (t 'named)))
3367 (when (setq title (assq type titles))
3368 (or (bobp) (insert "\n"))
3369 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3370 (setq titles (remove title titles)))
3371 (if (equal key (car entry)) (setq startline (org-current-line)))
3372 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3373 (car entry) " = " (cdr entry) "\n"))
3374 (remove-text-properties 0 (length s) '(face nil) s)
3375 (insert s))
3376 (if (eq org-table-use-standard-references t)
3377 (org-table-fedit-toggle-ref-type))
3378 (org-goto-line startline)
3379 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3381 (defun org-table-fedit-post-command ()
3382 (when (not (memq this-command '(lisp-complete-symbol)))
3383 (let ((win (selected-window)))
3384 (save-excursion
3385 (condition-case nil
3386 (org-table-show-reference)
3387 (error nil))
3388 (select-window win)))))
3390 (defun org-table-formula-to-user (s)
3391 "Convert a formula from internal to user representation."
3392 (if (eq org-table-use-standard-references t)
3393 (org-table-convert-refs-to-an s)
3396 (defun org-table-formula-from-user (s)
3397 "Convert a formula from user to internal representation."
3398 (if org-table-use-standard-references
3399 (org-table-convert-refs-to-rc s)
3402 (defun org-table-convert-refs-to-rc (s)
3403 "Convert spreadsheet references from A7 to @7$28.
3404 Works for single references, but also for entire formulas and even the
3405 full TBLFM line."
3406 (let ((start 0))
3407 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3408 (cond
3409 ((match-end 3)
3410 ;; format match, just advance
3411 (setq start (match-end 0)))
3412 ((and (> (match-beginning 0) 0)
3413 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3414 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3415 ;; 3.e5 or something like this.
3416 (setq start (match-end 0)))
3417 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3418 ;; (member (match-string 1 s)
3419 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3421 ;; function name, just advance
3422 (setq start (match-end 0)))
3424 (setq start (match-beginning 0)
3425 s (replace-match
3426 (if (equal (match-string 2 s) "&")
3427 (format "$%d" (org-letters-to-number (match-string 1 s)))
3428 (format "@%d$%d"
3429 (string-to-number (match-string 2 s))
3430 (org-letters-to-number (match-string 1 s))))
3431 t t s)))))
3434 (defun org-table-convert-refs-to-an (s)
3435 "Convert spreadsheet references from to @7$28 to AB7.
3436 Works for single references, but also for entire formulas and even the
3437 full TBLFM line."
3438 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3439 (setq s (replace-match
3440 (format "%s%d"
3441 (org-number-to-letters
3442 (string-to-number (match-string 2 s)))
3443 (string-to-number (match-string 1 s)))
3444 t t s)))
3445 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3446 (setq s (replace-match (concat "\\1"
3447 (org-number-to-letters
3448 (string-to-number (match-string 2 s))) "&")
3449 t nil s)))
3452 (defun org-letters-to-number (s)
3453 "Convert a base 26 number represented by letters into an integer.
3454 For example: AB -> 28."
3455 (let ((n 0))
3456 (setq s (upcase s))
3457 (while (> (length s) 0)
3458 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3459 s (substring s 1)))
3462 (defun org-number-to-letters (n)
3463 "Convert an integer into a base 26 number represented by letters.
3464 For example: 28 -> AB."
3465 (let ((s ""))
3466 (while (> n 0)
3467 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3468 n (/ (1- n) 26)))
3471 (defun org-table-time-string-to-seconds (s)
3472 "Convert a time string into numerical duration in seconds.
3473 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3474 If S is a string representing a number, keep this number."
3475 (if (equal s "")
3477 (let (hour minus min sec res)
3478 (cond
3479 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3480 (setq minus (< 0 (length (match-string 1 s)))
3481 hour (string-to-number (match-string 2 s))
3482 min (string-to-number (match-string 3 s))
3483 sec (string-to-number (match-string 4 s)))
3484 (if minus
3485 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3486 (setq res (+ (* hour 3600) (* min 60) sec))))
3487 ((and (not (string-match org-ts-regexp-both s))
3488 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3489 (setq minus (< 0 (length (match-string 1 s)))
3490 hour (string-to-number (match-string 2 s))
3491 min (string-to-number (match-string 3 s)))
3492 (if minus
3493 (setq res (- (+ (* hour 3600) (* min 60))))
3494 (setq res (+ (* hour 3600) (* min 60)))))
3495 (t (setq res (string-to-number s))))
3496 (number-to-string res))))
3498 (defun org-table-time-seconds-to-string (secs &optional output-format)
3499 "Convert a number of seconds to a time string.
3500 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3501 minutes or seconds."
3502 (let* ((secs0 (abs secs))
3503 (res
3504 (cond ((eq output-format 'days)
3505 (format "%.3f" (/ (float secs0) 86400)))
3506 ((eq output-format 'hours)
3507 (format "%.2f" (/ (float secs0) 3600)))
3508 ((eq output-format 'minutes)
3509 (format "%.1f" (/ (float secs0) 60)))
3510 ((eq output-format 'seconds)
3511 (format "%d" secs0))
3512 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3513 (if (< secs 0) (concat "-" res) res)))
3515 (defun org-table-fedit-convert-buffer (function)
3516 "Convert all references in this buffer, using FUNCTION."
3517 (let ((line (org-current-line)))
3518 (goto-char (point-min))
3519 (while (not (eobp))
3520 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3521 (delete-region (point) (point-at-eol))
3522 (or (eobp) (forward-char 1)))
3523 (org-goto-line line)))
3525 (defun org-table-fedit-toggle-ref-type ()
3526 "Convert all references in the buffer from B3 to @3$2 and back."
3527 (interactive)
3528 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3529 (org-table-fedit-convert-buffer
3530 (if org-table-buffer-is-an
3531 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3532 (message "Reference type switched to %s"
3533 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3535 (defun org-table-fedit-ref-up ()
3536 "Shift the reference at point one row/hline up."
3537 (interactive)
3538 (org-table-fedit-shift-reference 'up))
3539 (defun org-table-fedit-ref-down ()
3540 "Shift the reference at point one row/hline down."
3541 (interactive)
3542 (org-table-fedit-shift-reference 'down))
3543 (defun org-table-fedit-ref-left ()
3544 "Shift the reference at point one field to the left."
3545 (interactive)
3546 (org-table-fedit-shift-reference 'left))
3547 (defun org-table-fedit-ref-right ()
3548 "Shift the reference at point one field to the right."
3549 (interactive)
3550 (org-table-fedit-shift-reference 'right))
3552 (defun org-table-fedit-shift-reference (dir)
3553 (cond
3554 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3555 (if (memq dir '(left right))
3556 (org-rematch-and-replace 1 (eq dir 'left))
3557 (user-error "Cannot shift reference in this direction")))
3558 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3559 ;; A B3-like reference
3560 (if (memq dir '(up down))
3561 (org-rematch-and-replace 2 (eq dir 'up))
3562 (org-rematch-and-replace 1 (eq dir 'left))))
3563 ((org-at-regexp-p
3564 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3565 ;; An internal reference
3566 (if (memq dir '(up down))
3567 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3568 (org-rematch-and-replace 5 (eq dir 'left))))))
3570 (defun org-rematch-and-replace (n &optional decr hline)
3571 "Re-match the group N, and replace it with the shifted reference."
3572 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3573 (goto-char (match-beginning n))
3574 (and (looking-at (regexp-quote (match-string n)))
3575 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3576 t t)))
3578 (defun org-table-shift-refpart (ref &optional decr hline)
3579 "Shift a reference part REF.
3580 If DECR is set, decrease the references row/column, else increase.
3581 If HLINE is set, this may be a hline reference, it certainly is not
3582 a translation reference."
3583 (save-match-data
3584 (let* ((sign (string-match "^[-+]" ref)) n)
3586 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3587 (cond
3588 ((and hline (string-match "^I+" ref))
3589 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3590 (setq n (+ n (if decr -1 1)))
3591 (if (= n 0) (setq n (+ n (if decr -1 1))))
3592 (if sign
3593 (setq sign (if (< n 0) "-" "+") n (abs n))
3594 (setq n (max 1 n)))
3595 (concat sign (make-string n ?I)))
3597 ((string-match "^[0-9]+" ref)
3598 (setq n (string-to-number (concat sign ref)))
3599 (setq n (+ n (if decr -1 1)))
3600 (if sign
3601 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3602 (number-to-string (max 1 n))))
3604 ((string-match "^[a-zA-Z]+" ref)
3605 (org-number-to-letters
3606 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3608 (t (user-error "Cannot shift reference"))))))
3610 (defun org-table-fedit-toggle-coordinates ()
3611 "Toggle the display of coordinates in the referenced table."
3612 (interactive)
3613 (let ((pos (marker-position org-pos)))
3614 (with-current-buffer (marker-buffer org-pos)
3615 (save-excursion
3616 (goto-char pos)
3617 (org-table-toggle-coordinate-overlays)))))
3619 (defun org-table-fedit-finish (&optional arg)
3620 "Parse the buffer for formula definitions and install them.
3621 With prefix ARG, apply the new formulas to the table."
3622 (interactive "P")
3623 (org-table-remove-rectangle-highlight)
3624 (if org-table-use-standard-references
3625 (progn
3626 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3627 (setq org-table-buffer-is-an nil)))
3628 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3629 (goto-char (point-min))
3630 (while (re-search-forward
3631 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3632 nil t)
3633 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3634 form (match-string 3))
3635 (setq form (org-trim form))
3636 (when (not (equal form ""))
3637 (while (string-match "[ \t]*\n[ \t]*" form)
3638 (setq form (replace-match " " t t form)))
3639 (when (assoc var eql)
3640 (user-error "Double formulas for %s" var))
3641 (push (cons var form) eql)))
3642 (setq org-pos nil)
3643 (set-window-configuration org-window-configuration)
3644 (select-window sel-win)
3645 (goto-char pos)
3646 (unless (org-at-table-p)
3647 (user-error "Lost table position - cannot install formulas"))
3648 (org-table-store-formulas eql)
3649 (move-marker pos nil)
3650 (kill-buffer "*Edit Formulas*")
3651 (if arg
3652 (org-table-recalculate 'all)
3653 (message "New formulas installed - press C-u C-c C-c to apply."))))
3655 (defun org-table-fedit-abort ()
3656 "Abort editing formulas, without installing the changes."
3657 (interactive)
3658 (org-table-remove-rectangle-highlight)
3659 (let ((pos org-pos) (sel-win org-selected-window))
3660 (set-window-configuration org-window-configuration)
3661 (select-window sel-win)
3662 (goto-char pos)
3663 (move-marker pos nil)
3664 (message "Formula editing aborted without installing changes")))
3666 (defun org-table-fedit-lisp-indent ()
3667 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3668 (interactive)
3669 (let ((pos (point)) beg end ind)
3670 (beginning-of-line 1)
3671 (cond
3672 ((looking-at "[ \t]")
3673 (goto-char pos)
3674 (call-interactively 'lisp-indent-line))
3675 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3676 ((not (fboundp 'pp-buffer))
3677 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3678 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3679 (goto-char (- (match-end 0) 2))
3680 (setq beg (point))
3681 (setq ind (make-string (current-column) ?\ ))
3682 (condition-case nil (forward-sexp 1)
3683 (error
3684 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3685 (setq end (point))
3686 (save-restriction
3687 (narrow-to-region beg end)
3688 (if (eq last-command this-command)
3689 (progn
3690 (goto-char (point-min))
3691 (setq this-command nil)
3692 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3693 (replace-match " ")))
3694 (pp-buffer)
3695 (untabify (point-min) (point-max))
3696 (goto-char (1+ (point-min)))
3697 (while (re-search-forward "^." nil t)
3698 (beginning-of-line 1)
3699 (insert ind))
3700 (goto-char (point-max))
3701 (org-delete-backward-char 1)))
3702 (goto-char beg))
3703 (t nil))))
3705 (defvar org-show-positions nil)
3707 (defun org-table-show-reference (&optional local)
3708 "Show the location/value of the $ expression at point."
3709 (interactive)
3710 (org-table-remove-rectangle-highlight)
3711 (catch 'exit
3712 (let ((pos (if local (point) org-pos))
3713 (face2 'highlight)
3714 (org-inhibit-highlight-removal t)
3715 (win (selected-window))
3716 (org-show-positions nil)
3717 var name e what match dest)
3718 (if local (org-table-get-specials))
3719 (setq what (cond
3720 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3721 (setq match (concat (substring (match-string 0) 0 -1)
3722 "$1.."
3723 (substring (match-string 0) 0 -1)
3724 "$100"))
3725 'range)
3726 ((or (org-at-regexp-p org-table-range-regexp2)
3727 (org-at-regexp-p org-table-translate-regexp)
3728 (org-at-regexp-p org-table-range-regexp))
3729 (setq match
3730 (save-match-data
3731 (org-table-convert-refs-to-rc (match-string 0))))
3732 'range)
3733 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3734 ((org-at-regexp-p "\\$[0-9]+") 'column)
3735 ((not local) nil)
3736 (t (user-error "No reference at point")))
3737 match (and what (or match (match-string 0))))
3738 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3739 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3740 'secondary-selection))
3741 (org-add-hook 'before-change-functions
3742 'org-table-remove-rectangle-highlight)
3743 (if (eq what 'name) (setq var (substring match 1)))
3744 (when (eq what 'range)
3745 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3746 (setq match (org-table-formula-substitute-names match)))
3747 (unless local
3748 (save-excursion
3749 (end-of-line 1)
3750 (re-search-backward "^\\S-" nil t)
3751 (beginning-of-line 1)
3752 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3753 (setq dest
3754 (save-match-data
3755 (org-table-convert-refs-to-rc (match-string 1))))
3756 (org-table-add-rectangle-overlay
3757 (match-beginning 1) (match-end 1) face2))))
3758 (if (and (markerp pos) (marker-buffer pos))
3759 (if (get-buffer-window (marker-buffer pos))
3760 (select-window (get-buffer-window (marker-buffer pos)))
3761 (org-switch-to-buffer-other-window (get-buffer-window
3762 (marker-buffer pos)))))
3763 (goto-char pos)
3764 (org-table-force-dataline)
3765 (when dest
3766 (setq name (substring dest 1))
3767 (cond
3768 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3769 (setq e (assoc name org-table-named-field-locations))
3770 (org-goto-line (nth 1 e))
3771 (org-table-goto-column (nth 2 e)))
3772 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3773 (let ((l (string-to-number (match-string 1 dest)))
3774 (c (string-to-number (match-string 2 dest))))
3775 (org-goto-line (aref org-table-dlines l))
3776 (org-table-goto-column c)))
3777 (t (org-table-goto-column (string-to-number name))))
3778 (move-marker pos (point))
3779 (org-table-highlight-rectangle nil nil face2))
3780 (cond
3781 ((equal dest match))
3782 ((not match))
3783 ((eq what 'range)
3784 (condition-case nil
3785 (save-excursion
3786 (org-table-get-range match nil nil 'highlight))
3787 (error nil)))
3788 ((setq e (assoc var org-table-named-field-locations))
3789 (org-goto-line (nth 1 e))
3790 (org-table-goto-column (nth 2 e))
3791 (org-table-highlight-rectangle (point) (point))
3792 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3793 ((setq e (assoc var org-table-column-names))
3794 (org-table-goto-column (string-to-number (cdr e)))
3795 (org-table-highlight-rectangle (point) (point))
3796 (goto-char (org-table-begin))
3797 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3798 (org-table-end) t)
3799 (progn
3800 (goto-char (match-beginning 1))
3801 (org-table-highlight-rectangle)
3802 (message "Named column (column %s)" (cdr e)))
3803 (user-error "Column name not found")))
3804 ((eq what 'column)
3805 ;; column number
3806 (org-table-goto-column (string-to-number (substring match 1)))
3807 (org-table-highlight-rectangle (point) (point))
3808 (message "Column %s" (substring match 1)))
3809 ((setq e (assoc var org-table-local-parameters))
3810 (goto-char (org-table-begin))
3811 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3812 (progn
3813 (goto-char (match-beginning 1))
3814 (org-table-highlight-rectangle)
3815 (message "Local parameter."))
3816 (user-error "Parameter not found")))
3818 (cond
3819 ((not var) (user-error "No reference at point"))
3820 ((setq e (assoc var org-table-formula-constants-local))
3821 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3822 var (cdr e)))
3823 ((setq e (assoc var org-table-formula-constants))
3824 (message "Constant: $%s=%s in `org-table-formula-constants'."
3825 var (cdr e)))
3826 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3827 (message "Constant: $%s=%s, from `constants.el'%s."
3828 var e (format " (%s units)" constants-unit-system)))
3829 (t (user-error "Undefined name $%s" var)))))
3830 (goto-char pos)
3831 (when (and org-show-positions
3832 (not (memq this-command '(org-table-fedit-scroll
3833 org-table-fedit-scroll-down))))
3834 (push pos org-show-positions)
3835 (push org-table-current-begin-pos org-show-positions)
3836 (let ((min (apply 'min org-show-positions))
3837 (max (apply 'max org-show-positions)))
3838 (goto-char min) (recenter 0)
3839 (goto-char max)
3840 (or (pos-visible-in-window-p max) (recenter -1))))
3841 (select-window win))))
3843 (defun org-table-force-dataline ()
3844 "Make sure the cursor is in a dataline in a table."
3845 (unless (save-excursion
3846 (beginning-of-line 1)
3847 (looking-at org-table-dataline-regexp))
3848 (let* ((re org-table-dataline-regexp)
3849 (p1 (save-excursion (re-search-forward re nil 'move)))
3850 (p2 (save-excursion (re-search-backward re nil 'move))))
3851 (cond ((and p1 p2)
3852 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3853 p1 p2)))
3854 ((or p1 p2) (goto-char (or p1 p2)))
3855 (t (user-error "No table dataline around here"))))))
3857 (defun org-table-fedit-line-up ()
3858 "Move cursor one line up in the window showing the table."
3859 (interactive)
3860 (org-table-fedit-move 'previous-line))
3862 (defun org-table-fedit-line-down ()
3863 "Move cursor one line down in the window showing the table."
3864 (interactive)
3865 (org-table-fedit-move 'next-line))
3867 (defun org-table-fedit-move (command)
3868 "Move the cursor in the window showing the table.
3869 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3870 (let ((org-table-allow-automatic-line-recalculation nil)
3871 (pos org-pos) (win (selected-window)) p)
3872 (select-window (get-buffer-window (marker-buffer org-pos)))
3873 (setq p (point))
3874 (call-interactively command)
3875 (while (and (org-at-table-p)
3876 (org-at-table-hline-p))
3877 (call-interactively command))
3878 (or (org-at-table-p) (goto-char p))
3879 (move-marker pos (point))
3880 (select-window win)))
3882 (defun org-table-fedit-scroll (N)
3883 (interactive "p")
3884 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3885 (scroll-other-window N)))
3887 (defun org-table-fedit-scroll-down (N)
3888 (interactive "p")
3889 (org-table-fedit-scroll (- N)))
3891 (defvar org-table-rectangle-overlays nil)
3893 (defun org-table-add-rectangle-overlay (beg end &optional face)
3894 "Add a new overlay."
3895 (let ((ov (make-overlay beg end)))
3896 (overlay-put ov 'face (or face 'secondary-selection))
3897 (push ov org-table-rectangle-overlays)))
3899 (defun org-table-highlight-rectangle (&optional beg end face)
3900 "Highlight rectangular region in a table."
3901 (setq beg (or beg (point)) end (or end (point)))
3902 (let ((b (min beg end))
3903 (e (max beg end))
3904 l1 c1 l2 c2 tmp)
3905 (and (boundp 'org-show-positions)
3906 (setq org-show-positions (cons b (cons e org-show-positions))))
3907 (goto-char (min beg end))
3908 (setq l1 (org-current-line)
3909 c1 (org-table-current-column))
3910 (goto-char (max beg end))
3911 (setq l2 (org-current-line)
3912 c2 (org-table-current-column))
3913 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3914 (org-goto-line l1)
3915 (beginning-of-line 1)
3916 (loop for line from l1 to l2 do
3917 (when (looking-at org-table-dataline-regexp)
3918 (org-table-goto-column c1)
3919 (skip-chars-backward "^|\n") (setq beg (point))
3920 (org-table-goto-column c2)
3921 (skip-chars-forward "^|\n") (setq end (point))
3922 (org-table-add-rectangle-overlay beg end face))
3923 (beginning-of-line 2))
3924 (goto-char b))
3925 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3927 (defun org-table-remove-rectangle-highlight (&rest ignore)
3928 "Remove the rectangle overlays."
3929 (unless org-inhibit-highlight-removal
3930 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3931 (mapc 'delete-overlay org-table-rectangle-overlays)
3932 (setq org-table-rectangle-overlays nil)))
3934 (defvar org-table-coordinate-overlays nil
3935 "Collects the coordinate grid overlays, so that they can be removed.")
3936 (make-variable-buffer-local 'org-table-coordinate-overlays)
3938 (defun org-table-overlay-coordinates ()
3939 "Add overlays to the table at point, to show row/column coordinates."
3940 (interactive)
3941 (mapc 'delete-overlay org-table-coordinate-overlays)
3942 (setq org-table-coordinate-overlays nil)
3943 (save-excursion
3944 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3945 (goto-char (org-table-begin))
3946 (while (org-at-table-p)
3947 (setq eol (point-at-eol))
3948 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3949 (push ov org-table-coordinate-overlays)
3950 (setq hline (looking-at org-table-hline-regexp))
3951 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3952 (format "%4d" (setq id (1+ id)))))
3953 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3954 (when hline
3955 (setq ic 0)
3956 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3957 (setq beg (1+ (match-beginning 0))
3958 ic (1+ ic)
3959 s1 (concat "$" (int-to-string ic))
3960 s2 (org-number-to-letters ic)
3961 str (if (eq org-table-use-standard-references t) s2 s1))
3962 (setq ov (make-overlay beg (+ beg (length str))))
3963 (push ov org-table-coordinate-overlays)
3964 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3965 (beginning-of-line 2)))))
3967 ;;;###autoload
3968 (defun org-table-toggle-coordinate-overlays ()
3969 "Toggle the display of Row/Column numbers in tables."
3970 (interactive)
3971 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3972 (message "Tables Row/Column numbers display turned %s"
3973 (if org-table-overlay-coordinates "on" "off"))
3974 (if (and (org-at-table-p) org-table-overlay-coordinates)
3975 (org-table-align))
3976 (unless org-table-overlay-coordinates
3977 (mapc 'delete-overlay org-table-coordinate-overlays)
3978 (setq org-table-coordinate-overlays nil)))
3980 ;;;###autoload
3981 (defun org-table-toggle-formula-debugger ()
3982 "Toggle the formula debugger in tables."
3983 (interactive)
3984 (setq org-table-formula-debug (not org-table-formula-debug))
3985 (message "Formula debugging has been turned %s"
3986 (if org-table-formula-debug "on" "off")))
3988 ;;; The orgtbl minor mode
3990 ;; Define a minor mode which can be used in other modes in order to
3991 ;; integrate the org-mode table editor.
3993 ;; This is really a hack, because the org-mode table editor uses several
3994 ;; keys which normally belong to the major mode, for example the TAB and
3995 ;; RET keys. Here is how it works: The minor mode defines all the keys
3996 ;; necessary to operate the table editor, but wraps the commands into a
3997 ;; function which tests if the cursor is currently inside a table. If that
3998 ;; is the case, the table editor command is executed. However, when any of
3999 ;; those keys is used outside a table, the function uses `key-binding' to
4000 ;; look up if the key has an associated command in another currently active
4001 ;; keymap (minor modes, major mode, global), and executes that command.
4002 ;; There might be problems if any of the keys used by the table editor is
4003 ;; otherwise used as a prefix key.
4005 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4006 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4007 ;; addresses this by checking explicitly for both bindings.
4009 ;; The optimized version (see variable `orgtbl-optimized') takes over
4010 ;; all keys which are bound to `self-insert-command' in the *global map*.
4011 ;; Some modes bind other commands to simple characters, for example
4012 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4013 ;; active, this binding is ignored inside tables and replaced with a
4014 ;; modified self-insert.
4017 (defvar orgtbl-mode-map (make-keymap)
4018 "Keymap for `orgtbl-mode'.")
4020 (defvar org-old-auto-fill-inhibit-regexp nil
4021 "Local variable used by `orgtbl-mode'.")
4023 (defconst orgtbl-line-start-regexp
4024 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4025 "Matches a line belonging to an orgtbl.")
4027 (defconst orgtbl-extra-font-lock-keywords
4028 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4029 0 (quote 'org-table) 'prepend))
4030 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4032 ;; Install it as a minor mode.
4033 (put 'orgtbl-mode :included t)
4034 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4036 ;;;###autoload
4037 (define-minor-mode orgtbl-mode
4038 "The `org-mode' table editor as a minor mode for use in other modes."
4039 :lighter " OrgTbl" :keymap orgtbl-mode-map
4040 (org-load-modules-maybe)
4041 (cond
4042 ((derived-mode-p 'org-mode)
4043 ;; Exit without error, in case some hook functions calls this
4044 ;; by accident in org-mode.
4045 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4046 (orgtbl-mode
4047 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4048 ;; Make sure we are first in minor-mode-map-alist
4049 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4050 ;; FIXME: maybe it should use emulation-mode-map-alists?
4051 (and c (setq minor-mode-map-alist
4052 (cons c (delq c minor-mode-map-alist)))))
4053 (org-set-local (quote org-table-may-need-update) t)
4054 (org-add-hook 'before-change-functions 'org-before-change-function
4055 nil 'local)
4056 (org-set-local 'org-old-auto-fill-inhibit-regexp
4057 auto-fill-inhibit-regexp)
4058 (org-set-local 'auto-fill-inhibit-regexp
4059 (if auto-fill-inhibit-regexp
4060 (concat orgtbl-line-start-regexp "\\|"
4061 auto-fill-inhibit-regexp)
4062 orgtbl-line-start-regexp))
4063 (add-to-invisibility-spec '(org-cwidth))
4064 (when (fboundp 'font-lock-add-keywords)
4065 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4066 (org-restart-font-lock))
4067 (easy-menu-add orgtbl-mode-menu))
4069 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4070 (org-table-cleanup-narrow-column-properties)
4071 (org-remove-from-invisibility-spec '(org-cwidth))
4072 (remove-hook 'before-change-functions 'org-before-change-function t)
4073 (when (fboundp 'font-lock-remove-keywords)
4074 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4075 (org-restart-font-lock))
4076 (easy-menu-remove orgtbl-mode-menu)
4077 (force-mode-line-update 'all))))
4079 (defun org-table-cleanup-narrow-column-properties ()
4080 "Remove all properties related to narrow-column invisibility."
4081 (let ((s (point-min)))
4082 (while (setq s (text-property-any s (point-max)
4083 'display org-narrow-column-arrow))
4084 (remove-text-properties s (1+ s) '(display t)))
4085 (setq s (point-min))
4086 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4087 (remove-text-properties s (1+ s) '(org-cwidth t)))
4088 (setq s (point-min))
4089 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4090 (remove-text-properties s (1+ s) '(invisible t)))))
4092 (defun orgtbl-make-binding (fun n &rest keys)
4093 "Create a function for binding in the table minor mode.
4094 FUN is the command to call inside a table. N is used to create a unique
4095 command name. KEYS are keys that should be checked in for a command
4096 to execute outside of tables."
4097 (eval
4098 (list 'defun
4099 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4100 '(arg)
4101 (concat "In tables, run `" (symbol-name fun) "'.\n"
4102 "Outside of tables, run the binding of `"
4103 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
4104 "'.")
4105 '(interactive "p")
4106 (list 'if
4107 '(org-at-table-p)
4108 (list 'call-interactively (list 'quote fun))
4109 (list 'let '(orgtbl-mode)
4110 (list 'call-interactively
4111 (append '(or)
4112 (mapcar (lambda (k)
4113 (list 'key-binding k))
4114 keys)
4115 '('orgtbl-error))))))))
4117 (defun orgtbl-error ()
4118 "Error when there is no default binding for a table key."
4119 (interactive)
4120 (user-error "This key has no function outside tables"))
4122 (defun orgtbl-setup ()
4123 "Setup orgtbl keymaps."
4124 (let ((nfunc 0)
4125 (bindings
4126 '(([(meta shift left)] org-table-delete-column)
4127 ([(meta left)] org-table-move-column-left)
4128 ([(meta right)] org-table-move-column-right)
4129 ([(meta shift right)] org-table-insert-column)
4130 ([(meta shift up)] org-table-kill-row)
4131 ([(meta shift down)] org-table-insert-row)
4132 ([(meta up)] org-table-move-row-up)
4133 ([(meta down)] org-table-move-row-down)
4134 ("\C-c\C-w" org-table-cut-region)
4135 ("\C-c\M-w" org-table-copy-region)
4136 ("\C-c\C-y" org-table-paste-rectangle)
4137 ("\C-c\C-w" org-table-wrap-region)
4138 ("\C-c-" org-table-insert-hline)
4139 ("\C-c}" org-table-toggle-coordinate-overlays)
4140 ("\C-c{" org-table-toggle-formula-debugger)
4141 ("\C-m" org-table-next-row)
4142 ([(shift return)] org-table-copy-down)
4143 ("\C-c?" org-table-field-info)
4144 ("\C-c " org-table-blank-field)
4145 ("\C-c+" org-table-sum)
4146 ("\C-c=" org-table-eval-formula)
4147 ("\C-c'" org-table-edit-formulas)
4148 ("\C-c`" org-table-edit-field)
4149 ("\C-c*" org-table-recalculate)
4150 ("\C-c^" org-table-sort-lines)
4151 ("\M-a" org-table-beginning-of-field)
4152 ("\M-e" org-table-end-of-field)
4153 ([(control ?#)] org-table-rotate-recalc-marks)))
4154 elt key fun cmd)
4155 (while (setq elt (pop bindings))
4156 (setq nfunc (1+ nfunc))
4157 (setq key (org-key (car elt))
4158 fun (nth 1 elt)
4159 cmd (orgtbl-make-binding fun nfunc key))
4160 (org-defkey orgtbl-mode-map key cmd))
4162 ;; Special treatment needed for TAB and RET
4163 (org-defkey orgtbl-mode-map [(return)]
4164 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4165 (org-defkey orgtbl-mode-map "\C-m"
4166 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4168 (org-defkey orgtbl-mode-map [(tab)]
4169 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4170 (org-defkey orgtbl-mode-map "\C-i"
4171 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4173 (org-defkey orgtbl-mode-map [(shift tab)]
4174 (orgtbl-make-binding 'org-table-previous-field 104
4175 [(shift tab)] [(tab)] "\C-i"))
4178 (unless (featurep 'xemacs)
4179 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4180 (orgtbl-make-binding 'org-table-previous-field 107
4181 [S-iso-lefttab] [backtab] [(shift tab)]
4182 [(tab)] "\C-i")))
4184 (org-defkey orgtbl-mode-map [backtab]
4185 (orgtbl-make-binding 'org-table-previous-field 108
4186 [backtab] [S-iso-lefttab] [(shift tab)]
4187 [(tab)] "\C-i"))
4189 (org-defkey orgtbl-mode-map "\M-\C-m"
4190 (orgtbl-make-binding 'org-table-wrap-region 105
4191 "\M-\C-m" [(meta return)]))
4192 (org-defkey orgtbl-mode-map [(meta return)]
4193 (orgtbl-make-binding 'org-table-wrap-region 106
4194 [(meta return)] "\M-\C-m"))
4196 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4197 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4199 (when orgtbl-optimized
4200 ;; If the user wants maximum table support, we need to hijack
4201 ;; some standard editing functions
4202 (org-remap orgtbl-mode-map
4203 'self-insert-command 'orgtbl-self-insert-command
4204 'delete-char 'org-delete-char
4205 'delete-backward-char 'org-delete-backward-char)
4206 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4207 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4208 '("OrgTbl"
4209 ["Create or convert" org-table-create-or-convert-from-region
4210 :active (not (org-at-table-p)) :keys "C-c |" ]
4211 "--"
4212 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4213 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4214 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4215 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4216 "--"
4217 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4218 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4219 ["Copy Field from Above"
4220 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4221 "--"
4222 ("Column"
4223 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4224 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4225 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4226 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4227 ("Row"
4228 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4229 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4230 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4231 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4232 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4233 "--"
4234 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4235 ("Rectangle"
4236 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4237 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4238 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4239 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4240 "--"
4241 ("Radio tables"
4242 ["Insert table template" orgtbl-insert-radio-table
4243 (assq major-mode orgtbl-radio-table-templates)]
4244 ["Comment/uncomment table" orgtbl-toggle-comment t])
4245 "--"
4246 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4247 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4248 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4249 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4250 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4251 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4252 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4253 ["Sum Column/Rectangle" org-table-sum
4254 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4255 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4256 ["Debug Formulas"
4257 org-table-toggle-formula-debugger :active (org-at-table-p)
4258 :keys "C-c {"
4259 :style toggle :selected org-table-formula-debug]
4260 ["Show Col/Row Numbers"
4261 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4262 :keys "C-c }"
4263 :style toggle :selected org-table-overlay-coordinates]
4267 (defun orgtbl-ctrl-c-ctrl-c (arg)
4268 "If the cursor is inside a table, realign the table.
4269 If it is a table to be sent away to a receiver, do it.
4270 With prefix arg, also recompute table."
4271 (interactive "P")
4272 (let ((case-fold-search t) (pos (point)) action)
4273 (save-excursion
4274 (beginning-of-line 1)
4275 (setq action (cond
4276 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4277 ((looking-at "[ \t]*|") pos)
4278 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4279 (cond
4280 ((integerp action)
4281 (goto-char action)
4282 (org-table-maybe-eval-formula)
4283 (if arg
4284 (call-interactively 'org-table-recalculate)
4285 (org-table-maybe-recalculate-line))
4286 (call-interactively 'org-table-align)
4287 (when (orgtbl-send-table 'maybe)
4288 (run-hooks 'orgtbl-after-send-table-hook)))
4289 ((eq action 'recalc)
4290 (org-table-set-constants)
4291 (save-excursion
4292 (beginning-of-line 1)
4293 (skip-chars-backward " \r\n\t")
4294 (if (org-at-table-p)
4295 (org-call-with-arg 'org-table-recalculate t))))
4296 (t (let (orgtbl-mode)
4297 (call-interactively (key-binding "\C-c\C-c")))))))
4299 (defun orgtbl-create-or-convert-from-region (arg)
4300 "Create table or convert region to table, if no conflicting binding.
4301 This installs the table binding `C-c |', but only if there is no
4302 conflicting binding to this key outside orgtbl-mode."
4303 (interactive "P")
4304 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4305 (if cmd
4306 (call-interactively cmd)
4307 (call-interactively 'org-table-create-or-convert-from-region))))
4309 (defun orgtbl-tab (arg)
4310 "Justification and field motion for `orgtbl-mode'."
4311 (interactive "P")
4312 (if arg (org-table-edit-field t)
4313 (org-table-justify-field-maybe)
4314 (org-table-next-field)))
4316 (defun orgtbl-ret ()
4317 "Justification and field motion for `orgtbl-mode'."
4318 (interactive)
4319 (if (bobp)
4320 (newline)
4321 (org-table-justify-field-maybe)
4322 (org-table-next-row)))
4324 (defun orgtbl-self-insert-command (N)
4325 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4326 If the cursor is in a table looking at whitespace, the whitespace is
4327 overwritten, and the table is not marked as requiring realignment."
4328 (interactive "p")
4329 (if (and (org-at-table-p)
4331 (and org-table-auto-blank-field
4332 (member last-command
4333 '(orgtbl-hijacker-command-100
4334 orgtbl-hijacker-command-101
4335 orgtbl-hijacker-command-102
4336 orgtbl-hijacker-command-103
4337 orgtbl-hijacker-command-104
4338 orgtbl-hijacker-command-105
4339 yas/expand))
4340 (org-table-blank-field))
4342 (eq N 1)
4343 (looking-at "[^|\n]* +|"))
4344 (let (org-table-may-need-update)
4345 (goto-char (1- (match-end 0)))
4346 (org-delete-backward-char 1)
4347 (goto-char (match-beginning 0))
4348 (self-insert-command N))
4349 (setq org-table-may-need-update t)
4350 (let* (orgtbl-mode
4352 (cmd (or (key-binding
4353 (or (and (listp function-key-map)
4354 (setq a (assoc last-input-event function-key-map))
4355 (cdr a))
4356 (vector last-input-event)))
4357 'self-insert-command)))
4358 (call-interactively cmd)
4359 (if (and org-self-insert-cluster-for-undo
4360 (eq cmd 'self-insert-command))
4361 (if (not (eq last-command 'orgtbl-self-insert-command))
4362 (setq org-self-insert-command-undo-counter 1)
4363 (if (>= org-self-insert-command-undo-counter 20)
4364 (setq org-self-insert-command-undo-counter 1)
4365 (and (> org-self-insert-command-undo-counter 0)
4366 buffer-undo-list
4367 (not (cadr buffer-undo-list)) ; remove nil entry
4368 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4369 (setq org-self-insert-command-undo-counter
4370 (1+ org-self-insert-command-undo-counter))))))))
4372 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4373 "Regular expression matching exponentials as produced by calc.")
4375 (defun orgtbl-gather-send-defs ()
4376 "Gather a plist of :name, :transform, :params for each destination before
4377 a radio table."
4378 (save-excursion
4379 (goto-char (org-table-begin))
4380 (let (rtn)
4381 (beginning-of-line 0)
4382 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4383 (let ((name (org-no-properties (match-string 1)))
4384 (transform (intern (match-string 2)))
4385 (params (if (match-end 3)
4386 (read (concat "(" (match-string 3) ")")))))
4387 (push (list :name name :transform transform :params params)
4388 rtn)
4389 (beginning-of-line 0)))
4390 rtn)))
4392 (defun orgtbl-send-replace-tbl (name txt)
4393 "Find and replace table NAME with TXT."
4394 (save-excursion
4395 (goto-char (point-min))
4396 (unless (re-search-forward
4397 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4398 (user-error "Don't know where to insert translated table"))
4399 (goto-char (match-beginning 0))
4400 (beginning-of-line 2)
4401 (save-excursion
4402 (let ((beg (point)))
4403 (unless (re-search-forward
4404 (concat "END RECEIVE ORGTBL +" name) nil t)
4405 (user-error "Cannot find end of insertion region"))
4406 (beginning-of-line 1)
4407 (delete-region beg (point))))
4408 (insert txt "\n")))
4410 ;;;###autoload
4411 (defun org-table-to-lisp (&optional txt)
4412 "Convert the table at point to a Lisp structure.
4413 The structure will be a list. Each item is either the symbol `hline'
4414 for a horizontal separator line, or a list of field values as strings.
4415 The table is taken from the parameter TXT, or from the buffer at point."
4416 (unless txt
4417 (unless (org-at-table-p)
4418 (user-error "No table at point")))
4419 (let* ((txt (or txt
4420 (buffer-substring-no-properties (org-table-begin)
4421 (org-table-end))))
4422 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4424 (mapcar
4425 (lambda (x)
4426 (if (string-match org-table-hline-regexp x)
4427 'hline
4428 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4429 lines)))
4431 (defun orgtbl-send-table (&optional maybe)
4432 "Send a transformed version of this table to the receiver position.
4433 With argument MAYBE, fail quietly if no transformation is defined for
4434 this table."
4435 (interactive)
4436 (catch 'exit
4437 (unless (org-at-table-p) (user-error "Not at a table"))
4438 ;; when non-interactive, we assume align has just happened.
4439 (when (org-called-interactively-p 'any) (org-table-align))
4440 (let ((dests (orgtbl-gather-send-defs))
4441 (txt (buffer-substring-no-properties (org-table-begin)
4442 (org-table-end)))
4443 (ntbl 0))
4444 (unless dests (if maybe (throw 'exit nil)
4445 (user-error "Don't know how to transform this table")))
4446 (dolist (dest dests)
4447 (let* ((name (plist-get dest :name))
4448 (transform (plist-get dest :transform))
4449 (params (plist-get dest :params))
4450 (skip (plist-get params :skip))
4451 (skipcols (plist-get params :skipcols))
4452 (no-escape (plist-get params :no-escape))
4454 (lines (org-table-clean-before-export
4455 (nthcdr (or skip 0)
4456 (org-split-string txt "[ \t]*\n[ \t]*"))))
4457 (i0 (if org-table-clean-did-remove-column 2 1))
4458 (lines (if no-escape lines
4459 (mapcar (lambda(l) (replace-regexp-in-string
4460 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4461 (table (mapcar
4462 (lambda (x)
4463 (if (string-match org-table-hline-regexp x)
4464 'hline
4465 (org-remove-by-index
4466 (org-split-string (org-trim x) "\\s-*|\\s-*")
4467 skipcols i0)))
4468 lines))
4469 (fun (if (= i0 2) 'cdr 'identity))
4470 (org-table-last-alignment
4471 (org-remove-by-index (funcall fun org-table-last-alignment)
4472 skipcols i0))
4473 (org-table-last-column-widths
4474 (org-remove-by-index (funcall fun org-table-last-column-widths)
4475 skipcols i0))
4476 (txt (if (fboundp transform)
4477 (funcall transform table params)
4478 (user-error "No such transformation function %s" transform))))
4479 (orgtbl-send-replace-tbl name txt))
4480 (setq ntbl (1+ ntbl)))
4481 (message "Table converted and installed at %d receiver location%s"
4482 ntbl (if (> ntbl 1) "s" ""))
4483 (if (> ntbl 0)
4484 ntbl
4485 nil))))
4487 (defun org-remove-by-index (list indices &optional i0)
4488 "Remove the elements in LIST with indices in INDICES.
4489 First element has index 0, or I0 if given."
4490 (if (not indices)
4491 list
4492 (if (integerp indices) (setq indices (list indices)))
4493 (setq i0 (1- (or i0 0)))
4494 (delq :rm (mapcar (lambda (x)
4495 (setq i0 (1+ i0))
4496 (if (memq i0 indices) :rm x))
4497 list))))
4499 (defun orgtbl-toggle-comment ()
4500 "Comment or uncomment the orgtbl at point."
4501 (interactive)
4502 (let* ((case-fold-search t)
4503 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4504 (re2 (concat "^" orgtbl-line-start-regexp))
4505 (commented (save-excursion (beginning-of-line 1)
4506 (cond ((looking-at re1) t)
4507 ((looking-at re2) nil)
4508 (t (user-error "Not at an org table")))))
4509 (re (if commented re1 re2))
4510 beg end)
4511 (save-excursion
4512 (beginning-of-line 1)
4513 (while (looking-at re) (beginning-of-line 0))
4514 (beginning-of-line 2)
4515 (setq beg (point))
4516 (while (looking-at re) (beginning-of-line 2))
4517 (setq end (point)))
4518 (comment-region beg end (if commented '(4) nil))))
4520 (defun orgtbl-insert-radio-table ()
4521 "Insert a radio table template appropriate for this major mode."
4522 (interactive)
4523 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4524 (txt (nth 1 e))
4525 name pos)
4526 (unless e (user-error "No radio table setup defined for %s" major-mode))
4527 (setq name (read-string "Table name: "))
4528 (while (string-match "%n" txt)
4529 (setq txt (replace-match name t t txt)))
4530 (or (bolp) (insert "\n"))
4531 (setq pos (point))
4532 (insert txt)
4533 (goto-char pos)))
4535 ;; Dynamically bound input and output for table formatting.
4536 (defvar *orgtbl-table* nil
4537 "Carries the current table through formatting routines.")
4538 (defvar *orgtbl-rtn* nil
4539 "Formatting routines push the output lines here.")
4540 ;; Formatting parameters for the current table section.
4541 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4542 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4543 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4544 (defvar *orgtbl-fmt* nil "Format for each entry.")
4545 (defvar *orgtbl-efmt* nil "Format for numbers.")
4546 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4547 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4548 (defvar *orgtbl-lstart* nil "Text starting a row.")
4549 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4550 (defvar *orgtbl-lend* nil "Text ending a row.")
4551 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4553 (defsubst orgtbl-get-fmt (fmt i)
4554 "Retrieve the format from FMT corresponding to the Ith column."
4555 (if (and (not (functionp fmt)) (consp fmt))
4556 (plist-get fmt i)
4557 fmt))
4559 (defsubst orgtbl-apply-fmt (fmt &rest args)
4560 "Apply format FMT to arguments ARGS.
4561 When FMT is nil, return the first argument from ARGS."
4562 (cond ((functionp fmt) (apply fmt args))
4563 (fmt (apply 'format fmt args))
4564 (args (car args))
4565 (t args)))
4567 (defsubst orgtbl-eval-str (str)
4568 "If STR is a function, evaluate it with no arguments."
4569 (if (functionp str)
4570 (funcall str)
4571 str))
4573 (defun orgtbl-format-line (line)
4574 "Format LINE as a table row."
4575 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4576 (let* ((i 0)
4577 (line
4578 (mapcar
4579 (lambda (f)
4580 (setq i (1+ i))
4581 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4582 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4583 (orgtbl-apply-fmt efmt (match-string 1 f)
4584 (match-string 2 f))
4585 f)))
4586 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4587 *orgtbl-default-fmt*)
4588 f)))
4589 line)))
4590 (push (if *orgtbl-lfmt*
4591 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4592 (concat (orgtbl-eval-str *orgtbl-lstart*)
4593 (mapconcat 'identity line *orgtbl-sep*)
4594 (orgtbl-eval-str *orgtbl-lend*)))
4595 *orgtbl-rtn*))))
4597 (defun orgtbl-format-section (section-stopper)
4598 "Format lines until the first occurrence of SECTION-STOPPER."
4599 (let (prevline)
4600 (progn
4601 (while (not (eq (car *orgtbl-table*) section-stopper))
4602 (if prevline (orgtbl-format-line prevline))
4603 (setq prevline (pop *orgtbl-table*)))
4604 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4605 (*orgtbl-lend* *orgtbl-llend*)
4606 (*orgtbl-lfmt* *orgtbl-llfmt*))
4607 (orgtbl-format-line prevline))))))
4609 ;;;###autoload
4610 (defun orgtbl-to-generic (table params &optional backend)
4611 "Convert the orgtbl-mode TABLE to some other format.
4612 This generic routine can be used for many standard cases.
4613 TABLE is a list, each entry either the symbol `hline' for a horizontal
4614 separator line, or a list of fields for that line.
4615 PARAMS is a property list of parameters that can influence the conversion.
4616 A third optional argument BACKEND can be used to convert the content of
4617 the cells using a specific export back-end.
4619 For the generic converter, some parameters are obligatory: you need to
4620 specify either :lfmt, or all of (:lstart :lend :sep).
4622 Valid parameters are:
4624 :splice When set to t, return only table body lines, don't wrap
4625 them into :tstart and :tend. Default is nil. When :splice
4626 is non-nil, this also means that the exporter should not look
4627 for and interpret header and footer sections.
4629 :hline String to be inserted on horizontal separation lines.
4630 May be nil to ignore hlines.
4632 :sep Separator between two fields
4633 :remove-nil-lines Do not include lines that evaluate to nil.
4635 Each in the following group may be either a string or a function
4636 of no arguments returning a string:
4638 :tstart String to start the table. Ignored when :splice is t.
4639 :tend String to end the table. Ignored when :splice is t.
4640 :lstart String to start a new table line.
4641 :llstart String to start the last table line, defaults to :lstart.
4642 :lend String to end a table line
4643 :llend String to end the last table line, defaults to :lend.
4645 Each in the following group may be a string, a function of one
4646 argument (the field or line) returning a string, or a plist
4647 mapping columns to either of the above:
4649 :lfmt Format for entire line, with enough %s to capture all fields.
4650 If this is present, :lstart, :lend, and :sep are ignored.
4651 :llfmt Format for the entire last line, defaults to :lfmt.
4652 :fmt A format to be used to wrap the field, should contain
4653 %s for the original field value. For example, to wrap
4654 everything in dollars, you could use :fmt \"$%s$\".
4655 This may also be a property list with column numbers and
4656 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4657 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4658 Same as above, specific for the header lines in the table.
4659 All lines before the first hline are treated as header.
4660 If any of these is not present, the data line value is used.
4662 This may be either a string or a function of two arguments:
4664 :efmt Use this format to print numbers with exponentials.
4665 The format should have %s twice for inserting mantissa
4666 and exponent, for example \"%s\\\\times10^{%s}\". This
4667 may also be a property list with column numbers and
4668 formats. :fmt will still be applied after :efmt.
4670 In addition to this, the parameters :skip and :skipcols are always handled
4671 directly by `orgtbl-send-table'. See manual."
4672 (let* ((splicep (plist-get params :splice))
4673 (hline (plist-get params :hline))
4674 (skipheadrule (plist-get params :skipheadrule))
4675 (remove-nil-linesp (plist-get params :remove-nil-lines))
4676 (remove-newlines (plist-get params :remove-newlines))
4677 (*orgtbl-hline* hline)
4678 (*orgtbl-table* table)
4679 (*orgtbl-sep* (plist-get params :sep))
4680 (*orgtbl-efmt* (plist-get params :efmt))
4681 (*orgtbl-lstart* (plist-get params :lstart))
4682 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4683 (*orgtbl-lend* (plist-get params :lend))
4684 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4685 (*orgtbl-lfmt* (plist-get params :lfmt))
4686 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4687 (*orgtbl-fmt* (plist-get params :fmt))
4688 *orgtbl-rtn*)
4689 ;; Convert cells content to backend BACKEND
4690 (when backend
4691 (setq *orgtbl-table*
4692 (mapcar
4693 (lambda(r)
4694 (if (listp r)
4695 (mapcar
4696 (lambda (c)
4697 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4700 *orgtbl-table*)))
4701 ;; Put header
4702 (unless splicep
4703 (when (plist-member params :tstart)
4704 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4705 (if tstart (push tstart *orgtbl-rtn*)))))
4706 ;; If we have a heading, format it and handle the trailing hline.
4707 (if (and (not splicep)
4708 (or (consp (car *orgtbl-table*))
4709 (consp (nth 1 *orgtbl-table*)))
4710 (memq 'hline (cdr *orgtbl-table*)))
4711 (progn
4712 (when (eq 'hline (car *orgtbl-table*))
4713 ;; There is a hline before the first data line
4714 (and hline (push hline *orgtbl-rtn*))
4715 (pop *orgtbl-table*))
4716 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4717 *orgtbl-lstart*))
4718 (*orgtbl-llstart* (or (plist-get params :hllstart)
4719 *orgtbl-llstart*))
4720 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4721 (*orgtbl-llend* (or (plist-get params :hllend)
4722 (plist-get params :hlend) *orgtbl-llend*))
4723 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4724 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4725 (plist-get params :hlfmt) *orgtbl-llfmt*))
4726 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4727 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4728 (orgtbl-format-section 'hline))
4729 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4730 (pop *orgtbl-table*)))
4731 ;; Now format the main section.
4732 (orgtbl-format-section nil)
4733 (unless splicep
4734 (when (plist-member params :tend)
4735 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4736 (if tend (push tend *orgtbl-rtn*)))))
4737 (mapconcat (if remove-newlines
4738 (lambda (tend)
4739 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4740 'identity)
4741 (nreverse (if remove-nil-linesp
4742 (remq nil *orgtbl-rtn*)
4743 *orgtbl-rtn*)) "\n")))
4745 ;;;###autoload
4746 (defun orgtbl-to-tsv (table params)
4747 "Convert the orgtbl-mode table to TAB separated material."
4748 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4749 ;;;###autoload
4750 (defun orgtbl-to-csv (table params)
4751 "Convert the orgtbl-mode table to CSV material.
4752 This does take care of the proper quoting of fields with comma or quotes."
4753 (orgtbl-to-generic table (org-combine-plists
4754 '(:sep "," :fmt org-quote-csv-field)
4755 params)))
4757 ;;;###autoload
4758 (defun orgtbl-to-latex (table params)
4759 "Convert the orgtbl-mode TABLE to LaTeX.
4760 TABLE is a list, each entry either the symbol `hline' for a horizontal
4761 separator line, or a list of fields for that line.
4762 PARAMS is a property list of parameters that can influence the conversion.
4763 Supports all parameters from `orgtbl-to-generic'. Most important for
4764 LaTeX are:
4766 :splice When set to t, return only table body lines, don't wrap
4767 them into a tabular environment. Default is nil.
4769 :fmt A format to be used to wrap the field, should contain %s for the
4770 original field value. For example, to wrap everything in dollars,
4771 use :fmt \"$%s$\". This may also be a property list with column
4772 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4773 The format may also be a function that formats its one argument.
4775 :efmt Format for transforming numbers with exponentials. The format
4776 should have %s twice for inserting mantissa and exponent, for
4777 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4778 This may also be a property list with column numbers and formats.
4779 The format may also be a function that formats its two arguments.
4781 :llend If you find too much space below the last line of a table,
4782 pass a value of \"\" for :llend to suppress the final \\\\.
4784 The general parameters :skip and :skipcols have already been applied when
4785 this function is called."
4786 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4787 org-table-last-alignment ""))
4788 (params2
4789 (list
4790 :tstart (concat "\\begin{tabular}{" alignment "}")
4791 :tend "\\end{tabular}"
4792 :lstart "" :lend " \\\\" :sep " & "
4793 :efmt "%s\\,(%s)" :hline "\\hline")))
4794 (require 'ox-latex)
4795 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4797 ;;;###autoload
4798 (defun orgtbl-to-html (table params)
4799 "Convert the orgtbl-mode TABLE to HTML.
4800 TABLE is a list, each entry either the symbol `hline' for a horizontal
4801 separator line, or a list of fields for that line.
4802 PARAMS is a property list of parameters that can influence the conversion.
4803 Currently this function recognizes the following parameters:
4805 :splice When set to t, return only table body lines, don't wrap
4806 them into a <table> environment. Default is nil.
4808 The general parameters :skip and :skipcols have already been applied when
4809 this function is called. The function does *not* use `orgtbl-to-generic',
4810 so you cannot specify parameters for it."
4811 (require 'ox-html)
4812 (let ((output (org-export-string-as
4813 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4814 (if (not (plist-get params :splice)) output
4815 (org-trim
4816 (replace-regexp-in-string
4817 "\\`<table .*>\n" ""
4818 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4820 ;;;###autoload
4821 (defun orgtbl-to-texinfo (table params)
4822 "Convert the orgtbl-mode TABLE to TeXInfo.
4823 TABLE is a list, each entry either the symbol `hline' for a horizontal
4824 separator line, or a list of fields for that line.
4825 PARAMS is a property list of parameters that can influence the conversion.
4826 Supports all parameters from `orgtbl-to-generic'. Most important for
4827 TeXInfo are:
4829 :splice nil/t When set to t, return only table body lines, don't wrap
4830 them into a multitable environment. Default is nil.
4832 :fmt fmt A format to be used to wrap the field, should contain
4833 %s for the original field value. For example, to wrap
4834 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4835 This may also be a property list with column numbers and
4836 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4837 Each format also may be a function that formats its one
4838 argument.
4840 :cf \"f1 f2..\" The column fractions for the table. By default these
4841 are computed automatically from the width of the columns
4842 under org-mode.
4844 The general parameters :skip and :skipcols have already been applied when
4845 this function is called."
4846 (let* ((total (float (apply '+ org-table-last-column-widths)))
4847 (colfrac (or (plist-get params :cf)
4848 (mapconcat
4849 (lambda (x) (format "%.3f" (/ (float x) total)))
4850 org-table-last-column-widths " ")))
4851 (params2
4852 (list
4853 :tstart (concat "@multitable @columnfractions " colfrac)
4854 :tend "@end multitable"
4855 :lstart "@item " :lend "" :sep " @tab "
4856 :hlstart "@headitem ")))
4857 (require 'ox-texinfo)
4858 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4860 ;;;###autoload
4861 (defun orgtbl-to-orgtbl (table params)
4862 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4863 Useful when slicing one table into many. The :hline, :sep,
4864 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4865 and :tend suppress strings without splicing; they can be set to
4866 provide ORGTBL directives for the generated table."
4867 (let* ((params2
4868 (list
4869 :remove-newlines t
4870 :tstart nil :tend nil
4871 :hline "|---"
4872 :sep " | "
4873 :lstart "| "
4874 :lend " |"))
4875 (params (org-combine-plists params2 params)))
4876 (with-temp-buffer
4877 (insert (orgtbl-to-generic table params))
4878 (goto-char (point-min))
4879 (while (re-search-forward org-table-hline-regexp nil t)
4880 (org-table-align))
4881 (buffer-substring 1 (buffer-size)))))
4883 (defun orgtbl-to-table.el (table params)
4884 "Convert the orgtbl-mode TABLE into a table.el table."
4885 (with-temp-buffer
4886 (insert (orgtbl-to-orgtbl table params))
4887 (org-table-align)
4888 (replace-regexp-in-string
4889 "-|" "-+"
4890 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4892 (defun orgtbl-to-unicode (table params)
4893 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4894 You need the ascii-art-to-unicode.el package for this. You can download
4895 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4896 (with-temp-buffer
4897 (insert (orgtbl-to-table.el table params))
4898 (goto-char (point-min))
4899 (if (or (featurep 'ascii-art-to-unicode)
4900 (require 'ascii-art-to-unicode nil t))
4901 (aa2u)
4902 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4903 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4904 "Link to ascii-art-to-unicode.el") org-stored-links))
4905 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4906 (buffer-string)))
4908 (defun org-table-get-remote-range (name-or-id form)
4909 "Get a field value or a list of values in a range from table at ID.
4911 NAME-OR-ID may be the name of a table in the current file as set
4912 by a \"#+NAME:\" directive. The first table following this line
4913 will then be used. Alternatively, it may be an ID referring to
4914 any entry, also in a different file. In this case, the first
4915 table in that entry will be referenced.
4916 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4917 \"@I$2..@II$2\". All the references must be absolute, not relative.
4919 The return value is either a single string for a single field, or a
4920 list of the fields in the rectangle."
4921 (save-match-data
4922 (let ((case-fold-search t) (id-loc nil)
4923 ;; Protect a bunch of variables from being overwritten
4924 ;; by the context of the remote table
4925 org-table-column-names org-table-column-name-regexp
4926 org-table-local-parameters org-table-named-field-locations
4927 org-table-current-line-types org-table-current-begin-line
4928 org-table-current-begin-pos org-table-dlines
4929 org-table-current-ncol
4930 org-table-hlines org-table-last-alignment
4931 org-table-last-column-widths org-table-last-alignment
4932 org-table-last-column-widths tbeg
4933 buffer loc)
4934 (setq form (org-table-convert-refs-to-rc form))
4935 (save-excursion
4936 (save-restriction
4937 (widen)
4938 (save-excursion
4939 (goto-char (point-min))
4940 (if (re-search-forward
4941 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
4942 (regexp-quote name-or-id) "[ \t]*$")
4943 nil t)
4944 (setq buffer (current-buffer) loc (match-beginning 0))
4945 (setq id-loc (org-id-find name-or-id 'marker))
4946 (unless (and id-loc (markerp id-loc))
4947 (user-error "Can't find remote table \"%s\"" name-or-id))
4948 (setq buffer (marker-buffer id-loc)
4949 loc (marker-position id-loc))
4950 (move-marker id-loc nil)))
4951 (with-current-buffer buffer
4952 (save-excursion
4953 (save-restriction
4954 (widen)
4955 (goto-char loc)
4956 (forward-char 1)
4957 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4958 (not (match-beginning 1)))
4959 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
4960 (setq tbeg (point-at-bol))
4961 (org-table-get-specials)
4962 (setq form (org-table-formula-substitute-names
4963 (org-table-formula-handle-first/last-rc form)))
4964 (if (and (string-match org-table-range-regexp form)
4965 (> (length (match-string 0 form)) 1))
4966 (save-match-data
4967 (org-table-get-range (match-string 0 form) tbeg 1))
4968 form)))))))))
4970 (defmacro org-define-lookup-function (mode)
4971 (let ((mode-str (symbol-name mode))
4972 (first-p (equal mode 'first))
4973 (all-p (equal mode 'all)))
4974 (let ((plural-str (if all-p "s" "")))
4975 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4976 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4977 If R-LIST is nil, return matching element%s of S-LIST.
4978 If PREDICATE is not nil, use it instead of `equal' to match VAL.
4979 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
4980 This function is generated by a call to the macro `org-define-lookup-function'."
4981 mode-str plural-str plural-str plural-str)
4982 (let ,(let ((lvars '((p (or predicate 'equal))
4983 (sl s-list)
4984 (rl (or r-list s-list))
4985 (ret nil))))
4986 (if first-p (add-to-list 'lvars '(match-p nil)))
4987 lvars)
4988 (while ,(if first-p '(and (not match-p) sl) 'sl)
4989 (progn
4990 (if (funcall p val (car sl))
4991 (progn
4992 ,(if first-p '(setq match-p t))
4993 (let ((rval (car rl)))
4994 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
4995 (setq sl (cdr sl) rl (cdr rl))))
4996 ret)))))
4998 (org-define-lookup-function first)
4999 (org-define-lookup-function last)
5000 (org-define-lookup-function all)
5002 (provide 'org-table)
5004 ;; Local variables:
5005 ;; generated-autoload-file: "org-loaddefs.el"
5006 ;; End:
5008 ;;; org-table.el ends here