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