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