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