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