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