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