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