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