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