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