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