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