Merge branch 'maint'
[org-mode.git] / lisp / org-table.el
blobcaa12ae70618bc73091c8af7adfdff239cc73642
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-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 "rP")
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-calc-current-TBLFM (&optional arg)
3148 "Apply the #+TBLFM in the line 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-TBLFM-begin))
3158 (setq s (set-marker (make-marker) (point)))
3159 (insert (concat formula "\n"))
3160 (setq e (set-marker (make-marker) (point)))
3162 ;; Recalculate the table
3163 (beginning-of-line 0) ; move to the inserted line
3164 (skip-chars-backward " \r\n\t")
3165 (if (org-at-table-p)
3166 (unwind-protect
3167 (org-call-with-arg 'org-table-recalculate (or arg t))
3169 ;; delete the formula inserted temporarily
3170 (delete-region s e))))))
3172 (defun org-TBLFM-begin ()
3173 "Find the beginning of the TBLFM lines and return its position.
3174 Return nil when the beginning of TBLFM line was not found."
3175 (save-excursion
3176 (when (progn (forward-line 1)
3177 (re-search-backward
3178 org-TBLFM-begin-regexp
3179 nil t))
3180 (point-at-bol 2))))
3184 (defun org-table-expand-lhs-ranges (equations)
3185 "Expand list of formulas.
3186 If some of the RHS in the formulas are ranges or a row reference, expand
3187 them to individual field equations for each field."
3188 (let (e res lhs rhs range r1 r2 c1 c2)
3189 (while (setq e (pop equations))
3190 (setq lhs (car e) rhs (cdr e))
3191 (cond
3192 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3193 ;; This just refers to one fixed field
3194 (push e res))
3195 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3196 ;; This just refers to one fixed named field
3197 (push e res))
3198 ((string-match "^@[0-9]+$" lhs)
3199 (loop for ic from 1 to org-table-current-ncol do
3200 (push (cons (format "%s$%d" lhs ic) rhs) res)
3201 (put-text-property 0 (length (caar res))
3202 :orig-eqn e (caar res))))
3204 (setq range (org-table-get-range lhs org-table-current-begin-pos
3205 1 nil 'corners))
3206 (setq r1 (nth 0 range) c1 (nth 1 range)
3207 r2 (nth 2 range) c2 (nth 3 range))
3208 (setq r1 (org-table-line-to-dline r1))
3209 (setq r2 (org-table-line-to-dline r2 'above))
3210 (loop for ir from r1 to r2 do
3211 (loop for ic from c1 to c2 do
3212 (push (cons (format "@%d$%d" ir ic) rhs) res)
3213 (put-text-property 0 (length (caar res))
3214 :orig-eqn e (caar res)))))))
3215 (nreverse res)))
3217 (defun org-table-formula-handle-first/last-rc (s)
3218 "Replace @<, @>, $<, $> with first/last row/column of the table.
3219 So @< and $< will always be replaced with @1 and $1, respectively.
3220 The advantage of these special markers are that structure editing of
3221 the table will not change them, while @1 and $1 will be modified
3222 when a line/row is swapped out of that privileged position. So for
3223 formulas that use a range of rows or columns, it may often be better
3224 to anchor the formula with \"I\" row markers, or to offset from the
3225 borders of the table using the @< @> $< $> makers."
3226 (let (n nmax len char (start 0))
3227 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3228 s start)
3229 (if (match-end 3)
3230 (setq start (match-end 3))
3231 (setq nmax (if (equal (match-string 1 s) "@")
3232 (1- (length org-table-dlines))
3233 org-table-current-ncol)
3234 len (- (match-end 2) (match-beginning 2))
3235 char (string-to-char (match-string 2 s))
3236 n (if (= char ?<)
3238 (- nmax len -1)))
3239 (if (or (< n 1) (> n nmax))
3240 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3241 (match-string 0 s) s))
3242 (setq start (match-beginning 0))
3243 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3246 (defun org-table-formula-substitute-names (f)
3247 "Replace $const with values in string F."
3248 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3249 ;; First, check for column names
3250 (while (setq start (string-match org-table-column-name-regexp f start))
3251 (setq start (1+ start))
3252 (setq a (assoc (match-string 1 f) org-table-column-names))
3253 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3254 ;; Parameters and constants
3255 (setq start 0)
3256 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3257 (if (match-end 2)
3258 (setq start (match-end 2))
3259 (setq start (1+ start))
3260 (if (setq a (save-match-data
3261 (org-table-get-constant (match-string 1 f))))
3262 (setq f (replace-match
3263 (concat (if pp "(") a (if pp ")")) t t f)))))
3264 (if org-table-formula-debug
3265 (put-text-property 0 (length f) :orig-formula f1 f))
3268 (defun org-table-get-constant (const)
3269 "Find the value for a parameter or constant in a formula.
3270 Parameters get priority."
3271 (or (cdr (assoc const org-table-local-parameters))
3272 (cdr (assoc const org-table-formula-constants-local))
3273 (cdr (assoc const org-table-formula-constants))
3274 (and (fboundp 'constants-get) (constants-get const))
3275 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3276 (org-entry-get nil (substring const 5) 'inherit))
3277 "#UNDEFINED_NAME"))
3279 (defvar org-table-fedit-map
3280 (let ((map (make-sparse-keymap)))
3281 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3282 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3283 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3284 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3285 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3286 (org-defkey map "\C-c?" 'org-table-show-reference)
3287 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3288 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3289 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3290 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3291 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3292 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3293 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3294 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3295 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3296 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3297 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3298 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3299 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3300 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3301 map))
3303 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3304 '("Edit-Formulas"
3305 ["Finish and Install" org-table-fedit-finish t]
3306 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3307 ["Abort" org-table-fedit-abort t]
3308 "--"
3309 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3310 ["Complete Lisp Symbol" lisp-complete-symbol t]
3311 "--"
3312 "Shift Reference at Point"
3313 ["Up" org-table-fedit-ref-up t]
3314 ["Down" org-table-fedit-ref-down t]
3315 ["Left" org-table-fedit-ref-left t]
3316 ["Right" org-table-fedit-ref-right t]
3318 "Change Test Row for Column Formulas"
3319 ["Up" org-table-fedit-line-up t]
3320 ["Down" org-table-fedit-line-down t]
3321 "--"
3322 ["Scroll Table Window" org-table-fedit-scroll t]
3323 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3324 ["Show Table Grid" org-table-fedit-toggle-coordinates
3325 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3326 org-table-overlay-coordinates)]
3327 "--"
3328 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3329 :style toggle :selected org-table-buffer-is-an]))
3331 (defvar org-pos)
3333 ;;;###autoload
3334 (defun org-table-edit-formulas ()
3335 "Edit the formulas of the current table in a separate buffer."
3336 (interactive)
3337 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3338 (beginning-of-line 0))
3339 (unless (org-at-table-p) (user-error "Not at a table"))
3340 (org-table-get-specials)
3341 (let ((key (org-table-current-field-formula 'key 'noerror))
3342 (eql (sort (org-table-get-stored-formulas 'noerror)
3343 'org-table-formula-less-p))
3344 (pos (point-marker))
3345 (startline 1)
3346 (wc (current-window-configuration))
3347 (sel-win (selected-window))
3348 (titles '((column . "# Column Formulas\n")
3349 (field . "# Field and Range Formulas\n")
3350 (named . "# Named Field Formulas\n")))
3351 entry s type title)
3352 (org-switch-to-buffer-other-window "*Edit Formulas*")
3353 (erase-buffer)
3354 ;; Keep global-font-lock-mode from turning on font-lock-mode
3355 (let ((font-lock-global-modes '(not fundamental-mode)))
3356 (fundamental-mode))
3357 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3358 (org-set-local 'org-pos pos)
3359 (org-set-local 'org-window-configuration wc)
3360 (org-set-local 'org-selected-window sel-win)
3361 (use-local-map org-table-fedit-map)
3362 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3363 (easy-menu-add org-table-fedit-menu)
3364 (setq startline (org-current-line))
3365 (while (setq entry (pop eql))
3366 (setq type (cond
3367 ((string-match "\\`$[<>]" (car entry)) 'column)
3368 ((equal (string-to-char (car entry)) ?@) 'field)
3369 ((string-match "^[0-9]" (car entry)) 'column)
3370 (t 'named)))
3371 (when (setq title (assq type titles))
3372 (or (bobp) (insert "\n"))
3373 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3374 (setq titles (remove title titles)))
3375 (if (equal key (car entry)) (setq startline (org-current-line)))
3376 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3377 (car entry) " = " (cdr entry) "\n"))
3378 (remove-text-properties 0 (length s) '(face nil) s)
3379 (insert s))
3380 (if (eq org-table-use-standard-references t)
3381 (org-table-fedit-toggle-ref-type))
3382 (org-goto-line startline)
3383 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3385 (defun org-table-fedit-post-command ()
3386 (when (not (memq this-command '(lisp-complete-symbol)))
3387 (let ((win (selected-window)))
3388 (save-excursion
3389 (condition-case nil
3390 (org-table-show-reference)
3391 (error nil))
3392 (select-window win)))))
3394 (defun org-table-formula-to-user (s)
3395 "Convert a formula from internal to user representation."
3396 (if (eq org-table-use-standard-references t)
3397 (org-table-convert-refs-to-an s)
3400 (defun org-table-formula-from-user (s)
3401 "Convert a formula from user to internal representation."
3402 (if org-table-use-standard-references
3403 (org-table-convert-refs-to-rc s)
3406 (defun org-table-convert-refs-to-rc (s)
3407 "Convert spreadsheet references from A7 to @7$28.
3408 Works for single references, but also for entire formulas and even the
3409 full TBLFM line."
3410 (let ((start 0))
3411 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3412 (cond
3413 ((match-end 3)
3414 ;; format match, just advance
3415 (setq start (match-end 0)))
3416 ((and (> (match-beginning 0) 0)
3417 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3418 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3419 ;; 3.e5 or something like this.
3420 (setq start (match-end 0)))
3421 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3422 ;; (member (match-string 1 s)
3423 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3425 ;; function name, just advance
3426 (setq start (match-end 0)))
3428 (setq start (match-beginning 0)
3429 s (replace-match
3430 (if (equal (match-string 2 s) "&")
3431 (format "$%d" (org-letters-to-number (match-string 1 s)))
3432 (format "@%d$%d"
3433 (string-to-number (match-string 2 s))
3434 (org-letters-to-number (match-string 1 s))))
3435 t t s)))))
3438 (defun org-table-convert-refs-to-an (s)
3439 "Convert spreadsheet references from to @7$28 to AB7.
3440 Works for single references, but also for entire formulas and even the
3441 full TBLFM line."
3442 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3443 (setq s (replace-match
3444 (format "%s%d"
3445 (org-number-to-letters
3446 (string-to-number (match-string 2 s)))
3447 (string-to-number (match-string 1 s)))
3448 t t s)))
3449 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3450 (setq s (replace-match (concat "\\1"
3451 (org-number-to-letters
3452 (string-to-number (match-string 2 s))) "&")
3453 t nil s)))
3456 (defun org-letters-to-number (s)
3457 "Convert a base 26 number represented by letters into an integer.
3458 For example: AB -> 28."
3459 (let ((n 0))
3460 (setq s (upcase s))
3461 (while (> (length s) 0)
3462 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3463 s (substring s 1)))
3466 (defun org-number-to-letters (n)
3467 "Convert an integer into a base 26 number represented by letters.
3468 For example: 28 -> AB."
3469 (let ((s ""))
3470 (while (> n 0)
3471 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3472 n (/ (1- n) 26)))
3475 (defun org-table-time-string-to-seconds (s)
3476 "Convert a time string into numerical duration in seconds.
3477 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3478 If S is a string representing a number, keep this number."
3479 (if (equal s "")
3481 (let (hour minus min sec res)
3482 (cond
3483 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3484 (setq minus (< 0 (length (match-string 1 s)))
3485 hour (string-to-number (match-string 2 s))
3486 min (string-to-number (match-string 3 s))
3487 sec (string-to-number (match-string 4 s)))
3488 (if minus
3489 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3490 (setq res (+ (* hour 3600) (* min 60) sec))))
3491 ((and (not (string-match org-ts-regexp-both s))
3492 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3493 (setq minus (< 0 (length (match-string 1 s)))
3494 hour (string-to-number (match-string 2 s))
3495 min (string-to-number (match-string 3 s)))
3496 (if minus
3497 (setq res (- (+ (* hour 3600) (* min 60))))
3498 (setq res (+ (* hour 3600) (* min 60)))))
3499 (t (setq res (string-to-number s))))
3500 (number-to-string res))))
3502 (defun org-table-time-seconds-to-string (secs &optional output-format)
3503 "Convert a number of seconds to a time string.
3504 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3505 minutes or seconds."
3506 (let* ((secs0 (abs secs))
3507 (res
3508 (cond ((eq output-format 'days)
3509 (format "%.3f" (/ (float secs0) 86400)))
3510 ((eq output-format 'hours)
3511 (format "%.2f" (/ (float secs0) 3600)))
3512 ((eq output-format 'minutes)
3513 (format "%.1f" (/ (float secs0) 60)))
3514 ((eq output-format 'seconds)
3515 (format "%d" secs0))
3516 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3517 (if (< secs 0) (concat "-" res) res)))
3519 (defun org-table-fedit-convert-buffer (function)
3520 "Convert all references in this buffer, using FUNCTION."
3521 (let ((line (org-current-line)))
3522 (goto-char (point-min))
3523 (while (not (eobp))
3524 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3525 (delete-region (point) (point-at-eol))
3526 (or (eobp) (forward-char 1)))
3527 (org-goto-line line)))
3529 (defun org-table-fedit-toggle-ref-type ()
3530 "Convert all references in the buffer from B3 to @3$2 and back."
3531 (interactive)
3532 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3533 (org-table-fedit-convert-buffer
3534 (if org-table-buffer-is-an
3535 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3536 (message "Reference type switched to %s"
3537 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3539 (defun org-table-fedit-ref-up ()
3540 "Shift the reference at point one row/hline up."
3541 (interactive)
3542 (org-table-fedit-shift-reference 'up))
3543 (defun org-table-fedit-ref-down ()
3544 "Shift the reference at point one row/hline down."
3545 (interactive)
3546 (org-table-fedit-shift-reference 'down))
3547 (defun org-table-fedit-ref-left ()
3548 "Shift the reference at point one field to the left."
3549 (interactive)
3550 (org-table-fedit-shift-reference 'left))
3551 (defun org-table-fedit-ref-right ()
3552 "Shift the reference at point one field to the right."
3553 (interactive)
3554 (org-table-fedit-shift-reference 'right))
3556 (defun org-table-fedit-shift-reference (dir)
3557 (cond
3558 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3559 (if (memq dir '(left right))
3560 (org-rematch-and-replace 1 (eq dir 'left))
3561 (user-error "Cannot shift reference in this direction")))
3562 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3563 ;; A B3-like reference
3564 (if (memq dir '(up down))
3565 (org-rematch-and-replace 2 (eq dir 'up))
3566 (org-rematch-and-replace 1 (eq dir 'left))))
3567 ((org-at-regexp-p
3568 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3569 ;; An internal reference
3570 (if (memq dir '(up down))
3571 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3572 (org-rematch-and-replace 5 (eq dir 'left))))))
3574 (defun org-rematch-and-replace (n &optional decr hline)
3575 "Re-match the group N, and replace it with the shifted reference."
3576 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3577 (goto-char (match-beginning n))
3578 (and (looking-at (regexp-quote (match-string n)))
3579 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3580 t t)))
3582 (defun org-table-shift-refpart (ref &optional decr hline)
3583 "Shift a reference part REF.
3584 If DECR is set, decrease the references row/column, else increase.
3585 If HLINE is set, this may be a hline reference, it certainly is not
3586 a translation reference."
3587 (save-match-data
3588 (let* ((sign (string-match "^[-+]" ref)) n)
3590 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3591 (cond
3592 ((and hline (string-match "^I+" ref))
3593 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3594 (setq n (+ n (if decr -1 1)))
3595 (if (= n 0) (setq n (+ n (if decr -1 1))))
3596 (if sign
3597 (setq sign (if (< n 0) "-" "+") n (abs n))
3598 (setq n (max 1 n)))
3599 (concat sign (make-string n ?I)))
3601 ((string-match "^[0-9]+" ref)
3602 (setq n (string-to-number (concat sign ref)))
3603 (setq n (+ n (if decr -1 1)))
3604 (if sign
3605 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3606 (number-to-string (max 1 n))))
3608 ((string-match "^[a-zA-Z]+" ref)
3609 (org-number-to-letters
3610 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3612 (t (user-error "Cannot shift reference"))))))
3614 (defun org-table-fedit-toggle-coordinates ()
3615 "Toggle the display of coordinates in the referenced table."
3616 (interactive)
3617 (let ((pos (marker-position org-pos)))
3618 (with-current-buffer (marker-buffer org-pos)
3619 (save-excursion
3620 (goto-char pos)
3621 (org-table-toggle-coordinate-overlays)))))
3623 (defun org-table-fedit-finish (&optional arg)
3624 "Parse the buffer for formula definitions and install them.
3625 With prefix ARG, apply the new formulas to the table."
3626 (interactive "P")
3627 (org-table-remove-rectangle-highlight)
3628 (if org-table-use-standard-references
3629 (progn
3630 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3631 (setq org-table-buffer-is-an nil)))
3632 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3633 (goto-char (point-min))
3634 (while (re-search-forward
3635 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3636 nil t)
3637 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3638 form (match-string 3))
3639 (setq form (org-trim form))
3640 (when (not (equal form ""))
3641 (while (string-match "[ \t]*\n[ \t]*" form)
3642 (setq form (replace-match " " t t form)))
3643 (when (assoc var eql)
3644 (user-error "Double formulas for %s" var))
3645 (push (cons var form) eql)))
3646 (setq org-pos nil)
3647 (set-window-configuration org-window-configuration)
3648 (select-window sel-win)
3649 (goto-char pos)
3650 (unless (org-at-table-p)
3651 (user-error "Lost table position - cannot install formulas"))
3652 (org-table-store-formulas eql)
3653 (move-marker pos nil)
3654 (kill-buffer "*Edit Formulas*")
3655 (if arg
3656 (org-table-recalculate 'all)
3657 (message "New formulas installed - press C-u C-c C-c to apply."))))
3659 (defun org-table-fedit-abort ()
3660 "Abort editing formulas, without installing the changes."
3661 (interactive)
3662 (org-table-remove-rectangle-highlight)
3663 (let ((pos org-pos) (sel-win org-selected-window))
3664 (set-window-configuration org-window-configuration)
3665 (select-window sel-win)
3666 (goto-char pos)
3667 (move-marker pos nil)
3668 (message "Formula editing aborted without installing changes")))
3670 (defun org-table-fedit-lisp-indent ()
3671 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3672 (interactive)
3673 (let ((pos (point)) beg end ind)
3674 (beginning-of-line 1)
3675 (cond
3676 ((looking-at "[ \t]")
3677 (goto-char pos)
3678 (call-interactively 'lisp-indent-line))
3679 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3680 ((not (fboundp 'pp-buffer))
3681 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3682 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3683 (goto-char (- (match-end 0) 2))
3684 (setq beg (point))
3685 (setq ind (make-string (current-column) ?\ ))
3686 (condition-case nil (forward-sexp 1)
3687 (error
3688 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3689 (setq end (point))
3690 (save-restriction
3691 (narrow-to-region beg end)
3692 (if (eq last-command this-command)
3693 (progn
3694 (goto-char (point-min))
3695 (setq this-command nil)
3696 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3697 (replace-match " ")))
3698 (pp-buffer)
3699 (untabify (point-min) (point-max))
3700 (goto-char (1+ (point-min)))
3701 (while (re-search-forward "^." nil t)
3702 (beginning-of-line 1)
3703 (insert ind))
3704 (goto-char (point-max))
3705 (org-delete-backward-char 1)))
3706 (goto-char beg))
3707 (t nil))))
3709 (defvar org-show-positions nil)
3711 (defun org-table-show-reference (&optional local)
3712 "Show the location/value of the $ expression at point."
3713 (interactive)
3714 (org-table-remove-rectangle-highlight)
3715 (catch 'exit
3716 (let ((pos (if local (point) org-pos))
3717 (face2 'highlight)
3718 (org-inhibit-highlight-removal t)
3719 (win (selected-window))
3720 (org-show-positions nil)
3721 var name e what match dest)
3722 (if local (org-table-get-specials))
3723 (setq what (cond
3724 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3725 (setq match (concat (substring (match-string 0) 0 -1)
3726 "$1.."
3727 (substring (match-string 0) 0 -1)
3728 "$100"))
3729 'range)
3730 ((or (org-at-regexp-p org-table-range-regexp2)
3731 (org-at-regexp-p org-table-translate-regexp)
3732 (org-at-regexp-p org-table-range-regexp))
3733 (setq match
3734 (save-match-data
3735 (org-table-convert-refs-to-rc (match-string 0))))
3736 'range)
3737 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3738 ((org-at-regexp-p "\\$[0-9]+") 'column)
3739 ((not local) nil)
3740 (t (user-error "No reference at point")))
3741 match (and what (or match (match-string 0))))
3742 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3743 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3744 'secondary-selection))
3745 (org-add-hook 'before-change-functions
3746 'org-table-remove-rectangle-highlight)
3747 (if (eq what 'name) (setq var (substring match 1)))
3748 (when (eq what 'range)
3749 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3750 (setq match (org-table-formula-substitute-names match)))
3751 (unless local
3752 (save-excursion
3753 (end-of-line 1)
3754 (re-search-backward "^\\S-" nil t)
3755 (beginning-of-line 1)
3756 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3757 (setq dest
3758 (save-match-data
3759 (org-table-convert-refs-to-rc (match-string 1))))
3760 (org-table-add-rectangle-overlay
3761 (match-beginning 1) (match-end 1) face2))))
3762 (if (and (markerp pos) (marker-buffer pos))
3763 (if (get-buffer-window (marker-buffer pos))
3764 (select-window (get-buffer-window (marker-buffer pos)))
3765 (org-switch-to-buffer-other-window (get-buffer-window
3766 (marker-buffer pos)))))
3767 (goto-char pos)
3768 (org-table-force-dataline)
3769 (when dest
3770 (setq name (substring dest 1))
3771 (cond
3772 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3773 (setq e (assoc name org-table-named-field-locations))
3774 (org-goto-line (nth 1 e))
3775 (org-table-goto-column (nth 2 e)))
3776 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3777 (let ((l (string-to-number (match-string 1 dest)))
3778 (c (string-to-number (match-string 2 dest))))
3779 (org-goto-line (aref org-table-dlines l))
3780 (org-table-goto-column c)))
3781 (t (org-table-goto-column (string-to-number name))))
3782 (move-marker pos (point))
3783 (org-table-highlight-rectangle nil nil face2))
3784 (cond
3785 ((equal dest match))
3786 ((not match))
3787 ((eq what 'range)
3788 (condition-case nil
3789 (save-excursion
3790 (org-table-get-range match nil nil 'highlight))
3791 (error nil)))
3792 ((setq e (assoc var org-table-named-field-locations))
3793 (org-goto-line (nth 1 e))
3794 (org-table-goto-column (nth 2 e))
3795 (org-table-highlight-rectangle (point) (point))
3796 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3797 ((setq e (assoc var org-table-column-names))
3798 (org-table-goto-column (string-to-number (cdr e)))
3799 (org-table-highlight-rectangle (point) (point))
3800 (goto-char (org-table-begin))
3801 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3802 (org-table-end) t)
3803 (progn
3804 (goto-char (match-beginning 1))
3805 (org-table-highlight-rectangle)
3806 (message "Named column (column %s)" (cdr e)))
3807 (user-error "Column name not found")))
3808 ((eq what 'column)
3809 ;; column number
3810 (org-table-goto-column (string-to-number (substring match 1)))
3811 (org-table-highlight-rectangle (point) (point))
3812 (message "Column %s" (substring match 1)))
3813 ((setq e (assoc var org-table-local-parameters))
3814 (goto-char (org-table-begin))
3815 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3816 (progn
3817 (goto-char (match-beginning 1))
3818 (org-table-highlight-rectangle)
3819 (message "Local parameter."))
3820 (user-error "Parameter not found")))
3822 (cond
3823 ((not var) (user-error "No reference at point"))
3824 ((setq e (assoc var org-table-formula-constants-local))
3825 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3826 var (cdr e)))
3827 ((setq e (assoc var org-table-formula-constants))
3828 (message "Constant: $%s=%s in `org-table-formula-constants'."
3829 var (cdr e)))
3830 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3831 (message "Constant: $%s=%s, from `constants.el'%s."
3832 var e (format " (%s units)" constants-unit-system)))
3833 (t (user-error "Undefined name $%s" var)))))
3834 (goto-char pos)
3835 (when (and org-show-positions
3836 (not (memq this-command '(org-table-fedit-scroll
3837 org-table-fedit-scroll-down))))
3838 (push pos org-show-positions)
3839 (push org-table-current-begin-pos org-show-positions)
3840 (let ((min (apply 'min org-show-positions))
3841 (max (apply 'max org-show-positions)))
3842 (goto-char min) (recenter 0)
3843 (goto-char max)
3844 (or (pos-visible-in-window-p max) (recenter -1))))
3845 (select-window win))))
3847 (defun org-table-force-dataline ()
3848 "Make sure the cursor is in a dataline in a table."
3849 (unless (save-excursion
3850 (beginning-of-line 1)
3851 (looking-at org-table-dataline-regexp))
3852 (let* ((re org-table-dataline-regexp)
3853 (p1 (save-excursion (re-search-forward re nil 'move)))
3854 (p2 (save-excursion (re-search-backward re nil 'move))))
3855 (cond ((and p1 p2)
3856 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3857 p1 p2)))
3858 ((or p1 p2) (goto-char (or p1 p2)))
3859 (t (user-error "No table dataline around here"))))))
3861 (defun org-table-fedit-line-up ()
3862 "Move cursor one line up in the window showing the table."
3863 (interactive)
3864 (org-table-fedit-move 'previous-line))
3866 (defun org-table-fedit-line-down ()
3867 "Move cursor one line down in the window showing the table."
3868 (interactive)
3869 (org-table-fedit-move 'next-line))
3871 (defun org-table-fedit-move (command)
3872 "Move the cursor in the window showing the table.
3873 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3874 (let ((org-table-allow-automatic-line-recalculation nil)
3875 (pos org-pos) (win (selected-window)) p)
3876 (select-window (get-buffer-window (marker-buffer org-pos)))
3877 (setq p (point))
3878 (call-interactively command)
3879 (while (and (org-at-table-p)
3880 (org-at-table-hline-p))
3881 (call-interactively command))
3882 (or (org-at-table-p) (goto-char p))
3883 (move-marker pos (point))
3884 (select-window win)))
3886 (defun org-table-fedit-scroll (N)
3887 (interactive "p")
3888 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3889 (scroll-other-window N)))
3891 (defun org-table-fedit-scroll-down (N)
3892 (interactive "p")
3893 (org-table-fedit-scroll (- N)))
3895 (defvar org-table-rectangle-overlays nil)
3897 (defun org-table-add-rectangle-overlay (beg end &optional face)
3898 "Add a new overlay."
3899 (let ((ov (make-overlay beg end)))
3900 (overlay-put ov 'face (or face 'secondary-selection))
3901 (push ov org-table-rectangle-overlays)))
3903 (defun org-table-highlight-rectangle (&optional beg end face)
3904 "Highlight rectangular region in a table."
3905 (setq beg (or beg (point)) end (or end (point)))
3906 (let ((b (min beg end))
3907 (e (max beg end))
3908 l1 c1 l2 c2 tmp)
3909 (and (boundp 'org-show-positions)
3910 (setq org-show-positions (cons b (cons e org-show-positions))))
3911 (goto-char (min beg end))
3912 (setq l1 (org-current-line)
3913 c1 (org-table-current-column))
3914 (goto-char (max beg end))
3915 (setq l2 (org-current-line)
3916 c2 (org-table-current-column))
3917 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3918 (org-goto-line l1)
3919 (beginning-of-line 1)
3920 (loop for line from l1 to l2 do
3921 (when (looking-at org-table-dataline-regexp)
3922 (org-table-goto-column c1)
3923 (skip-chars-backward "^|\n") (setq beg (point))
3924 (org-table-goto-column c2)
3925 (skip-chars-forward "^|\n") (setq end (point))
3926 (org-table-add-rectangle-overlay beg end face))
3927 (beginning-of-line 2))
3928 (goto-char b))
3929 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3931 (defun org-table-remove-rectangle-highlight (&rest ignore)
3932 "Remove the rectangle overlays."
3933 (unless org-inhibit-highlight-removal
3934 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3935 (mapc 'delete-overlay org-table-rectangle-overlays)
3936 (setq org-table-rectangle-overlays nil)))
3938 (defvar org-table-coordinate-overlays nil
3939 "Collects the coordinate grid overlays, so that they can be removed.")
3940 (make-variable-buffer-local 'org-table-coordinate-overlays)
3942 (defun org-table-overlay-coordinates ()
3943 "Add overlays to the table at point, to show row/column coordinates."
3944 (interactive)
3945 (mapc 'delete-overlay org-table-coordinate-overlays)
3946 (setq org-table-coordinate-overlays nil)
3947 (save-excursion
3948 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3949 (goto-char (org-table-begin))
3950 (while (org-at-table-p)
3951 (setq eol (point-at-eol))
3952 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3953 (push ov org-table-coordinate-overlays)
3954 (setq hline (looking-at org-table-hline-regexp))
3955 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3956 (format "%4d" (setq id (1+ id)))))
3957 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3958 (when hline
3959 (setq ic 0)
3960 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3961 (setq beg (1+ (match-beginning 0))
3962 ic (1+ ic)
3963 s1 (concat "$" (int-to-string ic))
3964 s2 (org-number-to-letters ic)
3965 str (if (eq org-table-use-standard-references t) s2 s1))
3966 (setq ov (make-overlay beg (+ beg (length str))))
3967 (push ov org-table-coordinate-overlays)
3968 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3969 (beginning-of-line 2)))))
3971 ;;;###autoload
3972 (defun org-table-toggle-coordinate-overlays ()
3973 "Toggle the display of Row/Column numbers in tables."
3974 (interactive)
3975 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3976 (message "Tables Row/Column numbers display turned %s"
3977 (if org-table-overlay-coordinates "on" "off"))
3978 (if (and (org-at-table-p) org-table-overlay-coordinates)
3979 (org-table-align))
3980 (unless org-table-overlay-coordinates
3981 (mapc 'delete-overlay org-table-coordinate-overlays)
3982 (setq org-table-coordinate-overlays nil)))
3984 ;;;###autoload
3985 (defun org-table-toggle-formula-debugger ()
3986 "Toggle the formula debugger in tables."
3987 (interactive)
3988 (setq org-table-formula-debug (not org-table-formula-debug))
3989 (message "Formula debugging has been turned %s"
3990 (if org-table-formula-debug "on" "off")))
3992 ;;; The orgtbl minor mode
3994 ;; Define a minor mode which can be used in other modes in order to
3995 ;; integrate the org-mode table editor.
3997 ;; This is really a hack, because the org-mode table editor uses several
3998 ;; keys which normally belong to the major mode, for example the TAB and
3999 ;; RET keys. Here is how it works: The minor mode defines all the keys
4000 ;; necessary to operate the table editor, but wraps the commands into a
4001 ;; function which tests if the cursor is currently inside a table. If that
4002 ;; is the case, the table editor command is executed. However, when any of
4003 ;; those keys is used outside a table, the function uses `key-binding' to
4004 ;; look up if the key has an associated command in another currently active
4005 ;; keymap (minor modes, major mode, global), and executes that command.
4006 ;; There might be problems if any of the keys used by the table editor is
4007 ;; otherwise used as a prefix key.
4009 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4010 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4011 ;; addresses this by checking explicitly for both bindings.
4013 ;; The optimized version (see variable `orgtbl-optimized') takes over
4014 ;; all keys which are bound to `self-insert-command' in the *global map*.
4015 ;; Some modes bind other commands to simple characters, for example
4016 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4017 ;; active, this binding is ignored inside tables and replaced with a
4018 ;; modified self-insert.
4021 (defvar orgtbl-mode-map (make-keymap)
4022 "Keymap for `orgtbl-mode'.")
4024 (defvar org-old-auto-fill-inhibit-regexp nil
4025 "Local variable used by `orgtbl-mode'.")
4027 (defconst orgtbl-line-start-regexp
4028 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4029 "Matches a line belonging to an orgtbl.")
4031 (defconst orgtbl-extra-font-lock-keywords
4032 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4033 0 (quote 'org-table) 'prepend))
4034 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4036 ;; Install it as a minor mode.
4037 (put 'orgtbl-mode :included t)
4038 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4040 ;;;###autoload
4041 (define-minor-mode orgtbl-mode
4042 "The `org-mode' table editor as a minor mode for use in other modes."
4043 :lighter " OrgTbl" :keymap orgtbl-mode-map
4044 (org-load-modules-maybe)
4045 (cond
4046 ((derived-mode-p 'org-mode)
4047 ;; Exit without error, in case some hook functions calls this
4048 ;; by accident in org-mode.
4049 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4050 (orgtbl-mode
4051 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4052 ;; Make sure we are first in minor-mode-map-alist
4053 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4054 ;; FIXME: maybe it should use emulation-mode-map-alists?
4055 (and c (setq minor-mode-map-alist
4056 (cons c (delq c minor-mode-map-alist)))))
4057 (org-set-local (quote org-table-may-need-update) t)
4058 (org-add-hook 'before-change-functions 'org-before-change-function
4059 nil 'local)
4060 (org-set-local 'org-old-auto-fill-inhibit-regexp
4061 auto-fill-inhibit-regexp)
4062 (org-set-local 'auto-fill-inhibit-regexp
4063 (if auto-fill-inhibit-regexp
4064 (concat orgtbl-line-start-regexp "\\|"
4065 auto-fill-inhibit-regexp)
4066 orgtbl-line-start-regexp))
4067 (add-to-invisibility-spec '(org-cwidth))
4068 (when (fboundp 'font-lock-add-keywords)
4069 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4070 (org-restart-font-lock))
4071 (easy-menu-add orgtbl-mode-menu))
4073 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4074 (org-table-cleanup-narrow-column-properties)
4075 (org-remove-from-invisibility-spec '(org-cwidth))
4076 (remove-hook 'before-change-functions 'org-before-change-function t)
4077 (when (fboundp 'font-lock-remove-keywords)
4078 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4079 (org-restart-font-lock))
4080 (easy-menu-remove orgtbl-mode-menu)
4081 (force-mode-line-update 'all))))
4083 (defun org-table-cleanup-narrow-column-properties ()
4084 "Remove all properties related to narrow-column invisibility."
4085 (let ((s (point-min)))
4086 (while (setq s (text-property-any s (point-max)
4087 'display org-narrow-column-arrow))
4088 (remove-text-properties s (1+ s) '(display t)))
4089 (setq s (point-min))
4090 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4091 (remove-text-properties s (1+ s) '(org-cwidth t)))
4092 (setq s (point-min))
4093 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4094 (remove-text-properties s (1+ s) '(invisible t)))))
4096 (defun orgtbl-make-binding (fun n &rest keys)
4097 "Create a function for binding in the table minor mode.
4098 FUN is the command to call inside a table. N is used to create a unique
4099 command name. KEYS are keys that should be checked in for a command
4100 to execute outside of tables."
4101 (eval
4102 (list 'defun
4103 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4104 '(arg)
4105 (concat "In tables, run `" (symbol-name fun) "'.\n"
4106 "Outside of tables, run the binding of `"
4107 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
4108 "'.")
4109 '(interactive "p")
4110 (list 'if
4111 '(org-at-table-p)
4112 (list 'call-interactively (list 'quote fun))
4113 (list 'let '(orgtbl-mode)
4114 (list 'call-interactively
4115 (append '(or)
4116 (mapcar (lambda (k)
4117 (list 'key-binding k))
4118 keys)
4119 '('orgtbl-error))))))))
4121 (defun orgtbl-error ()
4122 "Error when there is no default binding for a table key."
4123 (interactive)
4124 (user-error "This key has no function outside tables"))
4126 (defun orgtbl-setup ()
4127 "Setup orgtbl keymaps."
4128 (let ((nfunc 0)
4129 (bindings
4130 '(([(meta shift left)] org-table-delete-column)
4131 ([(meta left)] org-table-move-column-left)
4132 ([(meta right)] org-table-move-column-right)
4133 ([(meta shift right)] org-table-insert-column)
4134 ([(meta shift up)] org-table-kill-row)
4135 ([(meta shift down)] org-table-insert-row)
4136 ([(meta up)] org-table-move-row-up)
4137 ([(meta down)] org-table-move-row-down)
4138 ("\C-c\C-w" org-table-cut-region)
4139 ("\C-c\M-w" org-table-copy-region)
4140 ("\C-c\C-y" org-table-paste-rectangle)
4141 ("\C-c\C-w" org-table-wrap-region)
4142 ("\C-c-" org-table-insert-hline)
4143 ("\C-c}" org-table-toggle-coordinate-overlays)
4144 ("\C-c{" org-table-toggle-formula-debugger)
4145 ("\C-m" org-table-next-row)
4146 ([(shift return)] org-table-copy-down)
4147 ("\C-c?" org-table-field-info)
4148 ("\C-c " org-table-blank-field)
4149 ("\C-c+" org-table-sum)
4150 ("\C-c=" org-table-eval-formula)
4151 ("\C-c'" org-table-edit-formulas)
4152 ("\C-c`" org-table-edit-field)
4153 ("\C-c*" org-table-recalculate)
4154 ("\C-c^" org-table-sort-lines)
4155 ("\M-a" org-table-beginning-of-field)
4156 ("\M-e" org-table-end-of-field)
4157 ([(control ?#)] org-table-rotate-recalc-marks)))
4158 elt key fun cmd)
4159 (while (setq elt (pop bindings))
4160 (setq nfunc (1+ nfunc))
4161 (setq key (org-key (car elt))
4162 fun (nth 1 elt)
4163 cmd (orgtbl-make-binding fun nfunc key))
4164 (org-defkey orgtbl-mode-map key cmd))
4166 ;; Special treatment needed for TAB and RET
4167 (org-defkey orgtbl-mode-map [(return)]
4168 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4169 (org-defkey orgtbl-mode-map "\C-m"
4170 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4172 (org-defkey orgtbl-mode-map [(tab)]
4173 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4174 (org-defkey orgtbl-mode-map "\C-i"
4175 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4177 (org-defkey orgtbl-mode-map [(shift tab)]
4178 (orgtbl-make-binding 'org-table-previous-field 104
4179 [(shift tab)] [(tab)] "\C-i"))
4182 (unless (featurep 'xemacs)
4183 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4184 (orgtbl-make-binding 'org-table-previous-field 107
4185 [S-iso-lefttab] [backtab] [(shift tab)]
4186 [(tab)] "\C-i")))
4188 (org-defkey orgtbl-mode-map [backtab]
4189 (orgtbl-make-binding 'org-table-previous-field 108
4190 [backtab] [S-iso-lefttab] [(shift tab)]
4191 [(tab)] "\C-i"))
4193 (org-defkey orgtbl-mode-map "\M-\C-m"
4194 (orgtbl-make-binding 'org-table-wrap-region 105
4195 "\M-\C-m" [(meta return)]))
4196 (org-defkey orgtbl-mode-map [(meta return)]
4197 (orgtbl-make-binding 'org-table-wrap-region 106
4198 [(meta return)] "\M-\C-m"))
4200 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4201 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4203 (when orgtbl-optimized
4204 ;; If the user wants maximum table support, we need to hijack
4205 ;; some standard editing functions
4206 (org-remap orgtbl-mode-map
4207 'self-insert-command 'orgtbl-self-insert-command
4208 'delete-char 'org-delete-char
4209 'delete-backward-char 'org-delete-backward-char)
4210 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4211 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4212 '("OrgTbl"
4213 ["Create or convert" org-table-create-or-convert-from-region
4214 :active (not (org-at-table-p)) :keys "C-c |" ]
4215 "--"
4216 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4217 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4218 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4219 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4220 "--"
4221 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4222 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4223 ["Copy Field from Above"
4224 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4225 "--"
4226 ("Column"
4227 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4228 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4229 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4230 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4231 ("Row"
4232 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4233 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4234 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4235 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4236 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4237 "--"
4238 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4239 ("Rectangle"
4240 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4241 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4242 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4243 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4244 "--"
4245 ("Radio tables"
4246 ["Insert table template" orgtbl-insert-radio-table
4247 (assq major-mode orgtbl-radio-table-templates)]
4248 ["Comment/uncomment table" orgtbl-toggle-comment t])
4249 "--"
4250 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4251 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4252 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4253 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4254 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4255 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4256 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4257 ["Sum Column/Rectangle" org-table-sum
4258 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4259 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4260 ["Debug Formulas"
4261 org-table-toggle-formula-debugger :active (org-at-table-p)
4262 :keys "C-c {"
4263 :style toggle :selected org-table-formula-debug]
4264 ["Show Col/Row Numbers"
4265 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4266 :keys "C-c }"
4267 :style toggle :selected org-table-overlay-coordinates]
4271 (defun orgtbl-ctrl-c-ctrl-c (arg)
4272 "If the cursor is inside a table, realign the table.
4273 If it is a table to be sent away to a receiver, do it.
4274 With prefix arg, also recompute table."
4275 (interactive "P")
4276 (let ((case-fold-search t) (pos (point)) action)
4277 (save-excursion
4278 (beginning-of-line 1)
4279 (setq action (cond
4280 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4281 ((looking-at "[ \t]*|") pos)
4282 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4283 (cond
4284 ((integerp action)
4285 (goto-char action)
4286 (org-table-maybe-eval-formula)
4287 (if arg
4288 (call-interactively 'org-table-recalculate)
4289 (org-table-maybe-recalculate-line))
4290 (call-interactively 'org-table-align)
4291 (when (orgtbl-send-table 'maybe)
4292 (run-hooks 'orgtbl-after-send-table-hook)))
4293 ((eq action 'recalc)
4294 (org-table-set-constants)
4295 (save-excursion
4296 (beginning-of-line 1)
4297 (skip-chars-backward " \r\n\t")
4298 (if (org-at-table-p)
4299 (org-call-with-arg 'org-table-recalculate t))))
4300 (t (let (orgtbl-mode)
4301 (call-interactively (key-binding "\C-c\C-c")))))))
4303 (defun orgtbl-create-or-convert-from-region (arg)
4304 "Create table or convert region to table, if no conflicting binding.
4305 This installs the table binding `C-c |', but only if there is no
4306 conflicting binding to this key outside orgtbl-mode."
4307 (interactive "P")
4308 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4309 (if cmd
4310 (call-interactively cmd)
4311 (call-interactively 'org-table-create-or-convert-from-region))))
4313 (defun orgtbl-tab (arg)
4314 "Justification and field motion for `orgtbl-mode'."
4315 (interactive "P")
4316 (if arg (org-table-edit-field t)
4317 (org-table-justify-field-maybe)
4318 (org-table-next-field)))
4320 (defun orgtbl-ret ()
4321 "Justification and field motion for `orgtbl-mode'."
4322 (interactive)
4323 (if (bobp)
4324 (newline)
4325 (org-table-justify-field-maybe)
4326 (org-table-next-row)))
4328 (defun orgtbl-self-insert-command (N)
4329 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4330 If the cursor is in a table looking at whitespace, the whitespace is
4331 overwritten, and the table is not marked as requiring realignment."
4332 (interactive "p")
4333 (if (and (org-at-table-p)
4335 (and org-table-auto-blank-field
4336 (member last-command
4337 '(orgtbl-hijacker-command-100
4338 orgtbl-hijacker-command-101
4339 orgtbl-hijacker-command-102
4340 orgtbl-hijacker-command-103
4341 orgtbl-hijacker-command-104
4342 orgtbl-hijacker-command-105
4343 yas/expand))
4344 (org-table-blank-field))
4346 (eq N 1)
4347 (looking-at "[^|\n]* +|"))
4348 (let (org-table-may-need-update)
4349 (goto-char (1- (match-end 0)))
4350 (org-delete-backward-char 1)
4351 (goto-char (match-beginning 0))
4352 (self-insert-command N))
4353 (setq org-table-may-need-update t)
4354 (let* (orgtbl-mode
4356 (cmd (or (key-binding
4357 (or (and (listp function-key-map)
4358 (setq a (assoc last-input-event function-key-map))
4359 (cdr a))
4360 (vector last-input-event)))
4361 'self-insert-command)))
4362 (call-interactively cmd)
4363 (if (and org-self-insert-cluster-for-undo
4364 (eq cmd 'self-insert-command))
4365 (if (not (eq last-command 'orgtbl-self-insert-command))
4366 (setq org-self-insert-command-undo-counter 1)
4367 (if (>= org-self-insert-command-undo-counter 20)
4368 (setq org-self-insert-command-undo-counter 1)
4369 (and (> org-self-insert-command-undo-counter 0)
4370 buffer-undo-list
4371 (not (cadr buffer-undo-list)) ; remove nil entry
4372 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4373 (setq org-self-insert-command-undo-counter
4374 (1+ org-self-insert-command-undo-counter))))))))
4376 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4377 "Regular expression matching exponentials as produced by calc.")
4379 (defun orgtbl-gather-send-defs ()
4380 "Gather a plist of :name, :transform, :params for each destination before
4381 a radio table."
4382 (save-excursion
4383 (goto-char (org-table-begin))
4384 (let (rtn)
4385 (beginning-of-line 0)
4386 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4387 (let ((name (org-no-properties (match-string 1)))
4388 (transform (intern (match-string 2)))
4389 (params (if (match-end 3)
4390 (read (concat "(" (match-string 3) ")")))))
4391 (push (list :name name :transform transform :params params)
4392 rtn)
4393 (beginning-of-line 0)))
4394 rtn)))
4396 (defun orgtbl-send-replace-tbl (name txt)
4397 "Find and replace table NAME with TXT."
4398 (save-excursion
4399 (goto-char (point-min))
4400 (unless (re-search-forward
4401 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4402 (user-error "Don't know where to insert translated table"))
4403 (goto-char (match-beginning 0))
4404 (beginning-of-line 2)
4405 (save-excursion
4406 (let ((beg (point)))
4407 (unless (re-search-forward
4408 (concat "END RECEIVE ORGTBL +" name) nil t)
4409 (user-error "Cannot find end of insertion region"))
4410 (beginning-of-line 1)
4411 (delete-region beg (point))))
4412 (insert txt "\n")))
4414 ;;;###autoload
4415 (defun org-table-to-lisp (&optional txt)
4416 "Convert the table at point to a Lisp structure.
4417 The structure will be a list. Each item is either the symbol `hline'
4418 for a horizontal separator line, or a list of field values as strings.
4419 The table is taken from the parameter TXT, or from the buffer at point."
4420 (unless txt
4421 (unless (org-at-table-p)
4422 (user-error "No table at point")))
4423 (let* ((txt (or txt
4424 (buffer-substring-no-properties (org-table-begin)
4425 (org-table-end))))
4426 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4428 (mapcar
4429 (lambda (x)
4430 (if (string-match org-table-hline-regexp x)
4431 'hline
4432 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4433 lines)))
4435 (defun orgtbl-send-table (&optional maybe)
4436 "Send a transformed version of this table to the receiver position.
4437 With argument MAYBE, fail quietly if no transformation is defined for
4438 this table."
4439 (interactive)
4440 (catch 'exit
4441 (unless (org-at-table-p) (user-error "Not at a table"))
4442 ;; when non-interactive, we assume align has just happened.
4443 (when (org-called-interactively-p 'any) (org-table-align))
4444 (let ((dests (orgtbl-gather-send-defs))
4445 (txt (buffer-substring-no-properties (org-table-begin)
4446 (org-table-end)))
4447 (ntbl 0))
4448 (unless dests (if maybe (throw 'exit nil)
4449 (user-error "Don't know how to transform this table")))
4450 (dolist (dest dests)
4451 (let* ((name (plist-get dest :name))
4452 (transform (plist-get dest :transform))
4453 (params (plist-get dest :params))
4454 (skip (plist-get params :skip))
4455 (skipcols (plist-get params :skipcols))
4456 (no-escape (plist-get params :no-escape))
4458 (lines (org-table-clean-before-export
4459 (nthcdr (or skip 0)
4460 (org-split-string txt "[ \t]*\n[ \t]*"))))
4461 (i0 (if org-table-clean-did-remove-column 2 1))
4462 (lines (if no-escape lines
4463 (mapcar (lambda(l) (replace-regexp-in-string
4464 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4465 (table (mapcar
4466 (lambda (x)
4467 (if (string-match org-table-hline-regexp x)
4468 'hline
4469 (org-remove-by-index
4470 (org-split-string (org-trim x) "\\s-*|\\s-*")
4471 skipcols i0)))
4472 lines))
4473 (fun (if (= i0 2) 'cdr 'identity))
4474 (org-table-last-alignment
4475 (org-remove-by-index (funcall fun org-table-last-alignment)
4476 skipcols i0))
4477 (org-table-last-column-widths
4478 (org-remove-by-index (funcall fun org-table-last-column-widths)
4479 skipcols i0))
4480 (txt (if (fboundp transform)
4481 (funcall transform table params)
4482 (user-error "No such transformation function %s" transform))))
4483 (orgtbl-send-replace-tbl name txt))
4484 (setq ntbl (1+ ntbl)))
4485 (message "Table converted and installed at %d receiver location%s"
4486 ntbl (if (> ntbl 1) "s" ""))
4487 (if (> ntbl 0)
4488 ntbl
4489 nil))))
4491 (defun org-remove-by-index (list indices &optional i0)
4492 "Remove the elements in LIST with indices in INDICES.
4493 First element has index 0, or I0 if given."
4494 (if (not indices)
4495 list
4496 (if (integerp indices) (setq indices (list indices)))
4497 (setq i0 (1- (or i0 0)))
4498 (delq :rm (mapcar (lambda (x)
4499 (setq i0 (1+ i0))
4500 (if (memq i0 indices) :rm x))
4501 list))))
4503 (defun orgtbl-toggle-comment ()
4504 "Comment or uncomment the orgtbl at point."
4505 (interactive)
4506 (let* ((case-fold-search t)
4507 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4508 (re2 (concat "^" orgtbl-line-start-regexp))
4509 (commented (save-excursion (beginning-of-line 1)
4510 (cond ((looking-at re1) t)
4511 ((looking-at re2) nil)
4512 (t (user-error "Not at an org table")))))
4513 (re (if commented re1 re2))
4514 beg end)
4515 (save-excursion
4516 (beginning-of-line 1)
4517 (while (looking-at re) (beginning-of-line 0))
4518 (beginning-of-line 2)
4519 (setq beg (point))
4520 (while (looking-at re) (beginning-of-line 2))
4521 (setq end (point)))
4522 (comment-region beg end (if commented '(4) nil))))
4524 (defun orgtbl-insert-radio-table ()
4525 "Insert a radio table template appropriate for this major mode."
4526 (interactive)
4527 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4528 (txt (nth 1 e))
4529 name pos)
4530 (unless e (user-error "No radio table setup defined for %s" major-mode))
4531 (setq name (read-string "Table name: "))
4532 (while (string-match "%n" txt)
4533 (setq txt (replace-match name t t txt)))
4534 (or (bolp) (insert "\n"))
4535 (setq pos (point))
4536 (insert txt)
4537 (goto-char pos)))
4539 ;; Dynamically bound input and output for table formatting.
4540 (defvar *orgtbl-table* nil
4541 "Carries the current table through formatting routines.")
4542 (defvar *orgtbl-rtn* nil
4543 "Formatting routines push the output lines here.")
4544 ;; Formatting parameters for the current table section.
4545 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4546 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4547 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4548 (defvar *orgtbl-fmt* nil "Format for each entry.")
4549 (defvar *orgtbl-efmt* nil "Format for numbers.")
4550 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4551 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4552 (defvar *orgtbl-lstart* nil "Text starting a row.")
4553 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4554 (defvar *orgtbl-lend* nil "Text ending a row.")
4555 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4557 (defsubst orgtbl-get-fmt (fmt i)
4558 "Retrieve the format from FMT corresponding to the Ith column."
4559 (if (and (not (functionp fmt)) (consp fmt))
4560 (plist-get fmt i)
4561 fmt))
4563 (defsubst orgtbl-apply-fmt (fmt &rest args)
4564 "Apply format FMT to arguments ARGS.
4565 When FMT is nil, return the first argument from ARGS."
4566 (cond ((functionp fmt) (apply fmt args))
4567 (fmt (apply 'format fmt args))
4568 (args (car args))
4569 (t args)))
4571 (defsubst orgtbl-eval-str (str)
4572 "If STR is a function, evaluate it with no arguments."
4573 (if (functionp str)
4574 (funcall str)
4575 str))
4577 (defun orgtbl-format-line (line)
4578 "Format LINE as a table row."
4579 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4580 (let* ((i 0)
4581 (line
4582 (mapcar
4583 (lambda (f)
4584 (setq i (1+ i))
4585 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4586 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4587 (orgtbl-apply-fmt efmt (match-string 1 f)
4588 (match-string 2 f))
4589 f)))
4590 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4591 *orgtbl-default-fmt*)
4592 f)))
4593 line)))
4594 (push (if *orgtbl-lfmt*
4595 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4596 (concat (orgtbl-eval-str *orgtbl-lstart*)
4597 (mapconcat 'identity line *orgtbl-sep*)
4598 (orgtbl-eval-str *orgtbl-lend*)))
4599 *orgtbl-rtn*))))
4601 (defun orgtbl-format-section (section-stopper)
4602 "Format lines until the first occurrence of SECTION-STOPPER."
4603 (let (prevline)
4604 (progn
4605 (while (not (eq (car *orgtbl-table*) section-stopper))
4606 (if prevline (orgtbl-format-line prevline))
4607 (setq prevline (pop *orgtbl-table*)))
4608 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4609 (*orgtbl-lend* *orgtbl-llend*)
4610 (*orgtbl-lfmt* *orgtbl-llfmt*))
4611 (orgtbl-format-line prevline))))))
4613 ;;;###autoload
4614 (defun orgtbl-to-generic (table params &optional backend)
4615 "Convert the orgtbl-mode TABLE to some other format.
4616 This generic routine can be used for many standard cases.
4617 TABLE is a list, each entry either the symbol `hline' for a horizontal
4618 separator line, or a list of fields for that line.
4619 PARAMS is a property list of parameters that can influence the conversion.
4620 A third optional argument BACKEND can be used to convert the content of
4621 the cells using a specific export back-end.
4623 For the generic converter, some parameters are obligatory: you need to
4624 specify either :lfmt, or all of (:lstart :lend :sep).
4626 Valid parameters are:
4628 :splice When set to t, return only table body lines, don't wrap
4629 them into :tstart and :tend. Default is nil. When :splice
4630 is non-nil, this also means that the exporter should not look
4631 for and interpret header and footer sections.
4633 :hline String to be inserted on horizontal separation lines.
4634 May be nil to ignore hlines.
4636 :sep Separator between two fields
4637 :remove-nil-lines Do not include lines that evaluate to nil.
4639 Each in the following group may be either a string or a function
4640 of no arguments returning a string:
4642 :tstart String to start the table. Ignored when :splice is t.
4643 :tend String to end the table. Ignored when :splice is t.
4644 :lstart String to start a new table line.
4645 :llstart String to start the last table line, defaults to :lstart.
4646 :lend String to end a table line
4647 :llend String to end the last table line, defaults to :lend.
4649 Each in the following group may be a string, a function of one
4650 argument (the field or line) returning a string, or a plist
4651 mapping columns to either of the above:
4653 :lfmt Format for entire line, with enough %s to capture all fields.
4654 If this is present, :lstart, :lend, and :sep are ignored.
4655 :llfmt Format for the entire last line, defaults to :lfmt.
4656 :fmt A format to be used to wrap the field, should contain
4657 %s for the original field value. For example, to wrap
4658 everything in dollars, you could use :fmt \"$%s$\".
4659 This may also be a property list with column numbers and
4660 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4661 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4662 Same as above, specific for the header lines in the table.
4663 All lines before the first hline are treated as header.
4664 If any of these is not present, the data line value is used.
4666 This may be either a string or a function of two arguments:
4668 :efmt Use this format to print numbers with exponentials.
4669 The format should have %s twice for inserting mantissa
4670 and exponent, for example \"%s\\\\times10^{%s}\". This
4671 may also be a property list with column numbers and
4672 formats. :fmt will still be applied after :efmt.
4674 In addition to this, the parameters :skip and :skipcols are always handled
4675 directly by `orgtbl-send-table'. See manual."
4676 (let* ((splicep (plist-get params :splice))
4677 (hline (plist-get params :hline))
4678 (skipheadrule (plist-get params :skipheadrule))
4679 (remove-nil-linesp (plist-get params :remove-nil-lines))
4680 (remove-newlines (plist-get params :remove-newlines))
4681 (*orgtbl-hline* hline)
4682 (*orgtbl-table* table)
4683 (*orgtbl-sep* (plist-get params :sep))
4684 (*orgtbl-efmt* (plist-get params :efmt))
4685 (*orgtbl-lstart* (plist-get params :lstart))
4686 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4687 (*orgtbl-lend* (plist-get params :lend))
4688 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4689 (*orgtbl-lfmt* (plist-get params :lfmt))
4690 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4691 (*orgtbl-fmt* (plist-get params :fmt))
4692 *orgtbl-rtn*)
4693 ;; Convert cells content to backend BACKEND
4694 (when backend
4695 (setq *orgtbl-table*
4696 (mapcar
4697 (lambda(r)
4698 (if (listp r)
4699 (mapcar
4700 (lambda (c)
4701 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4704 *orgtbl-table*)))
4705 ;; Put header
4706 (unless splicep
4707 (when (plist-member params :tstart)
4708 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4709 (if tstart (push tstart *orgtbl-rtn*)))))
4710 ;; If we have a heading, format it and handle the trailing hline.
4711 (if (and (not splicep)
4712 (or (consp (car *orgtbl-table*))
4713 (consp (nth 1 *orgtbl-table*)))
4714 (memq 'hline (cdr *orgtbl-table*)))
4715 (progn
4716 (when (eq 'hline (car *orgtbl-table*))
4717 ;; There is a hline before the first data line
4718 (and hline (push hline *orgtbl-rtn*))
4719 (pop *orgtbl-table*))
4720 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4721 *orgtbl-lstart*))
4722 (*orgtbl-llstart* (or (plist-get params :hllstart)
4723 *orgtbl-llstart*))
4724 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4725 (*orgtbl-llend* (or (plist-get params :hllend)
4726 (plist-get params :hlend) *orgtbl-llend*))
4727 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4728 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4729 (plist-get params :hlfmt) *orgtbl-llfmt*))
4730 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4731 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4732 (orgtbl-format-section 'hline))
4733 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4734 (pop *orgtbl-table*)))
4735 ;; Now format the main section.
4736 (orgtbl-format-section nil)
4737 (unless splicep
4738 (when (plist-member params :tend)
4739 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4740 (if tend (push tend *orgtbl-rtn*)))))
4741 (mapconcat (if remove-newlines
4742 (lambda (tend)
4743 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4744 'identity)
4745 (nreverse (if remove-nil-linesp
4746 (remq nil *orgtbl-rtn*)
4747 *orgtbl-rtn*)) "\n")))
4749 ;;;###autoload
4750 (defun orgtbl-to-tsv (table params)
4751 "Convert the orgtbl-mode table to TAB separated material."
4752 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4753 ;;;###autoload
4754 (defun orgtbl-to-csv (table params)
4755 "Convert the orgtbl-mode table to CSV material.
4756 This does take care of the proper quoting of fields with comma or quotes."
4757 (orgtbl-to-generic table (org-combine-plists
4758 '(:sep "," :fmt org-quote-csv-field)
4759 params)))
4761 ;;;###autoload
4762 (defun orgtbl-to-latex (table params)
4763 "Convert the orgtbl-mode TABLE to LaTeX.
4764 TABLE is a list, each entry either the symbol `hline' for a horizontal
4765 separator line, or a list of fields for that line.
4766 PARAMS is a property list of parameters that can influence the conversion.
4767 Supports all parameters from `orgtbl-to-generic'. Most important for
4768 LaTeX are:
4770 :splice When set to t, return only table body lines, don't wrap
4771 them into a tabular environment. Default is nil.
4773 :fmt A format to be used to wrap the field, should contain %s for the
4774 original field value. For example, to wrap everything in dollars,
4775 use :fmt \"$%s$\". This may also be a property list with column
4776 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4777 The format may also be a function that formats its one argument.
4779 :efmt Format for transforming numbers with exponentials. The format
4780 should have %s twice for inserting mantissa and exponent, for
4781 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4782 This may also be a property list with column numbers and formats.
4783 The format may also be a function that formats its two arguments.
4785 :llend If you find too much space below the last line of a table,
4786 pass a value of \"\" for :llend to suppress the final \\\\.
4788 The general parameters :skip and :skipcols have already been applied when
4789 this function is called."
4790 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4791 org-table-last-alignment ""))
4792 (params2
4793 (list
4794 :tstart (concat "\\begin{tabular}{" alignment "}")
4795 :tend "\\end{tabular}"
4796 :lstart "" :lend " \\\\" :sep " & "
4797 :efmt "%s\\,(%s)" :hline "\\hline")))
4798 (require 'ox-latex)
4799 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4801 ;;;###autoload
4802 (defun orgtbl-to-html (table params)
4803 "Convert the orgtbl-mode TABLE to HTML.
4804 TABLE is a list, each entry either the symbol `hline' for a horizontal
4805 separator line, or a list of fields for that line.
4806 PARAMS is a property list of parameters that can influence the conversion.
4807 Currently this function recognizes the following parameters:
4809 :splice When set to t, return only table body lines, don't wrap
4810 them into a <table> environment. Default is nil.
4812 The general parameters :skip and :skipcols have already been applied when
4813 this function is called. The function does *not* use `orgtbl-to-generic',
4814 so you cannot specify parameters for it."
4815 (require 'ox-html)
4816 (let ((output (org-export-string-as
4817 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4818 (if (not (plist-get params :splice)) output
4819 (org-trim
4820 (replace-regexp-in-string
4821 "\\`<table .*>\n" ""
4822 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4824 ;;;###autoload
4825 (defun orgtbl-to-texinfo (table params)
4826 "Convert the orgtbl-mode TABLE to TeXInfo.
4827 TABLE is a list, each entry either the symbol `hline' for a horizontal
4828 separator line, or a list of fields for that line.
4829 PARAMS is a property list of parameters that can influence the conversion.
4830 Supports all parameters from `orgtbl-to-generic'. Most important for
4831 TeXInfo are:
4833 :splice nil/t When set to t, return only table body lines, don't wrap
4834 them into a multitable environment. Default is nil.
4836 :fmt fmt A format to be used to wrap the field, should contain
4837 %s for the original field value. For example, to wrap
4838 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4839 This may also be a property list with column numbers and
4840 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4841 Each format also may be a function that formats its one
4842 argument.
4844 :cf \"f1 f2..\" The column fractions for the table. By default these
4845 are computed automatically from the width of the columns
4846 under org-mode.
4848 The general parameters :skip and :skipcols have already been applied when
4849 this function is called."
4850 (let* ((total (float (apply '+ org-table-last-column-widths)))
4851 (colfrac (or (plist-get params :cf)
4852 (mapconcat
4853 (lambda (x) (format "%.3f" (/ (float x) total)))
4854 org-table-last-column-widths " ")))
4855 (params2
4856 (list
4857 :tstart (concat "@multitable @columnfractions " colfrac)
4858 :tend "@end multitable"
4859 :lstart "@item " :lend "" :sep " @tab "
4860 :hlstart "@headitem ")))
4861 (require 'ox-texinfo)
4862 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4864 ;;;###autoload
4865 (defun orgtbl-to-orgtbl (table params)
4866 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4867 Useful when slicing one table into many. The :hline, :sep,
4868 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4869 and :tend suppress strings without splicing; they can be set to
4870 provide ORGTBL directives for the generated table."
4871 (let* ((params2
4872 (list
4873 :remove-newlines t
4874 :tstart nil :tend nil
4875 :hline "|---"
4876 :sep " | "
4877 :lstart "| "
4878 :lend " |"))
4879 (params (org-combine-plists params2 params)))
4880 (with-temp-buffer
4881 (insert (orgtbl-to-generic table params))
4882 (goto-char (point-min))
4883 (while (re-search-forward org-table-hline-regexp nil t)
4884 (org-table-align))
4885 (buffer-substring 1 (buffer-size)))))
4887 (defun orgtbl-to-table.el (table params)
4888 "Convert the orgtbl-mode TABLE into a table.el table."
4889 (with-temp-buffer
4890 (insert (orgtbl-to-orgtbl table params))
4891 (org-table-align)
4892 (replace-regexp-in-string
4893 "-|" "-+"
4894 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4896 (defun orgtbl-to-unicode (table params)
4897 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4898 You need the ascii-art-to-unicode.el package for this. You can download
4899 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4900 (with-temp-buffer
4901 (insert (orgtbl-to-table.el table params))
4902 (goto-char (point-min))
4903 (if (or (featurep 'ascii-art-to-unicode)
4904 (require 'ascii-art-to-unicode nil t))
4905 (aa2u)
4906 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4907 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4908 "Link to ascii-art-to-unicode.el") org-stored-links))
4909 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4910 (buffer-string)))
4912 (defun org-table-get-remote-range (name-or-id form)
4913 "Get a field value or a list of values in a range from table at ID.
4915 NAME-OR-ID may be the name of a table in the current file as set
4916 by a \"#+NAME:\" directive. The first table following this line
4917 will then be used. Alternatively, it may be an ID referring to
4918 any entry, also in a different file. In this case, the first
4919 table in that entry will be referenced.
4920 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4921 \"@I$2..@II$2\". All the references must be absolute, not relative.
4923 The return value is either a single string for a single field, or a
4924 list of the fields in the rectangle."
4925 (save-match-data
4926 (let ((case-fold-search t) (id-loc nil)
4927 ;; Protect a bunch of variables from being overwritten
4928 ;; by the context of the remote table
4929 org-table-column-names org-table-column-name-regexp
4930 org-table-local-parameters org-table-named-field-locations
4931 org-table-current-line-types org-table-current-begin-line
4932 org-table-current-begin-pos org-table-dlines
4933 org-table-current-ncol
4934 org-table-hlines org-table-last-alignment
4935 org-table-last-column-widths org-table-last-alignment
4936 org-table-last-column-widths tbeg
4937 buffer loc)
4938 (setq form (org-table-convert-refs-to-rc form))
4939 (save-excursion
4940 (save-restriction
4941 (widen)
4942 (save-excursion
4943 (goto-char (point-min))
4944 (if (re-search-forward
4945 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
4946 (regexp-quote name-or-id) "[ \t]*$")
4947 nil t)
4948 (setq buffer (current-buffer) loc (match-beginning 0))
4949 (setq id-loc (org-id-find name-or-id 'marker))
4950 (unless (and id-loc (markerp id-loc))
4951 (user-error "Can't find remote table \"%s\"" name-or-id))
4952 (setq buffer (marker-buffer id-loc)
4953 loc (marker-position id-loc))
4954 (move-marker id-loc nil)))
4955 (with-current-buffer buffer
4956 (save-excursion
4957 (save-restriction
4958 (widen)
4959 (goto-char loc)
4960 (forward-char 1)
4961 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4962 (not (match-beginning 1)))
4963 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
4964 (setq tbeg (point-at-bol))
4965 (org-table-get-specials)
4966 (setq form (org-table-formula-substitute-names
4967 (org-table-formula-handle-first/last-rc form)))
4968 (if (and (string-match org-table-range-regexp form)
4969 (> (length (match-string 0 form)) 1))
4970 (save-match-data
4971 (org-table-get-range (match-string 0 form) tbeg 1))
4972 form)))))))))
4974 (defmacro org-define-lookup-function (mode)
4975 (let ((mode-str (symbol-name mode))
4976 (first-p (equal mode 'first))
4977 (all-p (equal mode 'all)))
4978 (let ((plural-str (if all-p "s" "")))
4979 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4980 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4981 If R-LIST is nil, return matching element%s of S-LIST.
4982 If PREDICATE is not nil, use it instead of `equal' to match VAL.
4983 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
4984 This function is generated by a call to the macro `org-define-lookup-function'."
4985 mode-str plural-str plural-str plural-str)
4986 (let ,(let ((lvars '((p (or predicate 'equal))
4987 (sl s-list)
4988 (rl (or r-list s-list))
4989 (ret nil))))
4990 (if first-p (add-to-list 'lvars '(match-p nil)))
4991 lvars)
4992 (while ,(if first-p '(and (not match-p) sl) 'sl)
4993 (progn
4994 (if (funcall p val (car sl))
4995 (progn
4996 ,(if first-p '(setq match-p t))
4997 (let ((rval (car rl)))
4998 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
4999 (setq sl (cdr sl) rl (cdr rl))))
5000 ret)))))
5002 (org-define-lookup-function first)
5003 (org-define-lookup-function last)
5004 (org-define-lookup-function all)
5006 (provide 'org-table)
5008 ;; Local variables:
5009 ;; generated-autoload-file: "org-loaddefs.el"
5010 ;; End:
5012 ;;; org-table.el ends here