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