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