Move `org-do-sort' into "org-table.el"
[org-mode.git] / lisp / org-table.el
blob6b33edaf4cdf327b90da43a7d82f57f93eb18c13
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the table editor and spreadsheet for Org-mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org-mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
35 ;;; Code:
37 (eval-when-compile
38 (require 'cl))
39 (require 'org)
41 (declare-function org-export-string-as "ox"
42 (string backend &optional body-only ext-plist))
43 (declare-function 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 (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 (save-excursion
935 (if (not (re-search-forward
936 (if table-type org-table-any-border-regexp
937 org-table-border-regexp)
938 nil t))
939 (goto-char (point-max))
940 (goto-char (match-beginning 0)))
941 (point-marker)))
943 ;;;###autoload
944 (defun org-table-justify-field-maybe (&optional new)
945 "Justify the current field, text to left, number to right.
946 Optional argument NEW may specify text to replace the current field content."
947 (cond
948 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
949 ((org-at-table-hline-p))
950 ((and (not new)
951 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
952 (current-buffer)))
953 (< (point) org-table-aligned-begin-marker)
954 (>= (point) org-table-aligned-end-marker)))
955 ;; This is not the same table, force a full re-align
956 (setq org-table-may-need-update t))
957 (t ;; realign the current field, based on previous full realign
958 (let* ((pos (point)) s
959 (col (org-table-current-column))
960 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
961 l f n o e)
962 (when (> col 0)
963 (skip-chars-backward "^|\n")
964 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
965 (progn
966 (setq s (match-string 1)
967 o (match-string 0)
968 l (max 1
969 (- (org-string-width
970 (buffer-substring-no-properties
971 (match-end 0) (match-beginning 0))) 3))
972 e (not (= (match-beginning 2) (match-end 2))))
973 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
974 l (if e "|" (setq org-table-may-need-update t) ""))
975 n (format f s))
976 (if new
977 (if (<= (org-string-width new) l)
978 (setq n (format f new))
979 (setq n (concat new "|") org-table-may-need-update t)))
980 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
981 (or (equal n o)
982 (let (org-table-may-need-update)
983 (replace-match n t t))))
984 (setq org-table-may-need-update t))
985 (goto-char pos))))))
987 ;;;###autoload
988 (defun org-table-next-field ()
989 "Go to the next field in the current table, creating new lines as needed.
990 Before doing so, re-align the table if necessary."
991 (interactive)
992 (org-table-maybe-eval-formula)
993 (org-table-maybe-recalculate-line)
994 (if (and org-table-automatic-realign
995 org-table-may-need-update)
996 (org-table-align))
997 (let ((end (org-table-end)))
998 (if (org-at-table-hline-p)
999 (end-of-line 1))
1000 (condition-case nil
1001 (progn
1002 (re-search-forward "|" end)
1003 (if (looking-at "[ \t]*$")
1004 (re-search-forward "|" end))
1005 (if (and (looking-at "-")
1006 org-table-tab-jumps-over-hlines
1007 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
1008 (goto-char (match-beginning 1)))
1009 (if (looking-at "-")
1010 (progn
1011 (beginning-of-line 0)
1012 (org-table-insert-row 'below))
1013 (if (looking-at " ") (forward-char 1))))
1014 (error
1015 (org-table-insert-row 'below)))))
1017 ;;;###autoload
1018 (defun org-table-previous-field ()
1019 "Go to the previous field in the table.
1020 Before doing so, re-align the table if necessary."
1021 (interactive)
1022 (org-table-justify-field-maybe)
1023 (org-table-maybe-recalculate-line)
1024 (if (and org-table-automatic-realign
1025 org-table-may-need-update)
1026 (org-table-align))
1027 (if (org-at-table-hline-p)
1028 (end-of-line 1))
1029 (condition-case nil
1030 (progn
1031 (re-search-backward "|" (org-table-begin))
1032 (re-search-backward "|" (org-table-begin)))
1033 (error (user-error "Cannot move to previous table field")))
1034 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1035 (re-search-backward "|" (org-table-begin)))
1036 (if (looking-at "| ?")
1037 (goto-char (match-end 0))))
1039 (defun org-table-beginning-of-field (&optional n)
1040 "Move to the end of the current table field.
1041 If already at or after the end, move to the end of the next table field.
1042 With numeric argument N, move N-1 fields forward 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 beginning of the current table field.
1056 If already at or before the beginning, move to the beginning of the
1057 previous field.
1058 With numeric argument N, move N-1 fields backward first."
1059 (interactive "p")
1060 (let ((pos (point)))
1061 (while (> n 1)
1062 (setq n (1- n))
1063 (org-table-next-field))
1064 (when (re-search-forward "|" (point-at-eol 1) t)
1065 (backward-char 1)
1066 (skip-chars-backward " ")
1067 (if (and (equal (char-before (point)) ?|) (looking-at " "))
1068 (forward-char 1)))
1069 (if (<= (point) pos) (org-table-end-of-field 2))))
1071 ;;;###autoload
1072 (defun org-table-next-row ()
1073 "Go to the next row (same column) in the current table.
1074 Before doing so, re-align the table if necessary."
1075 (interactive)
1076 (org-table-maybe-eval-formula)
1077 (org-table-maybe-recalculate-line)
1078 (if (or (looking-at "[ \t]*$")
1079 (save-excursion (skip-chars-backward " \t") (bolp)))
1080 (newline)
1081 (if (and org-table-automatic-realign
1082 org-table-may-need-update)
1083 (org-table-align))
1084 (let ((col (org-table-current-column)))
1085 (beginning-of-line 2)
1086 (if (or (not (org-at-table-p))
1087 (org-at-table-hline-p))
1088 (progn
1089 (beginning-of-line 0)
1090 (org-table-insert-row 'below)))
1091 (org-table-goto-column col)
1092 (skip-chars-backward "^|\n\r")
1093 (if (looking-at " ") (forward-char 1)))))
1095 ;;;###autoload
1096 (defun org-table-copy-down (n)
1097 "Copy the value of the current field one row below.
1099 If the field at the cursor is empty, copy the content of the
1100 nearest non-empty field above. With argument N, use the Nth
1101 non-empty field.
1103 If the current field is not empty, it is copied down to the next
1104 row, and the cursor is moved with it. Therefore, repeating this
1105 command causes the column to be filled row-by-row.
1107 If the variable `org-table-copy-increment' is non-nil and the
1108 field is an integer or a timestamp, it will be incremented while
1109 copying. By default, increment by the difference between the
1110 value in the current field and the one in the field above. To
1111 increment using a fixed integer, set `org-table-copy-increment'
1112 to a number. In the case of a timestamp, increment by days."
1113 (interactive "p")
1114 (let* ((colpos (org-table-current-column))
1115 (col (current-column))
1116 (field (save-excursion (org-table-get-field)))
1117 (field-up (or (save-excursion
1118 (org-table-get (1- (org-table-current-line))
1119 (org-table-current-column))) ""))
1120 (non-empty (string-match "[^ \t]" field))
1121 (non-empty-up (string-match "[^ \t]" field-up))
1122 (beg (org-table-begin))
1123 (orig-n n)
1124 txt txt-up inc)
1125 (org-table-check-inside-data-field)
1126 (if (not non-empty)
1127 (save-excursion
1128 (setq txt
1129 (catch 'exit
1130 (while (progn (beginning-of-line 1)
1131 (re-search-backward org-table-dataline-regexp
1132 beg t))
1133 (org-table-goto-column colpos t)
1134 (if (and (looking-at
1135 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1136 (<= (setq n (1- n)) 0))
1137 (throw 'exit (match-string 1))))))
1138 (setq field-up
1139 (catch 'exit
1140 (while (progn (beginning-of-line 1)
1141 (re-search-backward org-table-dataline-regexp
1142 beg t))
1143 (org-table-goto-column colpos t)
1144 (if (and (looking-at
1145 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1146 (<= (setq n (1- n)) 0))
1147 (throw 'exit (match-string 1))))))
1148 (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
1149 ;; Above field was not empty, go down to the next row
1150 (setq txt (org-trim field))
1151 (org-table-next-row)
1152 (org-table-blank-field))
1153 (if non-empty-up (setq txt-up (org-trim field-up)))
1154 (setq inc (cond
1155 ((numberp org-table-copy-increment) org-table-copy-increment)
1156 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
1157 (string-match org-ts-regexp3 txt))
1158 (- (org-time-string-to-absolute txt)
1159 (org-time-string-to-absolute txt-up)))
1160 ((string-match org-ts-regexp3 txt) 1)
1161 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up)
1162 (- (string-to-number txt)
1163 (string-to-number (match-string 0 txt-up))))
1164 (t 1)))
1165 (t 1)))
1166 (if (not txt)
1167 (user-error "No non-empty field found")
1168 (if (and org-table-copy-increment
1169 (not (equal orig-n 0))
1170 (string-match "^[-+^/*0-9eE.]+$" txt)
1171 (< (string-to-number txt) 100000000))
1172 (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
1173 (insert txt)
1174 (org-move-to-column col)
1175 (if (and org-table-copy-increment (org-at-timestamp-p t))
1176 (org-timestamp-up-day inc)
1177 (org-table-maybe-recalculate-line))
1178 (org-table-align)
1179 (org-move-to-column col))))
1181 (defun org-table-check-inside-data-field (&optional noerror)
1182 "Is point inside a table data field?
1183 I.e. not on a hline or before the first or after the last column?
1184 This actually throws an error, so it aborts the current command."
1185 (if (or (not (org-at-table-p))
1186 (= (org-table-current-column) 0)
1187 (org-at-table-hline-p)
1188 (looking-at "[ \t]*$"))
1189 (if noerror
1191 (user-error "Not in table data field"))
1194 (defvar org-table-clip nil
1195 "Clipboard for table regions.")
1197 (defun org-table-get (line column)
1198 "Get the field in table line LINE, column COLUMN.
1199 If LINE is larger than the number of data lines in the table, the function
1200 returns nil. However, if COLUMN is too large, we will simply return an
1201 empty string.
1202 If LINE is nil, use the current line.
1203 If COLUMN is nil, use the current column."
1204 (setq column (or column (org-table-current-column)))
1205 (save-excursion
1206 (and (or (not line) (org-table-goto-line line))
1207 (org-trim (org-table-get-field column)))))
1209 (defun org-table-put (line column value &optional align)
1210 "Put VALUE into line LINE, column COLUMN.
1211 When ALIGN is set, also realign the table."
1212 (setq column (or column (org-table-current-column)))
1213 (prog1 (save-excursion
1214 (and (or (not line) (org-table-goto-line line))
1215 (progn (org-table-goto-column column nil 'force) t)
1216 (org-table-get-field column value)))
1217 (and align (org-table-align))))
1219 (defun org-table-current-line ()
1220 "Return the index of the current data line."
1221 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1222 (save-excursion
1223 (goto-char (org-table-begin))
1224 (while (and (re-search-forward org-table-dataline-regexp end t)
1225 (setq cnt (1+ cnt))
1226 (< (point-at-eol) pos))))
1227 cnt))
1229 (defun org-table-goto-line (N)
1230 "Go to the Nth data line in the current table.
1231 Return t when the line exists, nil if it does not exist."
1232 (goto-char (org-table-begin))
1233 (let ((end (org-table-end)) (cnt 0))
1234 (while (and (re-search-forward org-table-dataline-regexp end t)
1235 (< (setq cnt (1+ cnt)) N)))
1236 (= cnt N)))
1238 ;;;###autoload
1239 (defun org-table-blank-field ()
1240 "Blank the current table field or active region."
1241 (interactive)
1242 (org-table-check-inside-data-field)
1243 (if (and (org-called-interactively-p 'any) (org-region-active-p))
1244 (let (org-table-clip)
1245 (org-table-cut-region (region-beginning) (region-end)))
1246 (skip-chars-backward "^|")
1247 (backward-char 1)
1248 (if (looking-at "|[^|\n]+")
1249 (let* ((pos (match-beginning 0))
1250 (match (match-string 0))
1251 (len (org-string-width match)))
1252 (replace-match (concat "|" (make-string (1- len) ?\ )))
1253 (goto-char (+ 2 pos))
1254 (substring match 1)))))
1256 (defun org-table-get-field (&optional n replace)
1257 "Return the value of the field in column N of current row.
1258 N defaults to current field.
1259 If REPLACE is a string, replace field with this value. The return value
1260 is always the old value."
1261 (and n (org-table-goto-column n))
1262 (skip-chars-backward "^|\n")
1263 (backward-char 1)
1264 (if (looking-at "|[^|\r\n]*")
1265 (let* ((pos (match-beginning 0))
1266 (val (buffer-substring (1+ pos) (match-end 0))))
1267 (if replace
1268 (replace-match (concat "|" (if (equal replace "") " " replace))
1269 t t))
1270 (goto-char (min (point-at-eol) (+ 2 pos)))
1271 val)
1272 (forward-char 1) ""))
1274 ;;;###autoload
1275 (defun org-table-field-info (arg)
1276 "Show info about the current field, and highlight any reference at point."
1277 (interactive "P")
1278 (unless (org-at-table-p) (user-error "Not at a table"))
1279 (org-table-get-specials)
1280 (save-excursion
1281 (let* ((pos (point))
1282 (col (org-table-current-column))
1283 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1284 (name (car (rassoc (list (org-current-line) col)
1285 org-table-named-field-locations)))
1286 (eql (org-table-expand-lhs-ranges
1287 (mapcar
1288 (lambda (e)
1289 (cons (org-table-formula-handle-first/last-rc
1290 (car e)) (cdr e)))
1291 (org-table-get-stored-formulas))))
1292 (dline (org-table-current-dline))
1293 (ref (format "@%d$%d" dline col))
1294 (ref1 (org-table-convert-refs-to-an ref))
1295 (fequation (or (assoc name eql) (assoc ref eql)))
1296 (cequation (assoc (int-to-string col) eql))
1297 (eqn (or fequation cequation)))
1298 (if (and eqn (get-text-property 0 :orig-eqn (car eqn)))
1299 (setq eqn (get-text-property 0 :orig-eqn (car eqn))))
1300 (goto-char pos)
1301 (condition-case nil
1302 (org-table-show-reference 'local)
1303 (error nil))
1304 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1305 dline col
1306 (if cname (concat " or $" cname) "")
1307 dline col ref1
1308 (if name (concat " or $" name) "")
1309 ;; FIXME: formula info not correct if special table line
1310 (if eqn
1311 (concat ", formula: "
1312 (org-table-formula-to-user
1313 (concat
1314 (if (string-match "^[$@]"(car eqn)) "" "$")
1315 (car eqn) "=" (cdr eqn))))
1316 "")))))
1318 (defun org-table-current-column ()
1319 "Find out which column we are in."
1320 (interactive)
1321 (if (org-called-interactively-p 'any) (org-table-check-inside-data-field))
1322 (save-excursion
1323 (let ((cnt 0) (pos (point)))
1324 (beginning-of-line 1)
1325 (while (search-forward "|" pos t)
1326 (setq cnt (1+ cnt)))
1327 (when (org-called-interactively-p 'interactive)
1328 (message "In table column %d" cnt))
1329 cnt)))
1331 ;;;###autoload
1332 (defun org-table-current-dline ()
1333 "Find out what table data line we are in.
1334 Only data lines count for this."
1335 (interactive)
1336 (when (org-called-interactively-p 'any)
1337 (org-table-check-inside-data-field))
1338 (save-excursion
1339 (let ((cnt 0) (pos (point)))
1340 (goto-char (org-table-begin))
1341 (while (<= (point) pos)
1342 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1343 (beginning-of-line 2))
1344 (when (org-called-interactively-p 'any)
1345 (message "This is table line %d" cnt))
1346 cnt)))
1348 ;;;###autoload
1349 (defun org-table-goto-column (n &optional on-delim force)
1350 "Move the cursor to the Nth column in the current table line.
1351 With optional argument ON-DELIM, stop with point before the left delimiter
1352 of the field.
1353 If there are less than N fields, just go to after the last delimiter.
1354 However, when FORCE is non-nil, create new columns if necessary."
1355 (interactive "p")
1356 (beginning-of-line 1)
1357 (when (> n 0)
1358 (while (and (> (setq n (1- n)) -1)
1359 (or (search-forward "|" (point-at-eol) t)
1360 (and force
1361 (progn (end-of-line 1)
1362 (skip-chars-backward "^|")
1363 (insert " | ")
1364 t)))))
1365 (when (and force (not (looking-at ".*|")))
1366 (save-excursion (end-of-line 1) (insert " | ")))
1367 (if on-delim
1368 (backward-char 1)
1369 (if (looking-at " ") (forward-char 1)))))
1371 ;;;###autoload
1372 (defun org-table-insert-column ()
1373 "Insert a new column into the table."
1374 (interactive)
1375 (if (not (org-at-table-p))
1376 (user-error "Not at a table"))
1377 (org-table-find-dataline)
1378 (let* ((col (max 1 (org-table-current-column)))
1379 (beg (org-table-begin))
1380 (end (org-table-end))
1381 ;; Current cursor position
1382 (linepos (org-current-line))
1383 (colpos col))
1384 (goto-char beg)
1385 (while (< (point) end)
1386 (if (org-at-table-hline-p)
1388 (org-table-goto-column col t)
1389 (insert "| "))
1390 (beginning-of-line 2))
1391 (move-marker end nil)
1392 (org-goto-line linepos)
1393 (org-table-goto-column colpos)
1394 (org-table-align)
1395 (when (or (not org-table-fix-formulas-confirm)
1396 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1397 (org-table-fix-formulas "$" nil (1- col) 1)
1398 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1400 (defun org-table-find-dataline ()
1401 "Find a data line in the current table, which is needed for column commands."
1402 (if (and (org-at-table-p)
1403 (not (org-at-table-hline-p)))
1405 (let ((col (current-column))
1406 (end (org-table-end)))
1407 (org-move-to-column col)
1408 (while (and (< (point) end)
1409 (or (not (= (current-column) col))
1410 (org-at-table-hline-p)))
1411 (beginning-of-line 2)
1412 (org-move-to-column col))
1413 (if (and (org-at-table-p)
1414 (not (org-at-table-hline-p)))
1416 (user-error
1417 "Please position cursor in a data line for column operations")))))
1419 (defun org-table-line-to-dline (line &optional above)
1420 "Turn a buffer line number into a data line number.
1421 If there is no data line in this line, return nil.
1422 If there is no matching dline (most likely te reference was a hline), the
1423 first dline below it is used. When ABOVE is non-nil, the one above is used."
1424 (catch 'exit
1425 (let ((ll (length org-table-dlines))
1427 (if above
1428 (progn
1429 (setq i (1- ll))
1430 (while (> i 0)
1431 (if (<= (aref org-table-dlines i) line)
1432 (throw 'exit i))
1433 (setq i (1- i))))
1434 (setq i 1)
1435 (while (< i ll)
1436 (if (>= (aref org-table-dlines i) line)
1437 (throw 'exit i))
1438 (setq i (1+ i)))))
1439 nil))
1441 ;;;###autoload
1442 (defun org-table-delete-column ()
1443 "Delete a column from the table."
1444 (interactive)
1445 (if (not (org-at-table-p))
1446 (user-error "Not at a table"))
1447 (org-table-find-dataline)
1448 (org-table-check-inside-data-field)
1449 (let* ((col (org-table-current-column))
1450 (beg (org-table-begin))
1451 (end (org-table-end))
1452 ;; Current cursor position
1453 (linepos (org-current-line))
1454 (colpos col))
1455 (goto-char beg)
1456 (while (< (point) end)
1457 (if (org-at-table-hline-p)
1459 (org-table-goto-column col t)
1460 (and (looking-at "|[^|\n]+|")
1461 (replace-match "|")))
1462 (beginning-of-line 2))
1463 (move-marker end nil)
1464 (org-goto-line linepos)
1465 (org-table-goto-column colpos)
1466 (org-table-align)
1467 (when (or (not org-table-fix-formulas-confirm)
1468 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1469 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1470 col -1 col)
1471 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1472 col -1 col))))
1474 ;;;###autoload
1475 (defun org-table-move-column-right ()
1476 "Move column to the right."
1477 (interactive)
1478 (org-table-move-column nil))
1479 ;;;###autoload
1480 (defun org-table-move-column-left ()
1481 "Move column to the left."
1482 (interactive)
1483 (org-table-move-column 'left))
1485 ;;;###autoload
1486 (defun org-table-move-column (&optional left)
1487 "Move the current column to the right. With arg LEFT, move to the left."
1488 (interactive "P")
1489 (if (not (org-at-table-p))
1490 (user-error "Not at a table"))
1491 (org-table-find-dataline)
1492 (org-table-check-inside-data-field)
1493 (let* ((col (org-table-current-column))
1494 (col1 (if left (1- col) col))
1495 (beg (org-table-begin))
1496 (end (org-table-end))
1497 ;; Current cursor position
1498 (linepos (org-current-line))
1499 (colpos (if left (1- col) (1+ col))))
1500 (if (and left (= col 1))
1501 (user-error "Cannot move column further left"))
1502 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1503 (user-error "Cannot move column further right"))
1504 (goto-char beg)
1505 (while (< (point) end)
1506 (if (org-at-table-hline-p)
1508 (org-table-goto-column col1 t)
1509 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1510 (replace-match "|\\2|\\1|")))
1511 (beginning-of-line 2))
1512 (move-marker end nil)
1513 (org-goto-line linepos)
1514 (org-table-goto-column colpos)
1515 (org-table-align)
1516 (when (or (not org-table-fix-formulas-confirm)
1517 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1518 (org-table-fix-formulas
1519 "$" (list (cons (number-to-string col) (number-to-string colpos))
1520 (cons (number-to-string colpos) (number-to-string col))))
1521 (org-table-fix-formulas
1522 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1523 (cons (number-to-string colpos) (number-to-string col)))))))
1525 ;;;###autoload
1526 (defun org-table-move-row-down ()
1527 "Move table row down."
1528 (interactive)
1529 (org-table-move-row nil))
1530 ;;;###autoload
1531 (defun org-table-move-row-up ()
1532 "Move table row up."
1533 (interactive)
1534 (org-table-move-row 'up))
1536 ;;;###autoload
1537 (defun org-table-move-row (&optional up)
1538 "Move the current table line down. With arg UP, move it up."
1539 (interactive "P")
1540 (let* ((col (current-column))
1541 (pos (point))
1542 (hline1p (save-excursion (beginning-of-line 1)
1543 (looking-at org-table-hline-regexp)))
1544 (dline1 (org-table-current-dline))
1545 (dline2 (+ dline1 (if up -1 1)))
1546 (tonew (if up 0 2))
1547 txt hline2p)
1548 (beginning-of-line tonew)
1549 (unless (org-at-table-p)
1550 (goto-char pos)
1551 (user-error "Cannot move row further"))
1552 (setq hline2p (looking-at org-table-hline-regexp))
1553 (goto-char pos)
1554 (beginning-of-line 1)
1555 (setq pos (point))
1556 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1557 (delete-region (point) (1+ (point-at-eol)))
1558 (beginning-of-line tonew)
1559 (insert txt)
1560 (beginning-of-line 0)
1561 (org-move-to-column col)
1562 (unless (or hline1p hline2p
1563 (not (or (not org-table-fix-formulas-confirm)
1564 (funcall org-table-fix-formulas-confirm
1565 "Fix formulas? "))))
1566 (org-table-fix-formulas
1567 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1568 (cons (number-to-string dline2) (number-to-string dline1)))))))
1570 ;;;###autoload
1571 (defun org-table-insert-row (&optional arg)
1572 "Insert a new row above the current line into the table.
1573 With prefix ARG, insert below the current line."
1574 (interactive "P")
1575 (if (not (org-at-table-p))
1576 (user-error "Not at a table"))
1577 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1578 (new (org-table-clean-line line)))
1579 ;; Fix the first field if necessary
1580 (if (string-match "^[ \t]*| *[#$] *|" line)
1581 (setq new (replace-match (match-string 0 line) t t new)))
1582 (beginning-of-line (if arg 2 1))
1583 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1584 (beginning-of-line 0)
1585 (re-search-forward "| ?" (point-at-eol) t)
1586 (and (or org-table-may-need-update org-table-overlay-coordinates)
1587 (org-table-align))
1588 (when (or (not org-table-fix-formulas-confirm)
1589 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1590 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1592 ;;;###autoload
1593 (defun org-table-insert-hline (&optional above)
1594 "Insert a horizontal-line below the current line into the table.
1595 With prefix ABOVE, insert above the current line."
1596 (interactive "P")
1597 (if (not (org-at-table-p))
1598 (user-error "Not at a table"))
1599 (when (eobp) (insert "\n") (backward-char 1))
1600 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1601 (org-table-align))
1602 (let ((line (org-table-clean-line
1603 (buffer-substring (point-at-bol) (point-at-eol))))
1604 (col (current-column)))
1605 (while (string-match "|\\( +\\)|" line)
1606 (setq line (replace-match
1607 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1608 ?-) "|") t t line)))
1609 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1610 (beginning-of-line (if above 1 2))
1611 (insert line "\n")
1612 (beginning-of-line (if above 1 -1))
1613 (org-move-to-column col)
1614 (and org-table-overlay-coordinates (org-table-align))))
1616 ;;;###autoload
1617 (defun org-table-hline-and-move (&optional same-column)
1618 "Insert a hline and move to the row below that line."
1619 (interactive "P")
1620 (let ((col (org-table-current-column)))
1621 (org-table-maybe-eval-formula)
1622 (org-table-maybe-recalculate-line)
1623 (org-table-insert-hline)
1624 (end-of-line 2)
1625 (if (looking-at "\n[ \t]*|-")
1626 (progn (insert "\n|") (org-table-align))
1627 (org-table-next-field))
1628 (if same-column (org-table-goto-column col))))
1630 (defun org-table-clean-line (s)
1631 "Convert a table line S into a string with only \"|\" and space.
1632 In particular, this does handle wide and invisible characters."
1633 (if (string-match "^[ \t]*|-" s)
1634 ;; It's a hline, just map the characters
1635 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1636 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1637 (setq s (replace-match
1638 (concat "|" (make-string (org-string-width (match-string 1 s))
1639 ?\ ) "|")
1640 t t s)))
1643 ;;;###autoload
1644 (defun org-table-kill-row ()
1645 "Delete the current row or horizontal line from the table."
1646 (interactive)
1647 (if (not (org-at-table-p))
1648 (user-error "Not at a table"))
1649 (let ((col (current-column))
1650 (dline (org-table-current-dline)))
1651 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1652 (if (not (org-at-table-p)) (beginning-of-line 0))
1653 (org-move-to-column col)
1654 (when (or (not org-table-fix-formulas-confirm)
1655 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1656 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1657 dline -1 dline))))
1659 ;;;###autoload
1660 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func)
1661 "Sort table lines according to the column at point.
1663 The position of point indicates the column to be used for
1664 sorting, and the range of lines is the range between the nearest
1665 horizontal separator lines, or the entire table of no such lines
1666 exist. If point is before the first column, you will be prompted
1667 for the sorting column. If there is an active region, the mark
1668 specifies the first line and the sorting column, while point
1669 should be in the last line to be included into the sorting.
1671 The command then prompts for the sorting type which can be
1672 alphabetically, numerically, or by time (as given in a time stamp
1673 in the field, or as a HH:MM value). Sorting in reverse order is
1674 also possible.
1676 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1678 If SORTING-TYPE is specified when this function is called from a Lisp
1679 program, no prompting will take place. SORTING-TYPE must be a character,
1680 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1681 sorting should be done in reverse order.
1683 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1684 a function to be called to extract the key. It must return either
1685 a string or a number that should serve as the sorting key for that
1686 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1687 is specified interactively, the comparison will be either a string or
1688 numeric compare based on the type of the first key in the table."
1689 (interactive "P")
1690 (let* ((thisline (org-current-line))
1691 (thiscol (org-table-current-column))
1692 (otc org-table-overlay-coordinates)
1693 beg end bcol ecol tend tbeg column lns pos)
1694 (when (equal thiscol 0)
1695 (if (org-called-interactively-p 'any)
1696 (setq thiscol
1697 (string-to-number
1698 (read-string "Use column N for sorting: ")))
1699 (setq thiscol 1))
1700 (org-table-goto-column thiscol))
1701 (org-table-check-inside-data-field)
1702 (if (org-region-active-p)
1703 (progn
1704 (setq beg (region-beginning) end (region-end))
1705 (goto-char beg)
1706 (setq column (org-table-current-column)
1707 beg (point-at-bol))
1708 (goto-char end)
1709 (setq end (point-at-bol 2)))
1710 (setq column (org-table-current-column)
1711 pos (point)
1712 tbeg (org-table-begin)
1713 tend (org-table-end))
1714 (if (re-search-backward org-table-hline-regexp tbeg t)
1715 (setq beg (point-at-bol 2))
1716 (goto-char tbeg)
1717 (setq beg (point-at-bol 1)))
1718 (goto-char pos)
1719 (if (re-search-forward org-table-hline-regexp tend t)
1720 (setq end (point-at-bol 1))
1721 (goto-char tend)
1722 (setq end (point-at-bol))))
1723 (setq beg (move-marker (make-marker) beg)
1724 end (move-marker (make-marker) end))
1725 (untabify beg end)
1726 (goto-char beg)
1727 (org-table-goto-column column)
1728 (skip-chars-backward "^|")
1729 (setq bcol (current-column))
1730 (org-table-goto-column (1+ column))
1731 (skip-chars-backward "^|")
1732 (setq ecol (1- (current-column)))
1733 (org-table-goto-column column)
1734 (setq lns (mapcar (lambda(x) (cons
1735 (org-sort-remove-invisible
1736 (nth (1- column)
1737 (org-split-string x "[ \t]*|[ \t]*")))
1739 (org-split-string (buffer-substring beg end) "\n")))
1740 (setq lns (org-table--do-sort
1741 lns "Table" with-case sorting-type getkey-func compare-func))
1742 (when org-table-overlay-coordinates
1743 (org-table-toggle-coordinate-overlays))
1744 (delete-region beg end)
1745 (move-marker beg nil)
1746 (move-marker end nil)
1747 (insert (mapconcat 'cdr lns "\n") "\n")
1748 (org-goto-line thisline)
1749 (org-table-goto-column thiscol)
1750 (when otc (org-table-toggle-coordinate-overlays))
1751 (message "%d lines sorted, based on column %d" (length lns) column)))
1753 (defun org-table--do-sort (table what &optional with-case sorting-type getkey-func compare-func)
1754 "Sort TABLE of WHAT according to SORTING-TYPE.
1755 The user will be prompted for the SORTING-TYPE if the call to this
1756 function does not specify it.
1757 WHAT is only for the prompt, to indicate what is being sorted.
1758 The sorting key will be extracted from the car of the elements of
1759 the table. If WITH-CASE is non-nil, the sorting will be case-sensitive.
1761 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1762 a function to be called to extract the key. It must return either
1763 a string or a number that should serve as the sorting key for that
1764 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1765 is specified interactively, the comparison will be either a string or
1766 numeric compare based on the type of the first key in the table."
1767 (unless sorting-type
1768 (message
1769 "Sort %s: [a]lphabetic, [n]umeric, [t]ime, [f]unc. A/N/T/F means reversed:"
1770 what)
1771 (setq sorting-type (read-char-exclusive)))
1772 (let (extractfun comparefun tempfun)
1773 ;; Define the appropriate functions
1774 (case sorting-type
1775 ((?n ?N)
1776 (setq extractfun #'string-to-number
1777 comparefun (if (= sorting-type ?n) #'< #'>)))
1778 ((?a ?A)
1779 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
1780 (lambda(x) (downcase (org-sort-remove-invisible x))))
1781 comparefun (if (= sorting-type ?a) #'string< #'org-string>)))
1782 ((?t ?T)
1783 (setq extractfun
1784 (lambda (x)
1785 (cond ((or (string-match org-ts-regexp x)
1786 (string-match org-ts-regexp-both x))
1787 (org-float-time
1788 (org-time-string-to-time (match-string 0 x))))
1789 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
1790 (org-hh:mm-string-to-minutes x))
1791 (t 0)))
1792 comparefun (if (= sorting-type ?t) #'< #'>)))
1793 ((?f ?F)
1794 (setq tempfun (or getkey-func
1795 (intern (org-icompleting-read
1796 "Sort using function: "
1797 obarray #'fboundp t nil nil))))
1798 (let ((extract-string-p (stringp (funcall tempfun (caar table)))))
1799 (setq extractfun (if (and extract-string-p (not with-case))
1800 (lambda (x) (downcase (funcall tempfun x)))
1801 tempfun))
1802 (setq comparefun (cond (compare-func
1803 (if (= sorting-type ?f) compare-func
1804 (lambda (a b) (funcall compare-func b a))))
1805 (extract-string-p
1806 (if (= sorting-type ?f) #'string<
1807 #'org-string>))
1808 (t (if (= sorting-type ?f) #'< #'>))))))
1809 (t (error "Invalid sorting type `%c'" sorting-type)))
1811 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
1812 table)
1813 (lambda (a b) (funcall comparefun (car a) (car b))))))
1815 ;;;###autoload
1816 (defun org-table-cut-region (beg end)
1817 "Copy region in table to the clipboard and blank all relevant fields.
1818 If there is no active region, use just the field at point."
1819 (interactive (list
1820 (if (org-region-active-p) (region-beginning) (point))
1821 (if (org-region-active-p) (region-end) (point))))
1822 (org-table-copy-region beg end 'cut))
1824 ;;;###autoload
1825 (defun org-table-copy-region (beg end &optional cut)
1826 "Copy rectangular region in table to clipboard.
1827 A special clipboard is used which can only be accessed
1828 with `org-table-paste-rectangle'."
1829 (interactive (list
1830 (if (org-region-active-p) (region-beginning) (point))
1831 (if (org-region-active-p) (region-end) (point))
1832 current-prefix-arg))
1833 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1834 region cols
1835 (rpl (if cut " " nil)))
1836 (goto-char beg)
1837 (org-table-check-inside-data-field)
1838 (setq l01 (org-current-line)
1839 c01 (org-table-current-column))
1840 (goto-char end)
1841 (org-table-check-inside-data-field)
1842 (setq l02 (org-current-line)
1843 c02 (org-table-current-column))
1844 (setq l1 (min l01 l02) l2 (max l01 l02)
1845 c1 (min c01 c02) c2 (max c01 c02))
1846 (catch 'exit
1847 (while t
1848 (catch 'nextline
1849 (if (> l1 l2) (throw 'exit t))
1850 (org-goto-line l1)
1851 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1852 (setq cols nil ic1 c1 ic2 c2)
1853 (while (< ic1 (1+ ic2))
1854 (push (org-table-get-field ic1 rpl) cols)
1855 (setq ic1 (1+ ic1)))
1856 (push (nreverse cols) region)
1857 (setq l1 (1+ l1)))))
1858 (setq org-table-clip (nreverse region))
1859 (if cut (org-table-align))
1860 org-table-clip))
1862 ;;;###autoload
1863 (defun org-table-paste-rectangle ()
1864 "Paste a rectangular region into a table.
1865 The upper right corner ends up in the current field. All involved fields
1866 will be overwritten. If the rectangle does not fit into the present table,
1867 the table is enlarged as needed. The process ignores horizontal separator
1868 lines."
1869 (interactive)
1870 (unless (and org-table-clip (listp org-table-clip))
1871 (user-error "First cut/copy a region to paste!"))
1872 (org-table-check-inside-data-field)
1873 (let* ((clip org-table-clip)
1874 (line (org-current-line))
1875 (col (org-table-current-column))
1876 (org-enable-table-editor t)
1877 (org-table-automatic-realign nil)
1878 c cols field)
1879 (while (setq cols (pop clip))
1880 (while (org-at-table-hline-p) (beginning-of-line 2))
1881 (if (not (org-at-table-p))
1882 (progn (end-of-line 0) (org-table-next-field)))
1883 (setq c col)
1884 (while (setq field (pop cols))
1885 (org-table-goto-column c nil 'force)
1886 (org-table-get-field nil field)
1887 (setq c (1+ c)))
1888 (beginning-of-line 2))
1889 (org-goto-line line)
1890 (org-table-goto-column col)
1891 (org-table-align)))
1893 ;;;###autoload
1894 (defun org-table-convert ()
1895 "Convert from `org-mode' table to table.el and back.
1896 Obviously, this only works within limits. When an Org-mode table is
1897 converted to table.el, all horizontal separator lines get lost, because
1898 table.el uses these as cell boundaries and has no notion of horizontal lines.
1899 A table.el table can be converted to an Org-mode table only if it does not
1900 do row or column spanning. Multiline cells will become multiple cells.
1901 Beware, Org-mode does not test if the table can be successfully converted - it
1902 blindly applies a recipe that works for simple tables."
1903 (interactive)
1904 (require 'table)
1905 (if (org-at-table.el-p)
1906 ;; convert to Org-mode table
1907 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1908 (end (move-marker (make-marker) (org-table-end t))))
1909 (table-unrecognize-region beg end)
1910 (goto-char beg)
1911 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1912 (replace-match ""))
1913 (goto-char beg))
1914 (if (org-at-table-p)
1915 ;; convert to table.el table
1916 (let ((beg (move-marker (make-marker) (org-table-begin)))
1917 (end (move-marker (make-marker) (org-table-end))))
1918 ;; first, get rid of all horizontal lines
1919 (goto-char beg)
1920 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1921 (replace-match ""))
1922 ;; insert a hline before first
1923 (goto-char beg)
1924 (org-table-insert-hline 'above)
1925 (beginning-of-line -1)
1926 ;; insert a hline after each line
1927 (while (progn (beginning-of-line 3) (< (point) end))
1928 (org-table-insert-hline))
1929 (goto-char beg)
1930 (setq end (move-marker end (org-table-end)))
1931 ;; replace "+" at beginning and ending of hlines
1932 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1933 (replace-match "\\1+-"))
1934 (goto-char beg)
1935 (while (re-search-forward "-|[ \t]*$" end t)
1936 (replace-match "-+"))
1937 (goto-char beg)))))
1939 (defun org-table-transpose-table-at-point ()
1940 "Transpose Org table at point and eliminate hlines.
1941 So a table like
1943 | 1 | 2 | 4 | 5 |
1944 |---+---+---+---|
1945 | a | b | c | d |
1946 | e | f | g | h |
1948 will be transposed as
1950 | 1 | a | e |
1951 | 2 | b | f |
1952 | 4 | c | g |
1953 | 5 | d | h |
1955 Note that horizontal lines disappear."
1956 (interactive)
1957 (let* ((table (delete 'hline (org-table-to-lisp)))
1958 (dline_old (org-table-current-line))
1959 (col_old (org-table-current-column))
1960 (contents (mapcar (lambda (p)
1961 (let ((tp table))
1962 (mapcar
1963 (lambda (rown)
1964 (prog1
1965 (pop (car tp))
1966 (setq tp (cdr tp))))
1967 table)))
1968 (car table))))
1969 (goto-char (org-table-begin))
1970 (re-search-forward "|")
1971 (backward-char)
1972 (delete-region (point) (org-table-end))
1973 (insert (mapconcat
1974 (lambda(x)
1975 (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1976 contents ""))
1977 (org-table-goto-line col_old)
1978 (org-table-goto-column dline_old))
1979 (org-table-align))
1981 ;;;###autoload
1982 (defun org-table-wrap-region (arg)
1983 "Wrap several fields in a column like a paragraph.
1984 This is useful if you'd like to spread the contents of a field over several
1985 lines, in order to keep the table compact.
1987 If there is an active region, and both point and mark are in the same column,
1988 the text in the column is wrapped to minimum width for the given number of
1989 lines. Generally, this makes the table more compact. A prefix ARG may be
1990 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1991 formats the selected text to two lines. If the region was longer than two
1992 lines, the remaining lines remain empty. A negative prefix argument reduces
1993 the current number of lines by that amount. The wrapped text is pasted back
1994 into the table. If you formatted it to more lines than it was before, fields
1995 further down in the table get overwritten - so you might need to make space in
1996 the table first.
1998 If there is no region, the current field is split at the cursor position and
1999 the text fragment to the right of the cursor is prepended to the field one
2000 line down.
2002 If there is no region, but you specify a prefix ARG, the current field gets
2003 blank, and the content is appended to the field above."
2004 (interactive "P")
2005 (org-table-check-inside-data-field)
2006 (if (org-region-active-p)
2007 ;; There is a region: fill as a paragraph
2008 (let* ((beg (region-beginning))
2009 (cline (save-excursion (goto-char beg) (org-current-line)))
2010 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
2011 nlines)
2012 (org-table-cut-region (region-beginning) (region-end))
2013 (if (> (length (car org-table-clip)) 1)
2014 (user-error "Region must be limited to single column"))
2015 (setq nlines (if arg
2016 (if (< arg 1)
2017 (+ (length org-table-clip) arg)
2018 arg)
2019 (length org-table-clip)))
2020 (setq org-table-clip
2021 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
2022 nil nlines)))
2023 (org-goto-line cline)
2024 (org-table-goto-column ccol)
2025 (org-table-paste-rectangle))
2026 ;; No region, split the current field at point
2027 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
2028 (skip-chars-forward "^\r\n|"))
2029 (if arg
2030 ;; combine with field above
2031 (let ((s (org-table-blank-field))
2032 (col (org-table-current-column)))
2033 (beginning-of-line 0)
2034 (while (org-at-table-hline-p) (beginning-of-line 0))
2035 (org-table-goto-column col)
2036 (skip-chars-forward "^|")
2037 (skip-chars-backward " ")
2038 (insert " " (org-trim s))
2039 (org-table-align))
2040 ;; split field
2041 (if (looking-at "\\([^|]+\\)+|")
2042 (let ((s (match-string 1)))
2043 (replace-match " |")
2044 (goto-char (match-beginning 0))
2045 (org-table-next-row)
2046 (insert (org-trim s) " ")
2047 (org-table-align))
2048 (org-table-next-row)))))
2050 (defvar org-field-marker nil)
2052 ;;;###autoload
2053 (defun org-table-edit-field (arg)
2054 "Edit table field in a different window.
2055 This is mainly useful for fields that contain hidden parts.
2056 When called with a \\[universal-argument] prefix, just make the full field visible so that
2057 it can be edited in place."
2058 (interactive "P")
2059 (cond
2060 ((equal arg '(16))
2061 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
2062 (arg
2063 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2064 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2065 (remove-text-properties b e '(org-cwidth t invisible t
2066 display t intangible t))
2067 (if (and (boundp 'font-lock-mode) font-lock-mode)
2068 (font-lock-fontify-block))))
2070 (let ((pos (point-marker))
2071 (coord
2072 (if (eq org-table-use-standard-references t)
2073 (concat (org-number-to-letters (org-table-current-column))
2074 (int-to-string (org-table-current-dline)))
2075 (concat "@" (int-to-string (org-table-current-dline))
2076 "$" (int-to-string (org-table-current-column)))))
2077 (field (org-table-get-field))
2078 (cw (current-window-configuration))
2080 (goto-char pos)
2081 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2082 (when (and (local-variable-p 'org-field-marker)
2083 (markerp org-field-marker))
2084 (move-marker org-field-marker nil))
2085 (erase-buffer)
2086 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
2087 (let ((org-inhibit-startup t)) (org-mode))
2088 (auto-fill-mode -1)
2089 (setq truncate-lines nil)
2090 (setq word-wrap t)
2091 (goto-char (setq p (point-max)))
2092 (insert (org-trim field))
2093 (remove-text-properties p (point-max)
2094 '(invisible t org-cwidth t display t
2095 intangible t))
2096 (goto-char p)
2097 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
2098 (org-set-local 'org-window-configuration cw)
2099 (org-set-local 'org-field-marker pos)
2100 (message "Edit and finish with C-c C-c")))))
2102 (defun org-table-finish-edit-field ()
2103 "Finish editing a table data field.
2104 Remove all newline characters, insert the result into the table, realign
2105 the table and kill the editing buffer."
2106 (let ((pos org-field-marker)
2107 (cw org-window-configuration)
2108 (cb (current-buffer))
2109 text)
2110 (goto-char (point-min))
2111 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
2112 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
2113 (replace-match " "))
2114 (setq text (org-trim (buffer-string)))
2115 (set-window-configuration cw)
2116 (kill-buffer cb)
2117 (select-window (get-buffer-window (marker-buffer pos)))
2118 (goto-char pos)
2119 (move-marker pos nil)
2120 (org-table-check-inside-data-field)
2121 (org-table-get-field nil text)
2122 (org-table-align)
2123 (message "New field value inserted")))
2125 (define-minor-mode org-table-follow-field-mode
2126 "Minor mode to make the table field editor window follow the cursor.
2127 When this mode is active, the field editor window will always show the
2128 current field. The mode exits automatically when the cursor leaves the
2129 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2130 nil " TblFollow" nil
2131 (if org-table-follow-field-mode
2132 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
2133 'append 'local)
2134 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
2135 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2136 (win (and buf (get-buffer-window buf))))
2137 (when win (delete-window win))
2138 (when buf
2139 (with-current-buffer buf
2140 (move-marker org-field-marker nil))
2141 (kill-buffer buf)))))
2143 (defun org-table-follow-fields-with-editor ()
2144 (if (and org-table-exit-follow-field-mode-when-leaving-table
2145 (not (org-at-table-p)))
2146 ;; We have left the table, exit the follow mode
2147 (org-table-follow-field-mode -1)
2148 (when (org-table-check-inside-data-field 'noerror)
2149 (let ((win (selected-window)))
2150 (org-table-edit-field nil)
2151 (org-fit-window-to-buffer)
2152 (select-window win)))))
2154 (defvar org-timecnt) ; dynamically scoped parameter
2156 ;;;###autoload
2157 (defun org-table-sum (&optional beg end nlast)
2158 "Sum numbers in region of current table column.
2159 The result will be displayed in the echo area, and will be available
2160 as kill to be inserted with \\[yank].
2162 If there is an active region, it is interpreted as a rectangle and all
2163 numbers in that rectangle will be summed. If there is no active
2164 region and point is located in a table column, sum all numbers in that
2165 column.
2167 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2168 numbers are assumed to be times as well (in decimal hours) and the
2169 numbers are added as such.
2171 If NLAST is a number, only the NLAST fields will actually be summed."
2172 (interactive)
2173 (save-excursion
2174 (let (col (org-timecnt 0) diff h m s org-table-clip)
2175 (cond
2176 ((and beg end)) ; beg and end given explicitly
2177 ((org-region-active-p)
2178 (setq beg (region-beginning) end (region-end)))
2180 (setq col (org-table-current-column))
2181 (goto-char (org-table-begin))
2182 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2183 (user-error "No table data"))
2184 (org-table-goto-column col)
2185 (setq beg (point))
2186 (goto-char (org-table-end))
2187 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2188 (user-error "No table data"))
2189 (org-table-goto-column col)
2190 (setq end (point))))
2191 (let* ((items (apply 'append (org-table-copy-region beg end)))
2192 (items1 (cond ((not nlast) items)
2193 ((>= nlast (length items)) items)
2194 (t (setq items (reverse items))
2195 (setcdr (nthcdr (1- nlast) items) nil)
2196 (nreverse items))))
2197 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2198 items1)))
2199 (res (apply '+ numbers))
2200 (sres (if (= org-timecnt 0)
2201 (number-to-string res)
2202 (setq diff (* 3600 res)
2203 h (floor (/ diff 3600)) diff (mod diff 3600)
2204 m (floor (/ diff 60)) diff (mod diff 60)
2205 s diff)
2206 (format "%.0f:%02.0f:%02.0f" h m s))))
2207 (kill-new sres)
2208 (if (org-called-interactively-p 'interactive)
2209 (message "%s"
2210 (substitute-command-keys
2211 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2212 (length numbers) sres))))
2213 sres))))
2215 (defun org-table-get-number-for-summing (s)
2216 (let (n)
2217 (if (string-match "^ *|? *" s)
2218 (setq s (replace-match "" nil nil s)))
2219 (if (string-match " *|? *$" s)
2220 (setq s (replace-match "" nil nil s)))
2221 (setq n (string-to-number s))
2222 (cond
2223 ((and (string-match "0" s)
2224 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2225 ((string-match "\\`[ \t]+\\'" s) nil)
2226 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2227 (let ((h (string-to-number (or (match-string 1 s) "0")))
2228 (m (string-to-number (or (match-string 2 s) "0")))
2229 (s (string-to-number (or (match-string 4 s) "0"))))
2230 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2231 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2232 ((equal n 0) nil)
2233 (t n))))
2235 (defun org-table-current-field-formula (&optional key noerror)
2236 "Return the formula active for the current field.
2237 Assumes that specials are in place.
2238 If KEY is given, return the key to this formula.
2239 Otherwise return the formula preceded with \"=\" or \":=\"."
2240 (let* ((name (car (rassoc (list (org-current-line)
2241 (org-table-current-column))
2242 org-table-named-field-locations)))
2243 (col (org-table-current-column))
2244 (scol (int-to-string col))
2245 (ref (format "@%d$%d" (org-table-current-dline) col))
2246 (stored-list (org-table-get-stored-formulas noerror))
2247 (ass (or (assoc name stored-list)
2248 (assoc ref stored-list)
2249 (assoc scol stored-list))))
2250 (if key
2251 (car ass)
2252 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2253 (cdr ass))))))
2255 (defun org-table-get-formula (&optional equation named)
2256 "Read a formula from the minibuffer, offer stored formula as default.
2257 When NAMED is non-nil, look for a named equation."
2258 (let* ((stored-list (org-table-get-stored-formulas))
2259 (name (car (rassoc (list (org-current-line)
2260 (org-table-current-column))
2261 org-table-named-field-locations)))
2262 (ref (format "@%d$%d" (org-table-current-dline)
2263 (org-table-current-column)))
2264 (refass (assoc ref stored-list))
2265 (nameass (assoc name stored-list))
2266 (scol (if named
2267 (if (and name (not (string-match "^LR[0-9]+$" name)))
2268 name
2269 ref)
2270 (int-to-string (org-table-current-column))))
2271 (dummy (and (or nameass refass) (not named)
2272 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2273 (message "Formula not replaced")))
2274 (name (or name ref))
2275 (org-table-may-need-update nil)
2276 (stored (cdr (assoc scol stored-list)))
2277 (eq (cond
2278 ((and stored equation (string-match "^ *=? *$" equation))
2279 stored)
2280 ((stringp equation)
2281 equation)
2282 (t (org-table-formula-from-user
2283 (read-string
2284 (org-table-formula-to-user
2285 (format "%s formula %s%s="
2286 (if named "Field" "Column")
2287 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2288 scol))
2289 (if stored (org-table-formula-to-user stored) "")
2290 'org-table-formula-history
2291 )))))
2292 mustsave)
2293 (when (not (string-match "\\S-" eq))
2294 ;; remove formula
2295 (setq stored-list (delq (assoc scol stored-list) stored-list))
2296 (org-table-store-formulas stored-list)
2297 (user-error "Formula removed"))
2298 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2299 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2300 (if (and name (not named))
2301 ;; We set the column equation, delete the named one.
2302 (setq stored-list (delq (assoc name stored-list) stored-list)
2303 mustsave t))
2304 (if stored
2305 (setcdr (assoc scol stored-list) eq)
2306 (setq stored-list (cons (cons scol eq) stored-list)))
2307 (if (or mustsave (not (equal stored eq)))
2308 (org-table-store-formulas stored-list))
2309 eq))
2311 (defun org-table-store-formulas (alist)
2312 "Store the list of formulas below the current table."
2313 (setq alist (sort alist 'org-table-formula-less-p))
2314 (let ((case-fold-search t))
2315 (save-excursion
2316 (goto-char (org-table-end))
2317 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2318 (progn
2319 ;; don't overwrite TBLFM, we might use text properties to store stuff
2320 (goto-char (match-beginning 3))
2321 (delete-region (match-beginning 3) (match-end 0)))
2322 (org-indent-line)
2323 (insert (or (match-string 2) "#+TBLFM:")))
2324 (insert " "
2325 (mapconcat (lambda (x)
2326 (concat
2327 (if (equal (string-to-char (car x)) ?@) "" "$")
2328 (car x) "=" (cdr x)))
2329 alist "::")
2330 "\n"))))
2332 (defsubst org-table-formula-make-cmp-string (a)
2333 (when (string-match "\\`$[<>]" a)
2334 (let ((arrow (string-to-char (substring a 1))))
2335 ;; Fake a high number to make sure this is sorted at the end.
2336 (setq a (org-table-formula-handle-first/last-rc a))
2337 (setq a (format "$%d" (+ 10000
2338 (if (= arrow ?<) -1000 0)
2339 (string-to-number (substring a 1)))))))
2340 (when (string-match
2341 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2343 (concat
2344 (if (match-end 2)
2345 (format "@%05d" (string-to-number (match-string 2 a))) "")
2346 (if (match-end 4)
2347 (format "$%05d" (string-to-number (match-string 4 a))) "")
2348 (if (match-end 5)
2349 (concat "@@" (match-string 5 a))))))
2351 (defun org-table-formula-less-p (a b)
2352 "Compare two formulas for sorting."
2353 (let ((as (org-table-formula-make-cmp-string (car a)))
2354 (bs (org-table-formula-make-cmp-string (car b))))
2355 (and as bs (string< as bs))))
2357 ;;;###autoload
2358 (defun org-table-get-stored-formulas (&optional noerror)
2359 "Return an alist with the stored formulas directly after current table."
2360 (interactive) ;; FIXME interactive?
2361 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2362 (save-excursion
2363 (goto-char (org-table-end))
2364 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2365 (setq strings (org-split-string (org-match-string-no-properties 2)
2366 " *:: *"))
2367 (while (setq string (pop strings))
2368 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2369 (setq scol (if (match-end 2)
2370 (match-string 2 string)
2371 (match-string 1 string))
2372 scol (if (member (string-to-char scol) '(?< ?>))
2373 (concat "$" scol) scol)
2374 eq (match-string 3 string)
2375 eq-alist (cons (cons scol eq) eq-alist))
2376 (if (member scol seen)
2377 (if noerror
2378 (progn
2379 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2380 (ding)
2381 (sit-for 2))
2382 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2383 (push scol seen))))))
2384 (nreverse eq-alist)))
2386 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2387 "Modify the equations after the table structure has been edited.
2388 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2389 For all numbers larger than LIMIT, shift them by DELTA."
2390 (save-excursion
2391 (goto-char (org-table-end))
2392 (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2393 (let ((msg "The formulas in #+TBLFM have been updated")
2394 (re (concat key "\\([0-9]+\\)"))
2395 (re2
2396 (when remove
2397 (if (or (equal key "$") (equal key "$LR"))
2398 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2399 (regexp-quote key) remove)
2400 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2401 s n a)
2402 (when remove
2403 (while (re-search-forward re2 (point-at-eol) t)
2404 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2405 (if (equal (char-before (match-beginning 0)) ?.)
2406 (user-error
2407 "Change makes TBLFM term %s invalid, use undo to recover"
2408 (match-string 0))
2409 (replace-match "")))))
2410 (while (re-search-forward re (point-at-eol) t)
2411 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2412 (setq s (match-string 1) n (string-to-number s))
2413 (cond
2414 ((setq a (assoc s replace))
2415 (replace-match (concat key (cdr a)) t t)
2416 (message msg))
2417 ((and limit (> n limit))
2418 (replace-match (concat key (int-to-string (+ n delta))) t t)
2419 (message msg))))))
2420 (forward-line))))
2422 (defun org-table-get-specials ()
2423 "Get the column names and local parameters for this table."
2424 (save-excursion
2425 (let ((beg (org-table-begin)) (end (org-table-end))
2426 names name fields fields1 field cnt
2427 c v l line col types dlines hlines last-dline)
2428 (setq org-table-column-names nil
2429 org-table-local-parameters nil
2430 org-table-named-field-locations nil
2431 org-table-current-begin-line nil
2432 org-table-current-begin-pos nil
2433 org-table-current-line-types nil
2434 org-table-current-ncol 0)
2435 (goto-char beg)
2436 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2437 (setq names (org-split-string (match-string 1) " *| *")
2438 cnt 1)
2439 (while (setq name (pop names))
2440 (setq cnt (1+ cnt))
2441 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
2442 (push (cons name (int-to-string cnt)) org-table-column-names))))
2443 (setq org-table-column-names (nreverse org-table-column-names))
2444 (setq org-table-column-name-regexp
2445 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2446 (goto-char beg)
2447 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2448 (setq fields (org-split-string (match-string 1) " *| *"))
2449 (while (setq field (pop fields))
2450 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2451 (push (cons (match-string 1 field) (match-string 2 field))
2452 org-table-local-parameters))))
2453 (goto-char beg)
2454 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2455 (setq c (match-string 1)
2456 fields (org-split-string (match-string 2) " *| *"))
2457 (save-excursion
2458 (beginning-of-line (if (equal c "_") 2 0))
2459 (setq line (org-current-line) col 1)
2460 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2461 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2462 (while (and fields1 (setq field (pop fields)))
2463 (setq v (pop fields1) col (1+ col))
2464 (when (and (stringp field) (stringp v)
2465 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
2466 (push (cons field v) org-table-local-parameters)
2467 (push (list field line col) org-table-named-field-locations))))
2468 ;; Analyse the line types
2469 (goto-char beg)
2470 (setq org-table-current-begin-line (org-current-line)
2471 org-table-current-begin-pos (point)
2472 l org-table-current-begin-line)
2473 (while (looking-at "[ \t]*|\\(-\\)?")
2474 (push (if (match-end 1) 'hline 'dline) types)
2475 (if (match-end 1) (push l hlines) (push l dlines))
2476 (beginning-of-line 2)
2477 (setq l (1+ l)))
2478 (push 'hline types) ;; add an imaginary extra hline to the end
2479 (setq org-table-current-line-types (apply 'vector (nreverse types))
2480 last-dline (car dlines)
2481 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2482 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2483 (org-goto-line last-dline)
2484 (let* ((l last-dline)
2485 (fields (org-split-string
2486 (buffer-substring (point-at-bol) (point-at-eol))
2487 "[ \t]*|[ \t]*"))
2488 (nfields (length fields))
2489 al al2)
2490 (setq org-table-current-ncol nfields)
2491 (loop for i from 1 to nfields do
2492 (push (list (format "LR%d" i) l i) al)
2493 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2494 (setq org-table-named-field-locations
2495 (append org-table-named-field-locations al))
2496 (setq org-table-local-parameters
2497 (append org-table-local-parameters al2))))))
2499 ;;;###autoload
2500 (defun org-table-maybe-eval-formula ()
2501 "Check if the current field starts with \"=\" or \":=\".
2502 If yes, store the formula and apply it."
2503 ;; We already know we are in a table. Get field will only return a formula
2504 ;; when appropriate. It might return a separator line, but no problem.
2505 (when org-table-formula-evaluate-inline
2506 (let* ((field (org-trim (or (org-table-get-field) "")))
2507 named eq)
2508 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2509 (setq named (equal (string-to-char field) ?:)
2510 eq (match-string 1 field))
2511 (if (or (fboundp 'calc-eval)
2512 (equal (substring eq 0 (min 2 (length eq))) "'("))
2513 (org-table-eval-formula (if named '(4) nil)
2514 (org-table-formula-from-user eq))
2515 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2517 (defvar org-recalc-commands nil
2518 "List of commands triggering the recalculation of a line.
2519 Will be filled automatically during use.")
2521 (defvar org-recalc-marks
2522 '((" " . "Unmarked: no special line, no automatic recalculation")
2523 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2524 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2525 ("!" . "Column name definition line. Reference in formula as $name.")
2526 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2527 ("_" . "Names for values in row below this one.")
2528 ("^" . "Names for values in row above this one.")))
2530 ;;;###autoload
2531 (defun org-table-rotate-recalc-marks (&optional newchar)
2532 "Rotate the recalculation mark in the first column.
2533 If in any row, the first field is not consistent with a mark,
2534 insert a new column for the markers.
2535 When there is an active region, change all the lines in the region,
2536 after prompting for the marking character.
2537 After each change, a message will be displayed indicating the meaning
2538 of the new mark."
2539 (interactive)
2540 (unless (org-at-table-p) (user-error "Not at a table"))
2541 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2542 (beg (org-table-begin))
2543 (end (org-table-end))
2544 (l (org-current-line))
2545 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2546 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2547 (have-col
2548 (save-excursion
2549 (goto-char beg)
2550 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2551 (col (org-table-current-column))
2552 (forcenew (car (assoc newchar org-recalc-marks)))
2553 epos new)
2554 (when l1
2555 (message "Change region to what mark? Type # * ! $ or SPC: ")
2556 (setq newchar (char-to-string (read-char-exclusive))
2557 forcenew (car (assoc newchar org-recalc-marks))))
2558 (if (and newchar (not forcenew))
2559 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2560 newchar))
2561 (if l1 (org-goto-line l1))
2562 (save-excursion
2563 (beginning-of-line 1)
2564 (unless (looking-at org-table-dataline-regexp)
2565 (user-error "Not at a table data line")))
2566 (unless have-col
2567 (org-table-goto-column 1)
2568 (org-table-insert-column)
2569 (org-table-goto-column (1+ col)))
2570 (setq epos (point-at-eol))
2571 (save-excursion
2572 (beginning-of-line 1)
2573 (org-table-get-field
2574 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2575 (concat " "
2576 (setq new (or forcenew
2577 (cadr (member (match-string 1) marks))))
2578 " ")
2579 " # ")))
2580 (if (and l1 l2)
2581 (progn
2582 (org-goto-line l1)
2583 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2584 (and (looking-at org-table-dataline-regexp)
2585 (org-table-get-field 1 (concat " " new " "))))
2586 (org-goto-line l1)))
2587 (if (not (= epos (point-at-eol))) (org-table-align))
2588 (org-goto-line l)
2589 (and (org-called-interactively-p 'interactive)
2590 (message "%s" (cdr (assoc new org-recalc-marks))))))
2592 ;;;###autoload
2593 (defun org-table-maybe-recalculate-line ()
2594 "Recompute the current line if marked for it, and if we haven't just done it."
2595 (interactive)
2596 (and org-table-allow-automatic-line-recalculation
2597 (not (and (memq last-command org-recalc-commands)
2598 (equal org-last-recalc-line (org-current-line))))
2599 (save-excursion (beginning-of-line 1)
2600 (looking-at org-table-auto-recalculate-regexp))
2601 (org-table-recalculate) t))
2603 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2604 (defsubst org-set-calc-mode (var &optional value)
2605 (if (stringp var)
2606 (setq var (assoc var '(("D" calc-angle-mode deg)
2607 ("R" calc-angle-mode rad)
2608 ("F" calc-prefer-frac t)
2609 ("S" calc-symbolic-mode t)))
2610 value (nth 2 var) var (nth 1 var)))
2611 (if (memq var org-tbl-calc-modes)
2612 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2613 (cons var (cons value org-tbl-calc-modes)))
2614 org-tbl-calc-modes)
2616 ;;;###autoload
2617 (defun org-table-eval-formula (&optional arg equation
2618 suppress-align suppress-const
2619 suppress-store suppress-analysis)
2620 "Replace the table field value at the cursor by the result of a calculation.
2622 This function makes use of Dave Gillespie's Calc package, in my view the
2623 most exciting program ever written for GNU Emacs. So you need to have Calc
2624 installed in order to use this function.
2626 In a table, this command replaces the value in the current field with the
2627 result of a formula. It also installs the formula as the \"current\" column
2628 formula, by storing it in a special line below the table. When called
2629 with a `C-u' prefix, the current field must be a named field, and the
2630 formula is installed as valid in only this specific field.
2632 When called with two `C-u' prefixes, insert the active equation
2633 for the field back into the current field, so that it can be
2634 edited there. This is useful in order to use \\[org-table-show-reference]
2635 to check the referenced fields.
2637 When called, the command first prompts for a formula, which is read in
2638 the minibuffer. Previously entered formulas are available through the
2639 history list, and the last used formula is offered as a default.
2640 These stored formulas are adapted correctly when moving, inserting, or
2641 deleting columns with the corresponding commands.
2643 The formula can be any algebraic expression understood by the Calc package.
2644 For details, see the Org-mode manual.
2646 This function can also be called from Lisp programs and offers
2647 additional arguments: EQUATION can be the formula to apply. If this
2648 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2649 used to speed-up recursive calls by by-passing unnecessary aligns.
2650 SUPPRESS-CONST suppresses the interpretation of constants in the
2651 formula, assuming that this has been done already outside the function.
2652 SUPPRESS-STORE means the formula should not be stored, either because
2653 it is already stored, or because it is a modified equation that should
2654 not overwrite the stored one."
2655 (interactive "P")
2656 (org-table-check-inside-data-field)
2657 (or suppress-analysis (org-table-get-specials))
2658 (if (equal arg '(16))
2659 (let ((eq (org-table-current-field-formula)))
2660 (or eq (user-error "No equation active for current field"))
2661 (org-table-get-field nil eq)
2662 (org-table-align)
2663 (setq org-table-may-need-update t))
2664 (let* (fields
2665 (ndown (if (integerp arg) arg 1))
2666 (org-table-automatic-realign nil)
2667 (case-fold-search nil)
2668 (down (> ndown 1))
2669 (formula (if (and equation suppress-store)
2670 equation
2671 (org-table-get-formula equation (equal arg '(4)))))
2672 (n0 (org-table-current-column))
2673 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2674 (numbers nil) ; was a variable, now fixed default
2675 (keep-empty nil)
2676 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2677 duration duration-output-format)
2678 ;; Parse the format string. Since we have a lot of modes, this is
2679 ;; a lot of work. However, I think calc still uses most of the time.
2680 (if (string-match ";" formula)
2681 (let ((tmp (org-split-string formula ";")))
2682 (setq formula (car tmp)
2683 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2684 (nth 1 tmp)))
2685 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2686 (setq c (string-to-char (match-string 1 fmt))
2687 n (string-to-number (match-string 2 fmt)))
2688 (if (= c ?p)
2689 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2690 (setq org-tbl-calc-modes
2691 (org-set-calc-mode
2692 'calc-float-format
2693 (list (cdr (assoc c '((?n . float) (?f . fix)
2694 (?s . sci) (?e . eng))))
2695 n))))
2696 (setq fmt (replace-match "" t t fmt)))
2697 (if (string-match "T" fmt)
2698 (setq duration t numbers t
2699 duration-output-format nil
2700 fmt (replace-match "" t t fmt)))
2701 (if (string-match "t" fmt)
2702 (setq duration t
2703 duration-output-format org-table-duration-custom-format
2704 numbers t
2705 fmt (replace-match "" t t fmt)))
2706 (if (string-match "N" fmt)
2707 (setq numbers t
2708 fmt (replace-match "" t t fmt)))
2709 (if (string-match "L" fmt)
2710 (setq literal t
2711 fmt (replace-match "" t t fmt)))
2712 (if (string-match "E" fmt)
2713 (setq keep-empty t
2714 fmt (replace-match "" t t fmt)))
2715 (while (string-match "[DRFS]" fmt)
2716 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2717 (setq fmt (replace-match "" t t fmt)))
2718 (unless (string-match "\\S-" fmt)
2719 (setq fmt nil))))
2720 (if (and (not suppress-const) org-table-formula-use-constants)
2721 (setq formula (org-table-formula-substitute-names formula)))
2722 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2723 (while (> ndown 0)
2724 (setq fields (org-split-string
2725 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2726 " *| *"))
2727 ;; replace fields with duration values if relevant
2728 (if duration
2729 (setq fields
2730 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2731 fields)))
2732 (if (eq numbers t)
2733 (setq fields (mapcar
2734 (lambda (x)
2735 (if (string-match "\\S-" x)
2736 (number-to-string (string-to-number x))
2738 fields)))
2739 (setq ndown (1- ndown))
2740 (setq form (copy-sequence formula)
2741 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2742 (if (and lispp literal) (setq lispp 'literal))
2744 ;; Insert row and column number of formula result field
2745 (while (string-match "[@$]#" form)
2746 (setq form
2747 (replace-match
2748 (format "%d"
2749 (save-match-data
2750 (if (equal (substring form (match-beginning 0)
2751 (1+ (match-beginning 0)))
2752 "@")
2753 (org-table-current-dline)
2754 (org-table-current-column))))
2755 t t form)))
2757 ;; Check for old vertical references
2758 (org-table--error-on-old-row-references form)
2759 ;; Insert remote references
2760 (setq form (org-table-remote-reference-indirection form))
2761 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2762 (setq form
2763 (replace-match
2764 (save-match-data
2765 (org-table-make-reference
2766 (let ((rmtrng (org-table-get-remote-range
2767 (match-string 1 form) (match-string 2 form))))
2768 (if duration
2769 (if (listp rmtrng)
2770 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2771 (org-table-time-string-to-seconds rmtrng))
2772 rmtrng))
2773 keep-empty numbers lispp))
2774 t t form)))
2775 ;; Insert complex ranges
2776 (while (and (string-match org-table-range-regexp form)
2777 (> (length (match-string 0 form)) 1))
2778 (setq formrg (save-match-data
2779 (org-table-get-range (match-string 0 form) nil n0)))
2780 (setq formrpl
2781 (save-match-data
2782 (org-table-make-reference
2783 ;; possibly handle durations
2784 (if duration
2785 (if (listp formrg)
2786 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2787 (org-table-time-string-to-seconds formrg))
2788 formrg)
2789 keep-empty numbers lispp)))
2790 (if (not (save-match-data
2791 (string-match (regexp-quote form) formrpl)))
2792 (setq form (replace-match formrpl t t form))
2793 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2794 ;; Insert simple ranges
2795 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2796 (setq form
2797 (replace-match
2798 (save-match-data
2799 (org-table-make-reference
2800 (org-sublist
2801 fields (string-to-number (match-string 1 form))
2802 (string-to-number (match-string 2 form)))
2803 keep-empty numbers lispp))
2804 t t form)))
2805 (setq form0 form)
2806 ;; Insert the references to fields in same row
2807 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2808 (setq n (+ (string-to-number (match-string 1 form))
2809 (if (match-end 2) n0 0))
2810 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2811 formrpl (save-match-data
2812 (org-table-make-reference
2813 x keep-empty numbers lispp)))
2814 (when (or (not x)
2815 (save-match-data
2816 (string-match (regexp-quote formula) formrpl)))
2817 (user-error "Invalid field specifier \"%s\""
2818 (match-string 0 form)))
2819 (setq form (replace-match formrpl t t form)))
2821 (if lispp
2822 (setq ev (condition-case nil
2823 (eval (eval (read form)))
2824 (error "#ERROR"))
2825 ev (if (numberp ev) (number-to-string ev) ev)
2826 ev (if duration (org-table-time-seconds-to-string
2827 (string-to-number ev)
2828 duration-output-format) ev))
2829 (or (fboundp 'calc-eval)
2830 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2831 ;; Use <...> time-stamps so that Calc can handle them
2832 (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
2833 (setq form (replace-match "<\\1>" nil nil form)))
2834 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2835 (when (string-match org-ts-regexp2 form)
2836 (let* ((ts (match-string 0 form))
2837 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2838 (system-time-locale "C")
2839 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2840 (cdr org-time-stamp-formats))
2841 (car org-time-stamp-formats))))
2842 (setq form (replace-match (format-time-string tf tsp) t t form))))
2844 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2845 form
2846 (calc-eval (cons form org-tbl-calc-modes)
2847 (when (and (not keep-empty) numbers) 'num)))
2848 ev (if duration (org-table-time-seconds-to-string
2849 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2850 (string-to-number (org-table-time-string-to-seconds ev))
2851 (string-to-number ev))
2852 duration-output-format)
2853 ev)))
2855 (when org-table-formula-debug
2856 (with-output-to-temp-buffer "*Substitution History*"
2857 (princ (format "Substitution history of formula
2858 Orig: %s
2859 $xyz-> %s
2860 @r$c-> %s
2861 $1-> %s\n" orig formula form0 form))
2862 (if (consp ev)
2863 (princ (format " %s^\nError: %s"
2864 (make-string (car ev) ?\-) (nth 1 ev)))
2865 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2866 ev (or fmt "NONE")
2867 (if fmt (format fmt (string-to-number ev)) ev)))))
2868 (setq bw (get-buffer-window "*Substitution History*"))
2869 (org-fit-window-to-buffer bw)
2870 (unless (and (org-called-interactively-p 'any) (not ndown))
2871 (unless (let (inhibit-redisplay)
2872 (y-or-n-p "Debugging Formula. Continue to next? "))
2873 (org-table-align)
2874 (user-error "Abort"))
2875 (delete-window bw)
2876 (message "")))
2877 (when (consp ev) (setq fmt nil ev "#ERROR"))
2878 (org-table-justify-field-maybe
2879 (format org-table-formula-field-format
2880 (if fmt (format fmt (string-to-number ev)) ev)))
2881 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2882 (call-interactively 'org-return)
2883 (setq ndown 0)))
2884 (and down (org-table-maybe-recalculate-line))
2885 (or suppress-align (and org-table-may-need-update
2886 (org-table-align))))))
2888 (defun org-table-put-field-property (prop value)
2889 (save-excursion
2890 (put-text-property (progn (skip-chars-backward "^|") (point))
2891 (progn (skip-chars-forward "^|") (point))
2892 prop value)))
2894 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2895 "Get a calc vector from a column, according to descriptor DESC.
2896 Optional arguments TBEG and COL can give the beginning of the table and
2897 the current column, to avoid unnecessary parsing.
2899 HIGHLIGHT means just highlight the range.
2901 When CORNERS-ONLY is set, only return the corners of the range as
2902 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2903 in the buffer and column1 and column2 are table column numbers."
2904 (if (not (equal (string-to-char desc) ?@))
2905 (setq desc (concat "@" desc)))
2906 (save-excursion
2907 (or tbeg (setq tbeg (org-table-begin)))
2908 (or col (setq col (org-table-current-column)))
2909 (let ((thisline (org-current-line))
2910 beg end c1 c2 r1 r2 rangep tmp)
2911 (unless (string-match org-table-range-regexp desc)
2912 (user-error "Invalid table range specifier `%s'" desc))
2913 (setq rangep (match-end 3)
2914 r1 (and (match-end 1) (match-string 1 desc))
2915 r2 (and (match-end 4) (match-string 4 desc))
2916 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2917 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2919 (and c1 (setq c1 (+ (string-to-number c1)
2920 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2921 (and c2 (setq c2 (+ (string-to-number c2)
2922 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2923 (if (equal r1 "") (setq r1 nil))
2924 (if (equal r2 "") (setq r2 nil))
2925 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2926 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2927 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2928 (if (not r1) (setq r1 thisline))
2929 (if (not r2) (setq r2 thisline))
2930 (if (or (not c1) (= 0 c1)) (setq c1 col))
2931 (if (or (not c2) (= 0 c2)) (setq c2 col))
2932 (if (and (not corners-only)
2933 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2934 ;; just one field
2935 (progn
2936 (org-goto-line r1)
2937 (while (not (looking-at org-table-dataline-regexp))
2938 (beginning-of-line 2))
2939 (prog1 (org-trim (org-table-get-field c1))
2940 (if highlight (org-table-highlight-rectangle (point) (point)))))
2941 ;; A range, return a vector
2942 ;; First sort the numbers to get a regular rectangle
2943 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2944 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2945 (if corners-only
2946 ;; Only return the corners of the range
2947 (list r1 c1 r2 c2)
2948 ;; Copy the range values into a list
2949 (org-goto-line r1)
2950 (while (not (looking-at org-table-dataline-regexp))
2951 (beginning-of-line 2))
2952 (org-table-goto-column c1)
2953 (setq beg (point))
2954 (org-goto-line r2)
2955 (while (not (looking-at org-table-dataline-regexp))
2956 (beginning-of-line 0))
2957 (org-table-goto-column c2)
2958 (setq end (point))
2959 (if highlight
2960 (org-table-highlight-rectangle
2961 beg (progn (skip-chars-forward "^|\n") (point))))
2962 ;; return string representation of calc vector
2963 (mapcar 'org-trim
2964 (apply 'append (org-table-copy-region beg end))))))))
2966 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2967 "Analyze descriptor DESC and retrieve the corresponding line number.
2968 The cursor is currently in line CLINE, the table begins in line BLINE,
2969 and TABLE is a vector with line types."
2970 (if (string-match "^[0-9]+$" desc)
2971 (aref org-table-dlines (string-to-number desc))
2972 (setq cline (or cline (org-current-line))
2973 bline (or bline org-table-current-begin-line)
2974 table (or table org-table-current-line-types))
2975 (if (or
2976 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2977 ;; 1 2 3 4 5 6
2978 (and (not (match-end 3)) (not (match-end 6)))
2979 (and (match-end 3) (match-end 6) (not (match-end 5))))
2980 (user-error "Invalid row descriptor `%s'" desc))
2981 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2982 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2983 (odir (and (match-end 5) (match-string 5 desc)))
2984 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2985 (i (- cline bline))
2986 (rel (and (match-end 6)
2987 (or (and (match-end 1) (not (match-end 3)))
2988 (match-end 5)))))
2989 (if (and hn (not hdir))
2990 (progn
2991 (setq i 0 hdir "+")
2992 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2993 (if (and (not hn) on (not odir))
2994 (user-error "Should never happen");;(aref org-table-dlines on)
2995 (if (and hn (> hn 0))
2996 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2997 nil hn cline desc)))
2998 (if on
2999 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
3000 rel on cline desc)))
3001 (+ bline i)))))
3003 (defun org-table-find-row-type (table i type backwards relative n cline desc)
3004 "FIXME: Needs more documentation."
3005 (let ((l (length table)))
3006 (while (> n 0)
3007 (while (and (setq i (+ i (if backwards -1 1)))
3008 (>= i 0) (< i l)
3009 (not (eq (aref table i) type))
3010 (if (and relative (eq (aref table i) 'hline))
3011 (cond
3012 ((eq org-table-relative-ref-may-cross-hline t) t)
3013 ((eq org-table-relative-ref-may-cross-hline 'error)
3014 (user-error "Row descriptor %s used in line %d crosses hline" desc cline))
3015 (t (setq i (- i (if backwards -1 1))
3016 n 1)
3017 nil))
3018 t)))
3019 (setq n (1- n)))
3020 (if (or (< i 0) (>= i l))
3021 (user-error "Row descriptor %s used in line %d leads outside table"
3022 desc cline)
3023 i)))
3025 (defun org-table--error-on-old-row-references (s)
3026 (when (string-match "&[-+0-9I]" s)
3027 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3029 (defun org-table-make-reference (elements keep-empty numbers lispp)
3030 "Convert list ELEMENTS to something appropriate to insert into formula.
3031 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3032 NUMBERS indicates that everything should be converted to numbers.
3033 LISPP non-nil means to return something appropriate for a Lisp
3034 list, 'literal is for the format specifier L."
3035 ;; Calc nan (not a number) is used for the conversion of the empty
3036 ;; field to a reference for several reasons: (i) It is accepted in a
3037 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3038 ;; (ii) In a single field (not in range) it can be distinguished
3039 ;; from "(nan)" which is the reference made from a single field
3040 ;; containing "nan".
3041 (if (stringp elements)
3042 ;; field reference
3043 (if lispp
3044 (if (eq lispp 'literal)
3045 elements
3046 (if (and (eq elements "") (not keep-empty))
3048 (prin1-to-string
3049 (if numbers (string-to-number elements) elements))))
3050 (if (string-match "\\S-" elements)
3051 (progn
3052 (when numbers (setq elements (number-to-string
3053 (string-to-number elements))))
3054 (concat "(" elements ")"))
3055 (if (or (not keep-empty) numbers) "(0)" "nan")))
3056 ;; range reference
3057 (unless keep-empty
3058 (setq elements
3059 (delq nil
3060 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3061 elements))))
3062 (setq elements (or elements '())) ; if delq returns nil then we need '()
3063 (if lispp
3064 (mapconcat
3065 (lambda (x)
3066 (if (eq lispp 'literal)
3068 (prin1-to-string (if numbers (string-to-number x) x))))
3069 elements " ")
3070 (concat "[" (mapconcat
3071 (lambda (x)
3072 (if (string-match "\\S-" x)
3073 (if numbers
3074 (number-to-string (string-to-number x))
3076 (if (or (not keep-empty) numbers) "0" "nan")))
3077 elements
3078 ",") "]"))))
3080 (defun org-table-message-once-per-second (t1 &rest args)
3081 "If there has been more than one second since T1, display message.
3082 ARGS are passed as arguments to the `message' function. Returns
3083 current time if a message is printed, otherwise returns T1. If
3084 T1 is nil, always messages."
3085 (let ((curtime (current-time)))
3086 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3087 (progn (apply 'message args)
3088 curtime)
3089 t1)))
3091 ;;;###autoload
3092 (defun org-table-recalculate (&optional all noalign)
3093 "Recalculate the current table line by applying all stored formulas.
3094 With prefix arg ALL, do this for all lines in the table.
3095 With the prefix argument ALL is `(16)' \
3096 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3097 it is the symbol `iterate', recompute the table until it no longer changes.
3098 If NOALIGN is not nil, do not re-align the table after the computations
3099 are done. This is typically used internally to save time, if it is
3100 known that the table will be realigned a little later anyway."
3101 (interactive "P")
3102 (or (memq this-command org-recalc-commands)
3103 (setq org-recalc-commands (cons this-command org-recalc-commands)))
3104 (unless (org-at-table-p) (user-error "Not at a table"))
3105 (if (or (eq all 'iterate) (equal all '(16)))
3106 (org-table-iterate)
3107 (org-table-get-specials)
3108 (let* ((eqlist (sort (org-table-get-stored-formulas)
3109 (lambda (a b) (string< (car a) (car b)))))
3110 (eqlist1 (copy-sequence eqlist))
3111 (inhibit-redisplay (not debug-on-error))
3112 (line-re org-table-dataline-regexp)
3113 (thisline (org-current-line))
3114 (thiscol (org-table-current-column))
3115 (log-first-time (current-time))
3116 (log-last-time log-first-time)
3117 seen-fields lhs1
3118 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
3119 ;; Insert constants in all formulas
3120 (when eqlist
3121 (setq eqlist
3122 (mapcar
3123 (lambda (x)
3124 (if (string-match "^@-?I+" (car x))
3125 (user-error "Can't assign to hline relative reference"))
3126 (when (string-match "\\`$[<>]" (car x))
3127 (setq lhs1 (car x))
3128 (setq x (cons (substring
3129 (org-table-formula-handle-first/last-rc
3130 (car x)) 1)
3131 (cdr x)))
3132 (if (assoc (car x) eqlist1)
3133 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3134 lhs1 (car x))))
3135 (cons
3136 (org-table-formula-handle-first/last-rc (car x))
3137 (org-table-formula-substitute-names
3138 (org-table-formula-handle-first/last-rc (cdr x)))))
3139 eqlist))
3140 ;; Split the equation list
3141 (while (setq eq (pop eqlist))
3142 (if (<= (string-to-char (car eq)) ?9)
3143 (push eq eqlnum)
3144 (push eq eqlname)))
3145 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
3146 ;; Expand ranges in lhs of formulas
3147 (setq eqlname (org-table-expand-lhs-ranges eqlname))
3149 ;; Get the correct line range to process
3150 (if all
3151 (progn
3152 (setq end (move-marker (make-marker) (1+ (org-table-end))))
3153 (goto-char (setq beg (org-table-begin)))
3154 (if (re-search-forward org-table-calculate-mark-regexp end t)
3155 ;; This is a table with marked lines, compute selected lines
3156 (setq line-re org-table-recalculate-regexp)
3157 ;; Move forward to the first non-header line
3158 (if (and (re-search-forward org-table-dataline-regexp end t)
3159 (re-search-forward org-table-hline-regexp end t)
3160 (re-search-forward org-table-dataline-regexp end t))
3161 (setq beg (match-beginning 0))
3162 nil))) ;; just leave beg where it is
3163 (setq beg (point-at-bol)
3164 end (move-marker (make-marker) (1+ (point-at-eol)))))
3165 (goto-char beg)
3167 ;; First find the named fields, and mark them untouchable.
3168 ;; Also check if several field/range formulas try to set the same field.
3169 (remove-text-properties beg end '(org-untouchable t))
3170 (while (setq eq (pop eqlname))
3171 (setq name (car eq)
3172 a (assoc name org-table-named-field-locations))
3173 (setq name1 name)
3174 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
3175 (nth 2 a))))
3176 (when (member name1 seen-fields)
3177 (user-error "Several field/range formulas try to set %s" name1))
3178 (push name1 seen-fields)
3180 (and (not a)
3181 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
3182 (setq a (list name
3183 (condition-case nil
3184 (aref org-table-dlines
3185 (string-to-number (match-string 1 name)))
3186 (error (user-error "Invalid row number in %s"
3187 name)))
3188 (string-to-number (match-string 2 name)))))
3189 (when (and a (or all (equal (nth 1 a) thisline)))
3190 (setq log-last-time
3191 (org-table-message-once-per-second
3192 (and all log-last-time)
3193 "Re-applying formula to field: %s" name))
3194 (org-goto-line (nth 1 a))
3195 (org-table-goto-column (nth 2 a))
3196 (push (append a (list (cdr eq))) eqlname1)
3197 (org-table-put-field-property :org-untouchable t)))
3198 (setq eqlname1 (nreverse eqlname1))
3200 ;; Now evaluate the column formulas, but skip fields covered
3201 ;; by field formulas
3202 (goto-char beg)
3203 (while (re-search-forward line-re end t)
3204 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3205 ;; Unprotected line, recalculate
3206 (setq cnt (1+ cnt))
3207 (and all (setq log-last-time
3208 (org-table-message-once-per-second
3209 log-last-time
3210 "Re-applying formulas to full table...(line %d)" cnt)))
3211 (setq org-last-recalc-line (org-current-line))
3212 (setq eql eqlnum)
3213 (while (setq entry (pop eql))
3214 (org-goto-line org-last-recalc-line)
3215 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3216 (unless (get-text-property (point) :org-untouchable)
3217 (org-table-eval-formula
3218 nil (cdr entry)
3219 'noalign 'nocst 'nostore 'noanalysis)))))
3221 ;; Now evaluate the field formulas
3222 (while (setq eq (pop eqlname1))
3223 (setq log-last-time
3224 (org-table-message-once-per-second
3225 (and all log-last-time)
3226 "Re-applying formula to field: %s" (car eq)))
3227 (org-goto-line (nth 1 eq))
3228 (let ((column-target (nth 2 eq)))
3229 (when (> column-target 1000)
3230 (user-error "Formula column target too large"))
3231 (let* ((column-count (progn (end-of-line)
3232 (1- (org-table-current-column))))
3233 (create-new-column
3234 (and (> column-target column-count)
3235 (or (eq org-table-formula-create-columns t)
3236 (and
3237 (eq org-table-formula-create-columns 'warn)
3238 (progn
3239 (org-display-warning
3240 "Out-of-bounds formula added columns")
3242 (and
3243 (eq org-table-formula-create-columns 'prompt)
3244 (yes-or-no-p
3245 "Out-of-bounds formula. Add columns?"))))))
3246 (org-table-goto-column column-target nil create-new-column))
3248 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
3249 'nostore 'noanalysis)))
3251 (org-goto-line thisline)
3252 (org-table-goto-column thiscol)
3253 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3254 (or noalign (and org-table-may-need-update (org-table-align))
3255 (and all (org-table-message-once-per-second
3256 log-first-time
3257 "Re-applying formulas to %d lines...done" cnt)))
3260 ;; back to initial position
3261 (org-table-message-once-per-second
3262 (and all log-first-time)
3263 "Re-applying formulas...done")
3265 (org-goto-line thisline)
3266 (org-table-goto-column thiscol)
3267 (or noalign (and org-table-may-need-update (org-table-align)))))))
3269 ;;;###autoload
3270 (defun org-table-iterate (&optional arg)
3271 "Recalculate the table until it does not change anymore.
3272 The maximum number of iterations is 10, but you can choose a different value
3273 with the prefix ARG."
3274 (interactive "P")
3275 (let ((imax (if arg (prefix-numeric-value arg) 10))
3276 (i 0)
3277 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3278 thistbl)
3279 (catch 'exit
3280 (while (< i imax)
3281 (setq i (1+ i))
3282 (org-table-recalculate 'all)
3283 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3284 (if (not (string= lasttbl thistbl))
3285 (setq lasttbl thistbl)
3286 (if (> i 1)
3287 (message "Convergence after %d iterations" i)
3288 (message "Table was already stable"))
3289 (throw 'exit t)))
3290 (user-error "No convergence after %d iterations" i))))
3292 ;;;###autoload
3293 (defun org-table-recalculate-buffer-tables ()
3294 "Recalculate all tables in the current buffer."
3295 (interactive)
3296 (save-excursion
3297 (save-restriction
3298 (widen)
3299 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3301 ;;;###autoload
3302 (defun org-table-iterate-buffer-tables ()
3303 "Iterate all tables in the buffer, to converge inter-table dependencies."
3304 (interactive)
3305 (let* ((imax 10)
3306 (i imax)
3307 (checksum (md5 (buffer-string)))
3309 (save-excursion
3310 (save-restriction
3311 (widen)
3312 (catch 'exit
3313 (while (> i 0)
3314 (setq i (1- i))
3315 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3316 (if (equal checksum (setq c1 (md5 (buffer-string))))
3317 (progn
3318 (message "Convergence after %d iterations" (- imax i))
3319 (throw 'exit t))
3320 (setq checksum c1)))
3321 (user-error "No convergence after %d iterations" imax))))))
3323 (defun org-table-calc-current-TBLFM (&optional arg)
3324 "Apply the #+TBLFM in the line at point to the table."
3325 (interactive "P")
3326 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3327 (let ((formula (buffer-substring
3328 (point-at-bol)
3329 (point-at-eol)))
3330 s e)
3331 (save-excursion
3332 ;; Insert a temporary formula at right after the table
3333 (goto-char (org-table-TBLFM-begin))
3334 (setq s (set-marker (make-marker) (point)))
3335 (insert (concat formula "\n"))
3336 (setq e (set-marker (make-marker) (point)))
3337 ;; Recalculate the table
3338 (beginning-of-line 0) ; move to the inserted line
3339 (skip-chars-backward " \r\n\t")
3340 (if (org-at-table-p)
3341 (unwind-protect
3342 (org-call-with-arg 'org-table-recalculate (or arg t))
3343 ;; delete the formula inserted temporarily
3344 (delete-region s e))))))
3346 (defun org-table-TBLFM-begin ()
3347 "Find the beginning of the TBLFM lines and return its position.
3348 Return nil when the beginning of TBLFM line was not found."
3349 (save-excursion
3350 (when (progn (forward-line 1)
3351 (re-search-backward
3352 org-table-TBLFM-begin-regexp
3353 nil t))
3354 (point-at-bol 2))))
3356 (defun org-table-expand-lhs-ranges (equations)
3357 "Expand list of formulas.
3358 If some of the RHS in the formulas are ranges or a row reference, expand
3359 them to individual field equations for each field."
3360 (let (e res lhs rhs range r1 r2 c1 c2)
3361 (while (setq e (pop equations))
3362 (setq lhs (car e) rhs (cdr e))
3363 (cond
3364 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3365 ;; This just refers to one fixed field
3366 (push e res))
3367 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3368 ;; This just refers to one fixed named field
3369 (push e res))
3370 ((string-match "^@[0-9]+$" lhs)
3371 (loop for ic from 1 to org-table-current-ncol do
3372 (push (cons (format "%s$%d" lhs ic) rhs) res)
3373 (put-text-property 0 (length (caar res))
3374 :orig-eqn e (caar res))))
3376 (setq range (org-table-get-range lhs org-table-current-begin-pos
3377 1 nil 'corners))
3378 (setq r1 (nth 0 range) c1 (nth 1 range)
3379 r2 (nth 2 range) c2 (nth 3 range))
3380 (setq r1 (org-table-line-to-dline r1))
3381 (setq r2 (org-table-line-to-dline r2 'above))
3382 (loop for ir from r1 to r2 do
3383 (loop for ic from c1 to c2 do
3384 (push (cons (format "@%d$%d" ir ic) rhs) res)
3385 (put-text-property 0 (length (caar res))
3386 :orig-eqn e (caar res)))))))
3387 (nreverse res)))
3389 (defun org-table-formula-handle-first/last-rc (s)
3390 "Replace @<, @>, $<, $> with first/last row/column of the table.
3391 So @< and $< will always be replaced with @1 and $1, respectively.
3392 The advantage of these special markers are that structure editing of
3393 the table will not change them, while @1 and $1 will be modified
3394 when a line/row is swapped out of that privileged position. So for
3395 formulas that use a range of rows or columns, it may often be better
3396 to anchor the formula with \"I\" row markers, or to offset from the
3397 borders of the table using the @< @> $< $> makers."
3398 (let (n nmax len char (start 0))
3399 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3400 s start)
3401 (if (match-end 3)
3402 (setq start (match-end 3))
3403 (setq nmax (if (equal (match-string 1 s) "@")
3404 (1- (length org-table-dlines))
3405 org-table-current-ncol)
3406 len (- (match-end 2) (match-beginning 2))
3407 char (string-to-char (match-string 2 s))
3408 n (if (= char ?<)
3410 (- nmax len -1)))
3411 (if (or (< n 1) (> n nmax))
3412 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3413 (match-string 0 s) s))
3414 (setq start (match-beginning 0))
3415 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3418 (defun org-table-formula-substitute-names (f)
3419 "Replace $const with values in string F."
3420 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3421 ;; First, check for column names
3422 (while (setq start (string-match org-table-column-name-regexp f start))
3423 (setq start (1+ start))
3424 (setq a (assoc (match-string 1 f) org-table-column-names))
3425 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3426 ;; Parameters and constants
3427 (setq start 0)
3428 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3429 (if (match-end 2)
3430 (setq start (match-end 2))
3431 (setq start (1+ start))
3432 (if (setq a (save-match-data
3433 (org-table-get-constant (match-string 1 f))))
3434 (setq f (replace-match
3435 (concat (if pp "(") a (if pp ")")) t t f)))))
3436 (if org-table-formula-debug
3437 (put-text-property 0 (length f) :orig-formula f1 f))
3440 (defun org-table-get-constant (const)
3441 "Find the value for a parameter or constant in a formula.
3442 Parameters get priority."
3443 (or (cdr (assoc const org-table-local-parameters))
3444 (cdr (assoc const org-table-formula-constants-local))
3445 (cdr (assoc const org-table-formula-constants))
3446 (and (fboundp 'constants-get) (constants-get const))
3447 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3448 (org-entry-get nil (substring const 5) 'inherit))
3449 "#UNDEFINED_NAME"))
3451 (defvar org-table-fedit-map
3452 (let ((map (make-sparse-keymap)))
3453 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3454 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3455 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3456 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3457 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3458 (org-defkey map "\C-c?" 'org-table-show-reference)
3459 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3460 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3461 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3462 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3463 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3464 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3465 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3466 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3467 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3468 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3469 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3470 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3471 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3472 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3473 map))
3475 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3476 '("Edit-Formulas"
3477 ["Finish and Install" org-table-fedit-finish t]
3478 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3479 ["Abort" org-table-fedit-abort t]
3480 "--"
3481 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3482 ["Complete Lisp Symbol" lisp-complete-symbol t]
3483 "--"
3484 "Shift Reference at Point"
3485 ["Up" org-table-fedit-ref-up t]
3486 ["Down" org-table-fedit-ref-down t]
3487 ["Left" org-table-fedit-ref-left t]
3488 ["Right" org-table-fedit-ref-right t]
3490 "Change Test Row for Column Formulas"
3491 ["Up" org-table-fedit-line-up t]
3492 ["Down" org-table-fedit-line-down t]
3493 "--"
3494 ["Scroll Table Window" org-table-fedit-scroll t]
3495 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3496 ["Show Table Grid" org-table-fedit-toggle-coordinates
3497 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3498 org-table-overlay-coordinates)]
3499 "--"
3500 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3501 :style toggle :selected org-table-buffer-is-an]))
3503 (defvar org-pos)
3505 ;;;###autoload
3506 (defun org-table-edit-formulas ()
3507 "Edit the formulas of the current table in a separate buffer."
3508 (interactive)
3509 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3510 (beginning-of-line 0))
3511 (unless (org-at-table-p) (user-error "Not at a table"))
3512 (org-table-get-specials)
3513 (let ((key (org-table-current-field-formula 'key 'noerror))
3514 (eql (sort (org-table-get-stored-formulas 'noerror)
3515 'org-table-formula-less-p))
3516 (pos (point-marker))
3517 (startline 1)
3518 (wc (current-window-configuration))
3519 (sel-win (selected-window))
3520 (titles '((column . "# Column Formulas\n")
3521 (field . "# Field and Range Formulas\n")
3522 (named . "# Named Field Formulas\n")))
3523 entry s type title)
3524 (org-switch-to-buffer-other-window "*Edit Formulas*")
3525 (erase-buffer)
3526 ;; Keep global-font-lock-mode from turning on font-lock-mode
3527 (let ((font-lock-global-modes '(not fundamental-mode)))
3528 (fundamental-mode))
3529 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3530 (org-set-local 'org-pos pos)
3531 (org-set-local 'org-window-configuration wc)
3532 (org-set-local 'org-selected-window sel-win)
3533 (use-local-map org-table-fedit-map)
3534 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3535 (easy-menu-add org-table-fedit-menu)
3536 (setq startline (org-current-line))
3537 (while (setq entry (pop eql))
3538 (setq type (cond
3539 ((string-match "\\`$[<>]" (car entry)) 'column)
3540 ((equal (string-to-char (car entry)) ?@) 'field)
3541 ((string-match "^[0-9]" (car entry)) 'column)
3542 (t 'named)))
3543 (when (setq title (assq type titles))
3544 (or (bobp) (insert "\n"))
3545 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3546 (setq titles (remove title titles)))
3547 (if (equal key (car entry)) (setq startline (org-current-line)))
3548 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3549 (car entry) " = " (cdr entry) "\n"))
3550 (remove-text-properties 0 (length s) '(face nil) s)
3551 (insert s))
3552 (if (eq org-table-use-standard-references t)
3553 (org-table-fedit-toggle-ref-type))
3554 (org-goto-line startline)
3555 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3557 (defun org-table-fedit-post-command ()
3558 (when (not (memq this-command '(lisp-complete-symbol)))
3559 (let ((win (selected-window)))
3560 (save-excursion
3561 (condition-case nil
3562 (org-table-show-reference)
3563 (error nil))
3564 (select-window win)))))
3566 (defun org-table-formula-to-user (s)
3567 "Convert a formula from internal to user representation."
3568 (if (eq org-table-use-standard-references t)
3569 (org-table-convert-refs-to-an s)
3572 (defun org-table-formula-from-user (s)
3573 "Convert a formula from user to internal representation."
3574 (if org-table-use-standard-references
3575 (org-table-convert-refs-to-rc s)
3578 (defun org-table-convert-refs-to-rc (s)
3579 "Convert spreadsheet references from A7 to @7$28.
3580 Works for single references, but also for entire formulas and even the
3581 full TBLFM line."
3582 (let ((start 0))
3583 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3584 (cond
3585 ((match-end 3)
3586 ;; format match, just advance
3587 (setq start (match-end 0)))
3588 ((and (> (match-beginning 0) 0)
3589 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3590 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3591 ;; 3.e5 or something like this.
3592 (setq start (match-end 0)))
3593 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3594 ;; (member (match-string 1 s)
3595 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3597 ;; function name, just advance
3598 (setq start (match-end 0)))
3600 (setq start (match-beginning 0)
3601 s (replace-match
3602 (if (equal (match-string 2 s) "&")
3603 (format "$%d" (org-letters-to-number (match-string 1 s)))
3604 (format "@%d$%d"
3605 (string-to-number (match-string 2 s))
3606 (org-letters-to-number (match-string 1 s))))
3607 t t s)))))
3610 (defun org-table-convert-refs-to-an (s)
3611 "Convert spreadsheet references from to @7$28 to AB7.
3612 Works for single references, but also for entire formulas and even the
3613 full TBLFM line."
3614 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3615 (setq s (replace-match
3616 (format "%s%d"
3617 (org-number-to-letters
3618 (string-to-number (match-string 2 s)))
3619 (string-to-number (match-string 1 s)))
3620 t t s)))
3621 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3622 (setq s (replace-match (concat "\\1"
3623 (org-number-to-letters
3624 (string-to-number (match-string 2 s))) "&")
3625 t nil s)))
3628 (defun org-letters-to-number (s)
3629 "Convert a base 26 number represented by letters into an integer.
3630 For example: AB -> 28."
3631 (let ((n 0))
3632 (setq s (upcase s))
3633 (while (> (length s) 0)
3634 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3635 s (substring s 1)))
3638 (defun org-number-to-letters (n)
3639 "Convert an integer into a base 26 number represented by letters.
3640 For example: 28 -> AB."
3641 (let ((s ""))
3642 (while (> n 0)
3643 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3644 n (/ (1- n) 26)))
3647 (defun org-table-time-string-to-seconds (s)
3648 "Convert a time string into numerical duration in seconds.
3649 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3650 If S is a string representing a number, keep this number."
3651 (if (equal s "")
3653 (let (hour minus min sec res)
3654 (cond
3655 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3656 (setq minus (< 0 (length (match-string 1 s)))
3657 hour (string-to-number (match-string 2 s))
3658 min (string-to-number (match-string 3 s))
3659 sec (string-to-number (match-string 4 s)))
3660 (if minus
3661 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3662 (setq res (+ (* hour 3600) (* min 60) sec))))
3663 ((and (not (string-match org-ts-regexp-both s))
3664 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3665 (setq minus (< 0 (length (match-string 1 s)))
3666 hour (string-to-number (match-string 2 s))
3667 min (string-to-number (match-string 3 s)))
3668 (if minus
3669 (setq res (- (+ (* hour 3600) (* min 60))))
3670 (setq res (+ (* hour 3600) (* min 60)))))
3671 (t (setq res (string-to-number s))))
3672 (number-to-string res))))
3674 (defun org-table-time-seconds-to-string (secs &optional output-format)
3675 "Convert a number of seconds to a time string.
3676 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3677 minutes or seconds."
3678 (let* ((secs0 (abs secs))
3679 (res
3680 (cond ((eq output-format 'days)
3681 (format "%.3f" (/ (float secs0) 86400)))
3682 ((eq output-format 'hours)
3683 (format "%.2f" (/ (float secs0) 3600)))
3684 ((eq output-format 'minutes)
3685 (format "%.1f" (/ (float secs0) 60)))
3686 ((eq output-format 'seconds)
3687 (format "%d" secs0))
3688 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3689 (if (< secs 0) (concat "-" res) res)))
3691 (defun org-table-fedit-convert-buffer (function)
3692 "Convert all references in this buffer, using FUNCTION."
3693 (let ((line (org-current-line)))
3694 (goto-char (point-min))
3695 (while (not (eobp))
3696 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3697 (delete-region (point) (point-at-eol))
3698 (or (eobp) (forward-char 1)))
3699 (org-goto-line line)))
3701 (defun org-table-fedit-toggle-ref-type ()
3702 "Convert all references in the buffer from B3 to @3$2 and back."
3703 (interactive)
3704 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3705 (org-table-fedit-convert-buffer
3706 (if org-table-buffer-is-an
3707 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3708 (message "Reference type switched to %s"
3709 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3711 (defun org-table-fedit-ref-up ()
3712 "Shift the reference at point one row/hline up."
3713 (interactive)
3714 (org-table-fedit-shift-reference 'up))
3715 (defun org-table-fedit-ref-down ()
3716 "Shift the reference at point one row/hline down."
3717 (interactive)
3718 (org-table-fedit-shift-reference 'down))
3719 (defun org-table-fedit-ref-left ()
3720 "Shift the reference at point one field to the left."
3721 (interactive)
3722 (org-table-fedit-shift-reference 'left))
3723 (defun org-table-fedit-ref-right ()
3724 "Shift the reference at point one field to the right."
3725 (interactive)
3726 (org-table-fedit-shift-reference 'right))
3728 (defun org-table-fedit-shift-reference (dir)
3729 (cond
3730 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3731 (if (memq dir '(left right))
3732 (org-rematch-and-replace 1 (eq dir 'left))
3733 (user-error "Cannot shift reference in this direction")))
3734 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3735 ;; A B3-like reference
3736 (if (memq dir '(up down))
3737 (org-rematch-and-replace 2 (eq dir 'up))
3738 (org-rematch-and-replace 1 (eq dir 'left))))
3739 ((org-at-regexp-p
3740 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3741 ;; An internal reference
3742 (if (memq dir '(up down))
3743 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3744 (org-rematch-and-replace 5 (eq dir 'left))))))
3746 (defun org-rematch-and-replace (n &optional decr hline)
3747 "Re-match the group N, and replace it with the shifted reference."
3748 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3749 (goto-char (match-beginning n))
3750 (and (looking-at (regexp-quote (match-string n)))
3751 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3752 t t)))
3754 (defun org-table-shift-refpart (ref &optional decr hline)
3755 "Shift a reference part REF.
3756 If DECR is set, decrease the references row/column, else increase.
3757 If HLINE is set, this may be a hline reference, it certainly is not
3758 a translation reference."
3759 (save-match-data
3760 (let* ((sign (string-match "^[-+]" ref)) n)
3762 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3763 (cond
3764 ((and hline (string-match "^I+" ref))
3765 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3766 (setq n (+ n (if decr -1 1)))
3767 (if (= n 0) (setq n (+ n (if decr -1 1))))
3768 (if sign
3769 (setq sign (if (< n 0) "-" "+") n (abs n))
3770 (setq n (max 1 n)))
3771 (concat sign (make-string n ?I)))
3773 ((string-match "^[0-9]+" ref)
3774 (setq n (string-to-number (concat sign ref)))
3775 (setq n (+ n (if decr -1 1)))
3776 (if sign
3777 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3778 (number-to-string (max 1 n))))
3780 ((string-match "^[a-zA-Z]+" ref)
3781 (org-number-to-letters
3782 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3784 (t (user-error "Cannot shift reference"))))))
3786 (defun org-table-fedit-toggle-coordinates ()
3787 "Toggle the display of coordinates in the referenced table."
3788 (interactive)
3789 (let ((pos (marker-position org-pos)))
3790 (with-current-buffer (marker-buffer org-pos)
3791 (save-excursion
3792 (goto-char pos)
3793 (org-table-toggle-coordinate-overlays)))))
3795 (defun org-table-fedit-finish (&optional arg)
3796 "Parse the buffer for formula definitions and install them.
3797 With prefix ARG, apply the new formulas to the table."
3798 (interactive "P")
3799 (org-table-remove-rectangle-highlight)
3800 (if org-table-use-standard-references
3801 (progn
3802 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3803 (setq org-table-buffer-is-an nil)))
3804 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3805 (goto-char (point-min))
3806 (while (re-search-forward
3807 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3808 nil t)
3809 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3810 form (match-string 3))
3811 (setq form (org-trim form))
3812 (when (not (equal form ""))
3813 (while (string-match "[ \t]*\n[ \t]*" form)
3814 (setq form (replace-match " " t t form)))
3815 (when (assoc var eql)
3816 (user-error "Double formulas for %s" var))
3817 (push (cons var form) eql)))
3818 (setq org-pos nil)
3819 (set-window-configuration org-window-configuration)
3820 (select-window sel-win)
3821 (goto-char pos)
3822 (unless (org-at-table-p)
3823 (user-error "Lost table position - cannot install formulas"))
3824 (org-table-store-formulas eql)
3825 (move-marker pos nil)
3826 (kill-buffer "*Edit Formulas*")
3827 (if arg
3828 (org-table-recalculate 'all)
3829 (message "New formulas installed - press C-u C-c C-c to apply."))))
3831 (defun org-table-fedit-abort ()
3832 "Abort editing formulas, without installing the changes."
3833 (interactive)
3834 (org-table-remove-rectangle-highlight)
3835 (let ((pos org-pos) (sel-win org-selected-window))
3836 (set-window-configuration org-window-configuration)
3837 (select-window sel-win)
3838 (goto-char pos)
3839 (move-marker pos nil)
3840 (message "Formula editing aborted without installing changes")))
3842 (defun org-table-fedit-lisp-indent ()
3843 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3844 (interactive)
3845 (let ((pos (point)) beg end ind)
3846 (beginning-of-line 1)
3847 (cond
3848 ((looking-at "[ \t]")
3849 (goto-char pos)
3850 (call-interactively 'lisp-indent-line))
3851 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3852 ((not (fboundp 'pp-buffer))
3853 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3854 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3855 (goto-char (- (match-end 0) 2))
3856 (setq beg (point))
3857 (setq ind (make-string (current-column) ?\ ))
3858 (condition-case nil (forward-sexp 1)
3859 (error
3860 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3861 (setq end (point))
3862 (save-restriction
3863 (narrow-to-region beg end)
3864 (if (eq last-command this-command)
3865 (progn
3866 (goto-char (point-min))
3867 (setq this-command nil)
3868 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3869 (replace-match " ")))
3870 (pp-buffer)
3871 (untabify (point-min) (point-max))
3872 (goto-char (1+ (point-min)))
3873 (while (re-search-forward "^." nil t)
3874 (beginning-of-line 1)
3875 (insert ind))
3876 (goto-char (point-max))
3877 (org-delete-backward-char 1)))
3878 (goto-char beg))
3879 (t nil))))
3881 (defvar org-show-positions nil)
3883 (defun org-table-show-reference (&optional local)
3884 "Show the location/value of the $ expression at point."
3885 (interactive)
3886 (org-table-remove-rectangle-highlight)
3887 (catch 'exit
3888 (let ((pos (if local (point) org-pos))
3889 (face2 'highlight)
3890 (org-inhibit-highlight-removal t)
3891 (win (selected-window))
3892 (org-show-positions nil)
3893 var name e what match dest)
3894 (if local (org-table-get-specials))
3895 (setq what (cond
3896 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3897 (setq match (concat (substring (match-string 0) 0 -1)
3898 "$1.."
3899 (substring (match-string 0) 0 -1)
3900 "$100"))
3901 'range)
3902 ((or (org-at-regexp-p org-table-range-regexp2)
3903 (org-at-regexp-p org-table-translate-regexp)
3904 (org-at-regexp-p org-table-range-regexp))
3905 (setq match
3906 (save-match-data
3907 (org-table-convert-refs-to-rc (match-string 0))))
3908 'range)
3909 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3910 ((org-at-regexp-p "\\$[0-9]+") 'column)
3911 ((not local) nil)
3912 (t (user-error "No reference at point")))
3913 match (and what (or match (match-string 0))))
3914 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3915 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3916 'secondary-selection))
3917 (org-add-hook 'before-change-functions
3918 'org-table-remove-rectangle-highlight)
3919 (if (eq what 'name) (setq var (substring match 1)))
3920 (when (eq what 'range)
3921 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3922 (setq match (org-table-formula-substitute-names match)))
3923 (unless local
3924 (save-excursion
3925 (end-of-line 1)
3926 (re-search-backward "^\\S-" nil t)
3927 (beginning-of-line 1)
3928 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3929 (setq dest
3930 (save-match-data
3931 (org-table-convert-refs-to-rc (match-string 1))))
3932 (org-table-add-rectangle-overlay
3933 (match-beginning 1) (match-end 1) face2))))
3934 (if (and (markerp pos) (marker-buffer pos))
3935 (if (get-buffer-window (marker-buffer pos))
3936 (select-window (get-buffer-window (marker-buffer pos)))
3937 (org-switch-to-buffer-other-window (get-buffer-window
3938 (marker-buffer pos)))))
3939 (goto-char pos)
3940 (org-table-force-dataline)
3941 (when dest
3942 (setq name (substring dest 1))
3943 (cond
3944 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3945 (setq e (assoc name org-table-named-field-locations))
3946 (org-goto-line (nth 1 e))
3947 (org-table-goto-column (nth 2 e)))
3948 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3949 (let ((l (string-to-number (match-string 1 dest)))
3950 (c (string-to-number (match-string 2 dest))))
3951 (org-goto-line (aref org-table-dlines l))
3952 (org-table-goto-column c)))
3953 (t (org-table-goto-column (string-to-number name))))
3954 (move-marker pos (point))
3955 (org-table-highlight-rectangle nil nil face2))
3956 (cond
3957 ((equal dest match))
3958 ((not match))
3959 ((eq what 'range)
3960 (condition-case nil
3961 (save-excursion
3962 (org-table-get-range match nil nil 'highlight))
3963 (error nil)))
3964 ((setq e (assoc var org-table-named-field-locations))
3965 (org-goto-line (nth 1 e))
3966 (org-table-goto-column (nth 2 e))
3967 (org-table-highlight-rectangle (point) (point))
3968 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3969 ((setq e (assoc var org-table-column-names))
3970 (org-table-goto-column (string-to-number (cdr e)))
3971 (org-table-highlight-rectangle (point) (point))
3972 (goto-char (org-table-begin))
3973 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3974 (org-table-end) t)
3975 (progn
3976 (goto-char (match-beginning 1))
3977 (org-table-highlight-rectangle)
3978 (message "Named column (column %s)" (cdr e)))
3979 (user-error "Column name not found")))
3980 ((eq what 'column)
3981 ;; column number
3982 (org-table-goto-column (string-to-number (substring match 1)))
3983 (org-table-highlight-rectangle (point) (point))
3984 (message "Column %s" (substring match 1)))
3985 ((setq e (assoc var org-table-local-parameters))
3986 (goto-char (org-table-begin))
3987 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3988 (progn
3989 (goto-char (match-beginning 1))
3990 (org-table-highlight-rectangle)
3991 (message "Local parameter."))
3992 (user-error "Parameter not found")))
3994 (cond
3995 ((not var) (user-error "No reference at point"))
3996 ((setq e (assoc var org-table-formula-constants-local))
3997 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3998 var (cdr e)))
3999 ((setq e (assoc var org-table-formula-constants))
4000 (message "Constant: $%s=%s in `org-table-formula-constants'."
4001 var (cdr e)))
4002 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4003 (message "Constant: $%s=%s, from `constants.el'%s."
4004 var e (format " (%s units)" constants-unit-system)))
4005 (t (user-error "Undefined name $%s" var)))))
4006 (goto-char pos)
4007 (when (and org-show-positions
4008 (not (memq this-command '(org-table-fedit-scroll
4009 org-table-fedit-scroll-down))))
4010 (push pos org-show-positions)
4011 (push org-table-current-begin-pos org-show-positions)
4012 (let ((min (apply 'min org-show-positions))
4013 (max (apply 'max org-show-positions)))
4014 (set-window-start (selected-window) min)
4015 (goto-char max)
4016 (or (pos-visible-in-window-p max)
4017 (set-window-start (selected-window) max))))
4018 (select-window win))))
4020 (defun org-table-force-dataline ()
4021 "Make sure the cursor is in a dataline in a table."
4022 (unless (save-excursion
4023 (beginning-of-line 1)
4024 (looking-at org-table-dataline-regexp))
4025 (let* ((re org-table-dataline-regexp)
4026 (p1 (save-excursion (re-search-forward re nil 'move)))
4027 (p2 (save-excursion (re-search-backward re nil 'move))))
4028 (cond ((and p1 p2)
4029 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4030 p1 p2)))
4031 ((or p1 p2) (goto-char (or p1 p2)))
4032 (t (user-error "No table dataline around here"))))))
4034 (defun org-table-fedit-line-up ()
4035 "Move cursor one line up in the window showing the table."
4036 (interactive)
4037 (org-table-fedit-move 'previous-line))
4039 (defun org-table-fedit-line-down ()
4040 "Move cursor one line down in the window showing the table."
4041 (interactive)
4042 (org-table-fedit-move 'next-line))
4044 (defun org-table-fedit-move (command)
4045 "Move the cursor in the window showing the table.
4046 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4047 (let ((org-table-allow-automatic-line-recalculation nil)
4048 (pos org-pos) (win (selected-window)) p)
4049 (select-window (get-buffer-window (marker-buffer org-pos)))
4050 (setq p (point))
4051 (call-interactively command)
4052 (while (and (org-at-table-p)
4053 (org-at-table-hline-p))
4054 (call-interactively command))
4055 (or (org-at-table-p) (goto-char p))
4056 (move-marker pos (point))
4057 (select-window win)))
4059 (defun org-table-fedit-scroll (N)
4060 (interactive "p")
4061 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4062 (scroll-other-window N)))
4064 (defun org-table-fedit-scroll-down (N)
4065 (interactive "p")
4066 (org-table-fedit-scroll (- N)))
4068 (defvar org-table-rectangle-overlays nil)
4070 (defun org-table-add-rectangle-overlay (beg end &optional face)
4071 "Add a new overlay."
4072 (let ((ov (make-overlay beg end)))
4073 (overlay-put ov 'face (or face 'secondary-selection))
4074 (push ov org-table-rectangle-overlays)))
4076 (defun org-table-highlight-rectangle (&optional beg end face)
4077 "Highlight rectangular region in a table."
4078 (setq beg (or beg (point)) end (or end (point)))
4079 (let ((b (min beg end))
4080 (e (max beg end))
4081 l1 c1 l2 c2 tmp)
4082 (and (boundp 'org-show-positions)
4083 (setq org-show-positions (cons b (cons e org-show-positions))))
4084 (goto-char (min beg end))
4085 (setq l1 (org-current-line)
4086 c1 (org-table-current-column))
4087 (goto-char (max beg end))
4088 (setq l2 (org-current-line)
4089 c2 (org-table-current-column))
4090 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
4091 (org-goto-line l1)
4092 (beginning-of-line 1)
4093 (loop for line from l1 to l2 do
4094 (when (looking-at org-table-dataline-regexp)
4095 (org-table-goto-column c1)
4096 (skip-chars-backward "^|\n") (setq beg (point))
4097 (org-table-goto-column c2)
4098 (skip-chars-forward "^|\n") (setq end (point))
4099 (org-table-add-rectangle-overlay beg end face))
4100 (beginning-of-line 2))
4101 (goto-char b))
4102 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
4104 (defun org-table-remove-rectangle-highlight (&rest ignore)
4105 "Remove the rectangle overlays."
4106 (unless org-inhibit-highlight-removal
4107 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4108 (mapc 'delete-overlay org-table-rectangle-overlays)
4109 (setq org-table-rectangle-overlays nil)))
4111 (defvar org-table-coordinate-overlays nil
4112 "Collects the coordinate grid overlays, so that they can be removed.")
4113 (make-variable-buffer-local 'org-table-coordinate-overlays)
4115 (defun org-table-overlay-coordinates ()
4116 "Add overlays to the table at point, to show row/column coordinates."
4117 (interactive)
4118 (mapc 'delete-overlay org-table-coordinate-overlays)
4119 (setq org-table-coordinate-overlays nil)
4120 (save-excursion
4121 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4122 (goto-char (org-table-begin))
4123 (while (org-at-table-p)
4124 (setq eol (point-at-eol))
4125 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4126 (push ov org-table-coordinate-overlays)
4127 (setq hline (looking-at org-table-hline-regexp))
4128 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4129 (format "%4d" (setq id (1+ id)))))
4130 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4131 (when hline
4132 (setq ic 0)
4133 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4134 (setq beg (1+ (match-beginning 0))
4135 ic (1+ ic)
4136 s1 (concat "$" (int-to-string ic))
4137 s2 (org-number-to-letters ic)
4138 str (if (eq org-table-use-standard-references t) s2 s1))
4139 (setq ov (make-overlay beg (+ beg (length str))))
4140 (push ov org-table-coordinate-overlays)
4141 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4142 (beginning-of-line 2)))))
4144 ;;;###autoload
4145 (defun org-table-toggle-coordinate-overlays ()
4146 "Toggle the display of Row/Column numbers in tables."
4147 (interactive)
4148 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4149 (message "Tables Row/Column numbers display turned %s"
4150 (if org-table-overlay-coordinates "on" "off"))
4151 (if (and (org-at-table-p) org-table-overlay-coordinates)
4152 (org-table-align))
4153 (unless org-table-overlay-coordinates
4154 (mapc 'delete-overlay org-table-coordinate-overlays)
4155 (setq org-table-coordinate-overlays nil)))
4157 ;;;###autoload
4158 (defun org-table-toggle-formula-debugger ()
4159 "Toggle the formula debugger in tables."
4160 (interactive)
4161 (setq org-table-formula-debug (not org-table-formula-debug))
4162 (message "Formula debugging has been turned %s"
4163 (if org-table-formula-debug "on" "off")))
4165 ;;; The orgtbl minor mode
4167 ;; Define a minor mode which can be used in other modes in order to
4168 ;; integrate the org-mode table editor.
4170 ;; This is really a hack, because the org-mode table editor uses several
4171 ;; keys which normally belong to the major mode, for example the TAB and
4172 ;; RET keys. Here is how it works: The minor mode defines all the keys
4173 ;; necessary to operate the table editor, but wraps the commands into a
4174 ;; function which tests if the cursor is currently inside a table. If that
4175 ;; is the case, the table editor command is executed. However, when any of
4176 ;; those keys is used outside a table, the function uses `key-binding' to
4177 ;; look up if the key has an associated command in another currently active
4178 ;; keymap (minor modes, major mode, global), and executes that command.
4179 ;; There might be problems if any of the keys used by the table editor is
4180 ;; otherwise used as a prefix key.
4182 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4183 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4184 ;; addresses this by checking explicitly for both bindings.
4186 ;; The optimized version (see variable `orgtbl-optimized') takes over
4187 ;; all keys which are bound to `self-insert-command' in the *global map*.
4188 ;; Some modes bind other commands to simple characters, for example
4189 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4190 ;; active, this binding is ignored inside tables and replaced with a
4191 ;; modified self-insert.
4194 (defvar orgtbl-mode-map (make-keymap)
4195 "Keymap for `orgtbl-mode'.")
4197 (defvar org-old-auto-fill-inhibit-regexp nil
4198 "Local variable used by `orgtbl-mode'.")
4200 (defconst orgtbl-line-start-regexp
4201 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4202 "Matches a line belonging to an orgtbl.")
4204 (defconst orgtbl-extra-font-lock-keywords
4205 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4206 0 (quote 'org-table) 'prepend))
4207 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4209 ;; Install it as a minor mode.
4210 (put 'orgtbl-mode :included t)
4211 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4213 ;;;###autoload
4214 (define-minor-mode orgtbl-mode
4215 "The `org-mode' table editor as a minor mode for use in other modes."
4216 :lighter " OrgTbl" :keymap orgtbl-mode-map
4217 (org-load-modules-maybe)
4218 (cond
4219 ((derived-mode-p 'org-mode)
4220 ;; Exit without error, in case some hook functions calls this
4221 ;; by accident in org-mode.
4222 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4223 (orgtbl-mode
4224 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4225 ;; Make sure we are first in minor-mode-map-alist
4226 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4227 ;; FIXME: maybe it should use emulation-mode-map-alists?
4228 (and c (setq minor-mode-map-alist
4229 (cons c (delq c minor-mode-map-alist)))))
4230 (org-set-local (quote org-table-may-need-update) t)
4231 (org-add-hook 'before-change-functions 'org-before-change-function
4232 nil 'local)
4233 (org-set-local 'org-old-auto-fill-inhibit-regexp
4234 auto-fill-inhibit-regexp)
4235 (org-set-local 'auto-fill-inhibit-regexp
4236 (if auto-fill-inhibit-regexp
4237 (concat orgtbl-line-start-regexp "\\|"
4238 auto-fill-inhibit-regexp)
4239 orgtbl-line-start-regexp))
4240 (add-to-invisibility-spec '(org-cwidth))
4241 (when (fboundp 'font-lock-add-keywords)
4242 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4243 (org-restart-font-lock))
4244 (easy-menu-add orgtbl-mode-menu))
4246 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4247 (org-table-cleanup-narrow-column-properties)
4248 (org-remove-from-invisibility-spec '(org-cwidth))
4249 (remove-hook 'before-change-functions 'org-before-change-function t)
4250 (when (fboundp 'font-lock-remove-keywords)
4251 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4252 (org-restart-font-lock))
4253 (easy-menu-remove orgtbl-mode-menu)
4254 (force-mode-line-update 'all))))
4256 (defun org-table-cleanup-narrow-column-properties ()
4257 "Remove all properties related to narrow-column invisibility."
4258 (let ((s (point-min)))
4259 (while (setq s (text-property-any s (point-max)
4260 'display org-narrow-column-arrow))
4261 (remove-text-properties s (1+ s) '(display t)))
4262 (setq s (point-min))
4263 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4264 (remove-text-properties s (1+ s) '(org-cwidth t)))
4265 (setq s (point-min))
4266 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4267 (remove-text-properties s (1+ s) '(invisible t)))))
4269 (defun orgtbl-make-binding (fun n &rest keys)
4270 "Create a function for binding in the table minor mode.
4271 FUN is the command to call inside a table. N is used to create a unique
4272 command name. KEYS are keys that should be checked in for a command
4273 to execute outside of tables."
4274 (eval
4275 (list 'defun
4276 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4277 '(arg)
4278 (concat "In tables, run `" (symbol-name fun) "'.\n"
4279 "Outside of tables, run the binding of `"
4280 (mapconcat #'key-description keys "' or `")
4281 "'.")
4282 '(interactive "p")
4283 (list 'if
4284 '(org-at-table-p)
4285 (list 'call-interactively (list 'quote fun))
4286 (list 'let '(orgtbl-mode)
4287 (list 'call-interactively
4288 (append '(or)
4289 (mapcar (lambda (k)
4290 (list 'key-binding k))
4291 keys)
4292 '('orgtbl-error))))))))
4294 (defun orgtbl-error ()
4295 "Error when there is no default binding for a table key."
4296 (interactive)
4297 (user-error "This key has no function outside tables"))
4299 (defun orgtbl-setup ()
4300 "Setup orgtbl keymaps."
4301 (let ((nfunc 0)
4302 (bindings
4303 '(([(meta shift left)] org-table-delete-column)
4304 ([(meta left)] org-table-move-column-left)
4305 ([(meta right)] org-table-move-column-right)
4306 ([(meta shift right)] org-table-insert-column)
4307 ([(meta shift up)] org-table-kill-row)
4308 ([(meta shift down)] org-table-insert-row)
4309 ([(meta up)] org-table-move-row-up)
4310 ([(meta down)] org-table-move-row-down)
4311 ("\C-c\C-w" org-table-cut-region)
4312 ("\C-c\M-w" org-table-copy-region)
4313 ("\C-c\C-y" org-table-paste-rectangle)
4314 ("\C-c\C-w" org-table-wrap-region)
4315 ("\C-c-" org-table-insert-hline)
4316 ("\C-c}" org-table-toggle-coordinate-overlays)
4317 ("\C-c{" org-table-toggle-formula-debugger)
4318 ("\C-m" org-table-next-row)
4319 ([(shift return)] org-table-copy-down)
4320 ("\C-c?" org-table-field-info)
4321 ("\C-c " org-table-blank-field)
4322 ("\C-c+" org-table-sum)
4323 ("\C-c=" org-table-eval-formula)
4324 ("\C-c'" org-table-edit-formulas)
4325 ("\C-c`" org-table-edit-field)
4326 ("\C-c*" org-table-recalculate)
4327 ("\C-c^" org-table-sort-lines)
4328 ("\M-a" org-table-beginning-of-field)
4329 ("\M-e" org-table-end-of-field)
4330 ([(control ?#)] org-table-rotate-recalc-marks)))
4331 elt key fun cmd)
4332 (while (setq elt (pop bindings))
4333 (setq nfunc (1+ nfunc))
4334 (setq key (org-key (car elt))
4335 fun (nth 1 elt)
4336 cmd (orgtbl-make-binding fun nfunc key))
4337 (org-defkey orgtbl-mode-map key cmd))
4339 ;; Special treatment needed for TAB and RET
4340 (org-defkey orgtbl-mode-map [(return)]
4341 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4342 (org-defkey orgtbl-mode-map "\C-m"
4343 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4345 (org-defkey orgtbl-mode-map [(tab)]
4346 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4347 (org-defkey orgtbl-mode-map "\C-i"
4348 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4350 (org-defkey orgtbl-mode-map [(shift tab)]
4351 (orgtbl-make-binding 'org-table-previous-field 104
4352 [(shift tab)] [(tab)] "\C-i"))
4355 (unless (featurep 'xemacs)
4356 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4357 (orgtbl-make-binding 'org-table-previous-field 107
4358 [S-iso-lefttab] [backtab] [(shift tab)]
4359 [(tab)] "\C-i")))
4361 (org-defkey orgtbl-mode-map [backtab]
4362 (orgtbl-make-binding 'org-table-previous-field 108
4363 [backtab] [S-iso-lefttab] [(shift tab)]
4364 [(tab)] "\C-i"))
4366 (org-defkey orgtbl-mode-map "\M-\C-m"
4367 (orgtbl-make-binding 'org-table-wrap-region 105
4368 "\M-\C-m" [(meta return)]))
4369 (org-defkey orgtbl-mode-map [(meta return)]
4370 (orgtbl-make-binding 'org-table-wrap-region 106
4371 [(meta return)] "\M-\C-m"))
4373 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4374 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4376 (when orgtbl-optimized
4377 ;; If the user wants maximum table support, we need to hijack
4378 ;; some standard editing functions
4379 (org-remap orgtbl-mode-map
4380 'self-insert-command 'orgtbl-self-insert-command
4381 'delete-char 'org-delete-char
4382 'delete-backward-char 'org-delete-backward-char)
4383 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4384 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4385 '("OrgTbl"
4386 ["Create or convert" org-table-create-or-convert-from-region
4387 :active (not (org-at-table-p)) :keys "C-c |" ]
4388 "--"
4389 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4390 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4391 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4392 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4393 "--"
4394 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4395 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4396 ["Copy Field from Above"
4397 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4398 "--"
4399 ("Column"
4400 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4401 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4402 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4403 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4404 ("Row"
4405 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4406 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4407 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4408 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4409 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4410 "--"
4411 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4412 ("Rectangle"
4413 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4414 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4415 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4416 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4417 "--"
4418 ("Radio tables"
4419 ["Insert table template" orgtbl-insert-radio-table
4420 (assq major-mode orgtbl-radio-table-templates)]
4421 ["Comment/uncomment table" orgtbl-toggle-comment t])
4422 "--"
4423 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4424 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4425 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4426 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4427 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4428 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4429 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4430 ["Sum Column/Rectangle" org-table-sum
4431 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4432 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4433 ["Debug Formulas"
4434 org-table-toggle-formula-debugger :active (org-at-table-p)
4435 :keys "C-c {"
4436 :style toggle :selected org-table-formula-debug]
4437 ["Show Col/Row Numbers"
4438 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4439 :keys "C-c }"
4440 :style toggle :selected org-table-overlay-coordinates]
4441 "--"
4442 ("Plot"
4443 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4444 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4447 (defun orgtbl-ctrl-c-ctrl-c (arg)
4448 "If the cursor is inside a table, realign the table.
4449 If it is a table to be sent away to a receiver, do it.
4450 With prefix arg, also recompute table."
4451 (interactive "P")
4452 (let ((case-fold-search t) (pos (point)) action)
4453 (save-excursion
4454 (beginning-of-line 1)
4455 (setq action (cond
4456 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4457 ((looking-at "[ \t]*|") pos)
4458 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4459 (cond
4460 ((integerp action)
4461 (goto-char action)
4462 (org-table-maybe-eval-formula)
4463 (if arg
4464 (call-interactively 'org-table-recalculate)
4465 (org-table-maybe-recalculate-line))
4466 (call-interactively 'org-table-align)
4467 (when (orgtbl-send-table 'maybe)
4468 (run-hooks 'orgtbl-after-send-table-hook)))
4469 ((eq action 'recalc)
4470 (save-excursion
4471 (beginning-of-line 1)
4472 (skip-chars-backward " \r\n\t")
4473 (if (org-at-table-p)
4474 (org-call-with-arg 'org-table-recalculate t))))
4475 (t (let (orgtbl-mode)
4476 (call-interactively (key-binding "\C-c\C-c")))))))
4478 (defun orgtbl-create-or-convert-from-region (arg)
4479 "Create table or convert region to table, if no conflicting binding.
4480 This installs the table binding `C-c |', but only if there is no
4481 conflicting binding to this key outside orgtbl-mode."
4482 (interactive "P")
4483 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4484 (if cmd
4485 (call-interactively cmd)
4486 (call-interactively 'org-table-create-or-convert-from-region))))
4488 (defun orgtbl-tab (arg)
4489 "Justification and field motion for `orgtbl-mode'."
4490 (interactive "P")
4491 (if arg (org-table-edit-field t)
4492 (org-table-justify-field-maybe)
4493 (org-table-next-field)))
4495 (defun orgtbl-ret ()
4496 "Justification and field motion for `orgtbl-mode'."
4497 (interactive)
4498 (if (bobp)
4499 (newline)
4500 (org-table-justify-field-maybe)
4501 (org-table-next-row)))
4503 (defun orgtbl-self-insert-command (N)
4504 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4505 If the cursor is in a table looking at whitespace, the whitespace is
4506 overwritten, and the table is not marked as requiring realignment."
4507 (interactive "p")
4508 (if (and (org-at-table-p)
4510 (and org-table-auto-blank-field
4511 (member last-command
4512 '(orgtbl-hijacker-command-100
4513 orgtbl-hijacker-command-101
4514 orgtbl-hijacker-command-102
4515 orgtbl-hijacker-command-103
4516 orgtbl-hijacker-command-104
4517 orgtbl-hijacker-command-105
4518 yas/expand))
4519 (org-table-blank-field))
4521 (eq N 1)
4522 (looking-at "[^|\n]* +|"))
4523 (let (org-table-may-need-update)
4524 (goto-char (1- (match-end 0)))
4525 (org-delete-backward-char 1)
4526 (goto-char (match-beginning 0))
4527 (self-insert-command N))
4528 (setq org-table-may-need-update t)
4529 (let* (orgtbl-mode
4531 (cmd (or (key-binding
4532 (or (and (listp function-key-map)
4533 (setq a (assoc last-input-event function-key-map))
4534 (cdr a))
4535 (vector last-input-event)))
4536 'self-insert-command)))
4537 (call-interactively cmd)
4538 (if (and org-self-insert-cluster-for-undo
4539 (eq cmd 'self-insert-command))
4540 (if (not (eq last-command 'orgtbl-self-insert-command))
4541 (setq org-self-insert-command-undo-counter 1)
4542 (if (>= org-self-insert-command-undo-counter 20)
4543 (setq org-self-insert-command-undo-counter 1)
4544 (and (> org-self-insert-command-undo-counter 0)
4545 buffer-undo-list
4546 (not (cadr buffer-undo-list)) ; remove nil entry
4547 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4548 (setq org-self-insert-command-undo-counter
4549 (1+ org-self-insert-command-undo-counter))))))))
4551 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4552 "Regular expression matching exponentials as produced by calc.")
4554 (defun orgtbl-gather-send-defs ()
4555 "Gather a plist of :name, :transform, :params for each destination before
4556 a radio table."
4557 (save-excursion
4558 (goto-char (org-table-begin))
4559 (let (rtn)
4560 (beginning-of-line 0)
4561 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4562 (let ((name (org-no-properties (match-string 1)))
4563 (transform (intern (match-string 2)))
4564 (params (if (match-end 3)
4565 (read (concat "(" (match-string 3) ")")))))
4566 (push (list :name name :transform transform :params params)
4567 rtn)
4568 (beginning-of-line 0)))
4569 rtn)))
4571 (defun orgtbl-send-replace-tbl (name txt)
4572 "Find and replace table NAME with TXT."
4573 (save-excursion
4574 (goto-char (point-min))
4575 (unless (re-search-forward
4576 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4577 (user-error "Don't know where to insert translated table"))
4578 (let ((beg (line-beginning-position 2)))
4579 (unless (re-search-forward
4580 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4581 (user-error "Cannot find end of insertion region"))
4582 (beginning-of-line)
4583 (delete-region beg (point)))
4584 (insert txt "\n")))
4586 ;;;###autoload
4587 (defun org-table-to-lisp (&optional txt)
4588 "Convert the table at point to a Lisp structure.
4589 The structure will be a list. Each item is either the symbol `hline'
4590 for a horizontal separator line, or a list of field values as strings.
4591 The table is taken from the parameter TXT, or from the buffer at point."
4592 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4593 (let ((txt (or txt
4594 (buffer-substring-no-properties (org-table-begin)
4595 (org-table-end)))))
4596 (mapcar (lambda (x)
4597 (if (string-match org-table-hline-regexp x) 'hline
4598 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4599 (org-split-string txt "[ \t]*\n[ \t]*"))))
4601 (defun orgtbl-send-table (&optional maybe)
4602 "Send a transformed version of table at point to the receiver position.
4603 With argument MAYBE, fail quietly if no transformation is defined
4604 for this table."
4605 (interactive)
4606 (catch 'exit
4607 (unless (org-at-table-p) (user-error "Not at a table"))
4608 ;; when non-interactive, we assume align has just happened.
4609 (when (org-called-interactively-p 'any) (org-table-align))
4610 (let ((dests (orgtbl-gather-send-defs))
4611 (table (org-table-to-lisp
4612 (buffer-substring-no-properties (org-table-begin)
4613 (org-table-end))))
4614 (ntbl 0))
4615 (unless dests
4616 (if maybe (throw 'exit nil)
4617 (user-error "Don't know how to transform this table")))
4618 (dolist (dest dests)
4619 (let ((name (plist-get dest :name))
4620 (transform (plist-get dest :transform))
4621 (params (plist-get dest :params)))
4622 (unless (fboundp transform)
4623 (user-error "No such transformation function %s" transform))
4624 (orgtbl-send-replace-tbl name (funcall transform table params)))
4625 (incf ntbl))
4626 (message "Table converted and installed at %d receiver location%s"
4627 ntbl (if (> ntbl 1) "s" ""))
4628 (and (> ntbl 0) ntbl))))
4630 (defun org-remove-by-index (list indices &optional i0)
4631 "Remove the elements in LIST with indices in INDICES.
4632 First element has index 0, or I0 if given."
4633 (if (not indices)
4634 list
4635 (if (integerp indices) (setq indices (list indices)))
4636 (setq i0 (1- (or i0 0)))
4637 (delq :rm (mapcar (lambda (x)
4638 (setq i0 (1+ i0))
4639 (if (memq i0 indices) :rm x))
4640 list))))
4642 (defun orgtbl-toggle-comment ()
4643 "Comment or uncomment the orgtbl at point."
4644 (interactive)
4645 (let* ((case-fold-search t)
4646 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4647 (re2 (concat "^" orgtbl-line-start-regexp))
4648 (commented (save-excursion (beginning-of-line 1)
4649 (cond ((looking-at re1) t)
4650 ((looking-at re2) nil)
4651 (t (user-error "Not at an org table")))))
4652 (re (if commented re1 re2))
4653 beg end)
4654 (save-excursion
4655 (beginning-of-line 1)
4656 (while (looking-at re) (beginning-of-line 0))
4657 (beginning-of-line 2)
4658 (setq beg (point))
4659 (while (looking-at re) (beginning-of-line 2))
4660 (setq end (point)))
4661 (comment-region beg end (if commented '(4) nil))))
4663 (defun orgtbl-insert-radio-table ()
4664 "Insert a radio table template appropriate for this major mode."
4665 (interactive)
4666 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4667 (txt (nth 1 e))
4668 name pos)
4669 (unless e (user-error "No radio table setup defined for %s" major-mode))
4670 (setq name (read-string "Table name: "))
4671 (while (string-match "%n" txt)
4672 (setq txt (replace-match name t t txt)))
4673 (or (bolp) (insert "\n"))
4674 (setq pos (point))
4675 (insert txt)
4676 (goto-char pos)))
4678 ;;;###autoload
4679 (defun orgtbl-to-generic (table params)
4680 "Convert the orgtbl-mode TABLE to some other format.
4682 This generic routine can be used for many standard cases.
4684 TABLE is a list, each entry either the symbol `hline' for
4685 a horizontal separator line, or a list of fields for that
4686 line. PARAMS is a property list of parameters that can
4687 influence the conversion.
4689 Valid parameters are:
4691 :backend, :raw
4693 Export back-end used as a basis to transcode elements of the
4694 table, when no specific parameter applies to it. It is also
4695 used to translate cells contents. You can prevent this by
4696 setting :raw property to a non-nil value.
4698 :splice
4700 When non-nil, only convert rows, not the table itself. This is
4701 equivalent to setting to the empty string both :tstart
4702 and :tend, which see.
4704 :skip
4706 When set to an integer N, skip the first N lines of the table.
4707 Horizontal separation lines do count for this parameter!
4709 :skipcols
4711 List of columns that should be skipped. If the table has
4712 a column with calculation marks, that column is automatically
4713 discarded beforehand.
4715 :hline
4717 String to be inserted on horizontal separation lines. May be
4718 nil to ignore these lines altogether.
4720 :sep
4722 Separator between two fields, as a string.
4724 Each in the following group may be either a string or a function
4725 of no arguments returning a string:
4727 :tstart, :tend
4729 Strings to start and end the table. Ignored when :splice is t.
4731 :lstart, :lend
4733 Strings to start and end a new table line.
4735 :llstart, :llend
4737 Strings to start and end the last table line. Default,
4738 respectively, to :lstart and :lend.
4740 Each in the following group may be a string or a function of one
4741 argument (either the cells in the current row, as a list of
4742 strings, or the current cell) returning a string:
4744 :lfmt
4746 Format string for an entire row, with enough %s to capture all
4747 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4749 :llfmt
4751 Format for the entire last line, defaults to :lfmt.
4753 :fmt
4755 A format to be used to wrap the field, should contain %s for
4756 the original field value. For example, to wrap everything in
4757 dollars, you could use :fmt \"$%s$\". This may also be
4758 a property list with column numbers and format strings, or
4759 functions, e.g.,
4761 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4763 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4765 Same as above, specific for the header lines in the table.
4766 All lines before the first hline are treated as header. If
4767 any of these is not present, the data line value is used.
4769 This may be either a string or a function of two arguments:
4771 :efmt
4773 Use this format to print numbers with exponential. The format
4774 should have %s twice for inserting mantissa and exponent, for
4775 example \"%s\\\\times10^{%s}\". This may also be a property
4776 list with column numbers and format strings or functions.
4777 :fmt will still be applied after :efmt."
4778 (let ((backend (plist-get params :backend)))
4779 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4780 (user-error "Unknown :backend value"))
4781 (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
4782 (org-trim
4783 (org-export-string-as
4784 ;; Return TABLE as Org syntax. Tolerate non-string cells.
4785 (with-output-to-string
4786 (dolist (e table)
4787 (cond ((eq e 'hline) (princ "|--\n"))
4788 ((consp e)
4789 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4790 (princ "\n")))))
4791 ;; Build a custom back-end according to PARAMS. Before defining
4792 ;; a translator, check if there is anything to do. When there
4793 ;; isn't, let BACKEND handle the element.
4794 (org-export-create-backend
4795 :parent (or backend 'org)
4796 :filters
4797 '((:filter-parse-tree
4798 ;; Handle :skip parameter.
4799 (lambda (tree backend info)
4800 (let ((skip (plist-get info :skip)))
4801 (when skip
4802 (unless (wholenump skip) (user-error "Wrong :skip value"))
4803 (let ((n 0))
4804 (org-element-map tree 'table-row
4805 (lambda (row)
4806 (if (>= n skip) t
4807 (org-element-extract-element row)
4808 (incf n)
4809 nil))
4810 info t))
4811 tree)))
4812 ;; Handle :skipcols parameter.
4813 (lambda (tree backend info)
4814 (let ((skipcols (plist-get info :skipcols)))
4815 (when skipcols
4816 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4817 (org-element-map tree 'table
4818 (lambda (table)
4819 (let ((specialp
4820 (org-export-table-has-special-column-p table)))
4821 (dolist (row (org-element-contents table))
4822 (when (eq (org-element-property :type row) 'standard)
4823 (let ((c 1))
4824 (dolist (cell (nthcdr (if specialp 1 0)
4825 (org-element-contents row)))
4826 (when (memq c skipcols)
4827 (org-element-extract-element cell))
4828 (incf c)))))))
4829 info)
4830 tree)))))
4831 :transcoders
4832 `((table . ,(org-table--to-generic-table params))
4833 (table-row . ,(org-table--to-generic-row params))
4834 (table-cell . ,(org-table--to-generic-cell params))
4835 ;; Section. Return contents to avoid garbage around table.
4836 (section . (lambda (s c i) c))))
4837 'body-only (org-combine-plists params '(:with-tables t))))))
4839 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4840 (cond ((null value) nil)
4841 ((functionp value) `(funcall ',value ,@args))
4842 ((stringp value)
4843 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4844 (args `(format ,value ,@args))
4845 (t value)))
4846 ((and with-cons (consp value))
4847 `(let ((val (cadr (memq column ',value))))
4848 (cond ((null val) contents)
4849 ((stringp val) (format val ,@args))
4850 ((functionp val) (funcall val ,@args))
4851 (t (user-error "Wrong %s value" ,name)))))
4852 (t (user-error "Wrong %s value" name))))
4854 (defun org-table--to-generic-table (params)
4855 "Return custom table transcoder according to PARAMS.
4856 PARAMS is a plist. See `orgtbl-to-generic' for more
4857 information."
4858 (let ((backend (plist-get params :backend))
4859 (splice (plist-get params :splice))
4860 (tstart (plist-get params :tstart))
4861 (tend (plist-get params :tend)))
4862 `(lambda (table contents info)
4863 (concat
4864 ,(and tstart (not splice)
4865 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4866 ,(if (or (not backend) tstart tend splice) 'contents
4867 `(org-export-with-backend ',backend table contents info))
4868 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4870 (defun org-table--to-generic-row (params)
4871 "Return custom table row transcoder according to PARAMS.
4872 PARAMS is a plist. See `orgtbl-to-generic' for more
4873 information."
4874 (let* ((backend (plist-get params :backend))
4875 (lstart (plist-get params :lstart))
4876 (llstart (plist-get params :llstart))
4877 (hlstart (plist-get params :hlstart))
4878 (hllstart (plist-get params :hllstart))
4879 (lend (plist-get params :lend))
4880 (llend (plist-get params :llend))
4881 (hlend (plist-get params :hlend))
4882 (hllend (plist-get params :hllend))
4883 (lfmt (plist-get params :lfmt))
4884 (llfmt (plist-get params :llfmt))
4885 (hlfmt (plist-get params :hlfmt))
4886 (hllfmt (plist-get params :hllfmt)))
4887 `(lambda (row contents info)
4888 (if (eq (org-element-property :type row) 'rule)
4889 ,(cond
4890 ((plist-member params :hline)
4891 (org-table--generic-apply (plist-get params :hline) ":hline"))
4892 (backend `(org-export-with-backend ',backend row nil info)))
4893 (let ((headerp (org-export-table-row-in-header-p row info))
4894 (lastp (not (org-export-get-next-element row info)))
4895 (last-header-p (org-export-table-row-ends-header-p row info)))
4896 (when contents
4897 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4898 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4899 ;; `:lstart', `:lend' and their relatives.
4900 ,(let ((cells
4901 '(org-element-map row 'table-cell
4902 (lambda (cell)
4903 ;; Export all cells, without separators.
4905 ;; Use `org-export-data-with-backend'
4906 ;; instead of `org-export-data' to eschew
4907 ;; cached values, which
4908 ;; ignore :orgtbl-ignore-sep parameter.
4909 (org-export-data-with-backend
4910 cell
4911 (plist-get info :back-end)
4912 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4913 info)))
4914 `(cond
4915 ,(and hllfmt
4916 `(last-header-p ,(org-table--generic-apply
4917 hllfmt ":hllfmt" nil cells)))
4918 ,(and hlfmt
4919 `(headerp ,(org-table--generic-apply
4920 hlfmt ":hlfmt" nil cells)))
4921 ,(and llfmt
4922 `(lastp ,(org-table--generic-apply
4923 llfmt ":llfmt" nil cells)))
4925 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4926 `(concat
4927 (cond
4928 ,(and
4929 (or hllstart hllend)
4930 `(last-header-p
4931 (concat
4932 ,(org-table--generic-apply hllstart ":hllstart")
4933 contents
4934 ,(org-table--generic-apply hllend ":hllend"))))
4935 ,(and
4936 (or hlstart hlend)
4937 `(headerp
4938 (concat
4939 ,(org-table--generic-apply hlstart ":hlstart")
4940 contents
4941 ,(org-table--generic-apply hlend ":hlend"))))
4942 ,(and
4943 (or llstart llend)
4944 `(lastp
4945 (concat
4946 ,(org-table--generic-apply llstart ":llstart")
4947 contents
4948 ,(org-table--generic-apply llend ":llend"))))
4950 ,(cond
4951 ((or lstart lend)
4952 `(concat
4953 ,(org-table--generic-apply lstart ":lstart")
4954 contents
4955 ,(org-table--generic-apply lend ":lend")))
4956 (backend
4957 `(org-export-with-backend
4958 ',backend row contents info))
4959 (t 'contents)))))))))))))))
4961 (defun org-table--to-generic-cell (params)
4962 "Return custom table cell transcoder according to PARAMS.
4963 PARAMS is a plist. See `orgtbl-to-generic' for more
4964 information."
4965 (let* ((backend (plist-get params :backend))
4966 (efmt (plist-get params :efmt))
4967 (fmt (plist-get params :fmt))
4968 (hfmt (plist-get params :hfmt))
4969 (sep (plist-get params :sep))
4970 (hsep (plist-get params :hsep)))
4971 `(lambda (cell contents info)
4972 (let ((headerp (org-export-table-row-in-header-p
4973 (org-export-get-parent-element cell) info))
4974 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4975 ;; Make sure that contents are exported as Org data when :raw
4976 ;; parameter is non-nil.
4977 ,(when (and backend (plist-get params :raw))
4978 `(setq contents
4979 ;; Since we don't know what are the pseudo object
4980 ;; types defined in backend, we cannot pass them to
4981 ;; `org-element-interpret-data'. As a consequence,
4982 ;; they will be treated as pseudo elements, and
4983 ;; will have newlines appended instead of spaces.
4984 ;; Therefore, we must make sure :post-blank value
4985 ;; is really turned into spaces.
4986 (replace-regexp-in-string
4987 "\n" " "
4988 (org-trim
4989 (org-element-interpret-data
4990 (org-element-contents cell))))))
4991 (when contents
4992 ;; Check if we can apply `:efmt' on CONTENTS.
4993 ,(when efmt
4994 `(when (string-match orgtbl-exp-regexp contents)
4995 (let ((mantissa (match-string 1 contents))
4996 (exponent (match-string 2 contents)))
4997 (setq contents ,(org-table--generic-apply
4998 efmt ":efmt" t 'mantissa 'exponent)))))
4999 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5000 (cond
5001 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5002 hfmt ":hfmt" t 'contents))))
5003 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5004 fmt ":fmt" t 'contents))))))
5005 ;; If a separator is provided, use it instead of BACKEND's.
5006 ;; Separators are ignored when LFMT (or equivalent) is
5007 ;; provided.
5008 ,(cond
5009 ((or hsep sep)
5010 `(if (or ,(and (not sep) '(not headerp))
5011 (plist-get info :orgtbl-ignore-sep)
5012 (not (org-export-get-next-element cell info)))
5013 ,(if (not backend) 'contents
5014 `(org-export-with-backend ',backend cell contents info))
5015 (concat contents
5016 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5017 (or hsep sep)))))
5018 (backend `(org-export-with-backend ',backend cell contents info))
5019 (t 'contents))))))
5021 ;;;###autoload
5022 (defun orgtbl-to-tsv (table params)
5023 "Convert the orgtbl-mode table to TAB separated material."
5024 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5026 ;;;###autoload
5027 (defun orgtbl-to-csv (table params)
5028 "Convert the orgtbl-mode table to CSV material.
5029 This does take care of the proper quoting of fields with comma or quotes."
5030 (orgtbl-to-generic table
5031 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5032 params)))
5034 ;;;###autoload
5035 (defun orgtbl-to-latex (table params)
5036 "Convert the orgtbl-mode TABLE to LaTeX.
5038 TABLE is a list, each entry either the symbol `hline' for
5039 a horizontal separator line, or a list of fields for that line.
5040 PARAMS is a property list of parameters that can influence the
5041 conversion. All parameters from `orgtbl-to-generic' are
5042 supported. It is also possible to use the following ones:
5044 :booktabs
5046 When non-nil, use formal \"booktabs\" style.
5048 :environment
5050 Specify environment to use, as a string. If you use
5051 \"longtable\", you may also want to specify :language property,
5052 as a string, to get proper continuation strings."
5053 (require 'ox-latex)
5054 (orgtbl-to-generic
5055 table
5056 (org-combine-plists
5057 ;; Provide sane default values.
5058 (list :backend 'latex
5059 :latex-default-table-mode 'table
5060 :latex-tables-centered nil
5061 :latex-tables-booktabs (plist-get params :booktabs)
5062 :latex-table-scientific-notation nil
5063 :latex-default-table-environment
5064 (or (plist-get params :environment) "tabular"))
5065 params)))
5067 ;;;###autoload
5068 (defun orgtbl-to-html (table params)
5069 "Convert the orgtbl-mode TABLE to HTML.
5071 TABLE is a list, each entry either the symbol `hline' for
5072 a horizontal separator line, or a list of fields for that line.
5073 PARAMS is a property list of parameters that can influence the
5074 conversion. All parameters from `orgtbl-to-generic' are
5075 supported. It is also possible to use the following one:
5077 :attributes
5079 Attributes and values, as a plist, which will be used in
5080 <table> tag."
5081 (require 'ox-html)
5082 (orgtbl-to-generic
5083 table
5084 (org-combine-plists
5085 ;; Provide sane default values.
5086 (list :backend 'html
5087 :html-table-data-tags '("<td%s>" . "</td>")
5088 :html-table-use-header-tags-for-first-column nil
5089 :html-table-align-individual-fields t
5090 :html-table-row-tags '("<tr>" . "</tr>")
5091 :html-table-attributes
5092 (if (plist-member params :attributes)
5093 (plist-get params :attributes)
5094 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5095 :frame "hsides")))
5096 params)))
5098 ;;;###autoload
5099 (defun orgtbl-to-texinfo (table params)
5100 "Convert the orgtbl-mode TABLE to Texinfo.
5102 TABLE is a list, each entry either the symbol `hline' for
5103 a horizontal separator line, or a list of fields for that line.
5104 PARAMS is a property list of parameters that can influence the
5105 conversion. All parameters from `orgtbl-to-generic' are
5106 supported. It is also possible to use the following one:
5108 :columns
5110 Column widths, as a string. When providing column fractions,
5111 \"@columnfractions\" command can be omitted."
5112 (require 'ox-texinfo)
5113 (let ((output
5114 (orgtbl-to-generic
5115 table
5116 (org-combine-plists
5117 (list :backend 'texinfo
5118 :texinfo-tables-verbatim nil
5119 :texinfo-table-scientific-notation nil)
5120 params)))
5121 (columns (let ((w (plist-get params :columns)))
5122 (cond ((not w) nil)
5123 ((org-string-match-p "{\\|@columnfractions " w) w)
5124 (t (concat "@columnfractions " w))))))
5125 (if (not columns) output
5126 (replace-regexp-in-string
5127 "@multitable \\(.*\\)" columns output t nil 1))))
5129 ;;;###autoload
5130 (defun orgtbl-to-orgtbl (table params)
5131 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5133 TABLE is a list, each entry either the symbol `hline' for
5134 a horizontal separator line, or a list of fields for that line.
5135 PARAMS is a property list of parameters that can influence the
5136 conversion. All parameters from `orgtbl-to-generic' are
5137 supported.
5139 Useful when slicing one table into many. The :hline, :sep,
5140 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5141 be set to provide ORGTBL directives for the generated table."
5142 (require 'ox-org)
5143 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5145 (defun orgtbl-to-table.el (table params)
5146 "Convert the orgtbl-mode TABLE into a table.el table.
5147 TABLE is a list, each entry either the symbol `hline' for
5148 a horizontal separator line, or a list of fields for that line.
5149 PARAMS is a property list of parameters that can influence the
5150 conversion. All parameters from `orgtbl-to-generic' are
5151 supported."
5152 (with-temp-buffer
5153 (insert (orgtbl-to-orgtbl table params))
5154 (org-table-align)
5155 (replace-regexp-in-string
5156 "-|" "-+"
5157 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5159 (defun orgtbl-to-unicode (table params)
5160 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5162 TABLE is a list, each entry either the symbol `hline' for
5163 a horizontal separator line, or a list of fields for that line.
5164 PARAMS is a property list of parameters that can influence the
5165 conversion. All parameters from `orgtbl-to-generic' are
5166 supported. It is also possible to use the following ones:
5168 :ascii-art
5170 When non-nil, use \"ascii-art-to-unicode\" package to translate
5171 the table. You can download it here:
5172 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5174 :narrow
5176 When non-nil, narrow columns width than provided width cookie,
5177 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5178 (require 'ox-ascii)
5179 (orgtbl-to-generic
5180 table
5181 (org-combine-plists
5182 (list :backend 'ascii
5183 :ascii-charset 'utf-8
5184 :ascii-table-keep-all-vertical-lines (plist-get params :)
5185 :ascii-table-widen-columns (not (plist-get params :narrow))
5186 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5187 params)))
5189 ;; Put the cursor in a column containing numerical values
5190 ;; of an Org-Mode table,
5191 ;; type C-c " a
5192 ;; A new column is added with a bar plot.
5193 ;; When the table is refreshed (C-u C-c *),
5194 ;; the plot is updated to reflect the new values.
5196 (defun orgtbl-ascii-draw (value min max &optional width characters)
5197 "Draw an ascii bar in a table.
5198 VALUE is a the value to plot, the width of the bar to draw. A
5199 value equal to MIN will be displayed as empty (zero width bar).
5200 A value equal to MAX will draw a bar filling all the WIDTH.
5201 WIDTH is the expected width in characters of the column.
5202 CHARACTERS is a string that will compose the bar, with shades of
5203 grey from pure white to pure black. It defaults to a 10
5204 characters string of regular ascii characters."
5205 (let* ((characters (or characters " .:;c!lhVHW"))
5206 (width (or width 12))
5207 (value (if (numberp value) value (string-to-number value)))
5208 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5209 (cond
5210 ((< value 0) "too small")
5211 ((> value width) "too large")
5213 (let ((len (1- (length characters))))
5214 (concat
5215 (make-string (floor value) (elt characters len))
5216 (string (elt characters
5217 (floor (* (- value (floor value)) len))))))))))
5219 ;;;###autoload
5220 (defun orgtbl-ascii-plot (&optional ask)
5221 "Draw an ascii bar plot in a column.
5222 With cursor in a column containing numerical values, this
5223 function will draw a plot in a new column.
5224 ASK, if given, is a numeric prefix to override the default 12
5225 characters width of the plot. ASK may also be the
5226 \\[universal-argument] prefix, which will prompt for the width."
5227 (interactive "P")
5228 (let ((col (org-table-current-column))
5229 (min 1e999) ; 1e999 will be converted to infinity
5230 (max -1e999) ; which is the desired result
5231 (table (org-table-to-lisp))
5232 (length
5233 (cond ((consp ask)
5234 (read-number "Length of column " 12))
5235 ((numberp ask) ask)
5236 (t 12))))
5237 ;; Skip any hline a the top of table.
5238 (while (eq (car table) 'hline) (setq table (cdr table)))
5239 ;; Skip table header if any.
5240 (dolist (x (or (cdr (memq 'hline table)) table))
5241 (when (consp x)
5242 (setq x (nth (1- col) x))
5243 (when (string-match
5244 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5246 (setq x (string-to-number x))
5247 (when (> min x) (setq min x))
5248 (when (< max x) (setq max x)))))
5249 (org-table-insert-column)
5250 (org-table-move-column-right)
5251 (org-table-store-formulas
5252 (cons
5253 (cons
5254 (number-to-string (1+ col))
5255 (format "'(%s $%s %s %s %s)"
5256 "orgtbl-ascii-draw" col min max length))
5257 (org-table-get-stored-formulas)))
5258 (org-table-recalculate t)))
5260 ;; Example of extension: unicode characters
5261 ;; Here are two examples of different styles.
5263 ;; Unicode block characters are used to give a smooth effect.
5264 ;; See http://en.wikipedia.org/wiki/Block_Elements
5265 ;; Use one of those drawing functions
5266 ;; - orgtbl-ascii-draw (the default ascii)
5267 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5268 ;; - orgtbl-uc-draw-cont (smooth unicode)
5270 ;; This is best viewed with the "DejaVu Sans Mono" font
5271 ;; (use M-x set-default-font).
5273 (defun orgtbl-uc-draw-grid (value min max &optional width)
5274 "Draw a bar in a table using block unicode characters.
5275 It is a variant of orgtbl-ascii-draw with Unicode block
5276 characters, for a smooth display. Bars appear as grids (to the
5277 extent the font allows)."
5278 ;; http://en.wikipedia.org/wiki/Block_Elements
5279 ;; best viewed with the "DejaVu Sans Mono" font.
5280 (orgtbl-ascii-draw value min max width
5281 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5283 (defun orgtbl-uc-draw-cont (value min max &optional width)
5284 "Draw a bar in a table using block unicode characters.
5285 It is a variant of orgtbl-ascii-draw with Unicode block
5286 characters, for a smooth display. Bars are solid (to the extent
5287 the font allows)."
5288 (orgtbl-ascii-draw value min max width
5289 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5291 (defun org-table-get-remote-range (name-or-id form)
5292 "Get a field value or a list of values in a range from table at ID.
5294 NAME-OR-ID may be the name of a table in the current file as set
5295 by a \"#+NAME:\" directive. The first table following this line
5296 will then be used. Alternatively, it may be an ID referring to
5297 any entry, also in a different file. In this case, the first
5298 table in that entry will be referenced.
5299 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5300 \"@I$2..@II$2\". All the references must be absolute, not relative.
5302 The return value is either a single string for a single field, or a
5303 list of the fields in the rectangle."
5304 (save-match-data
5305 (let ((case-fold-search t) (id-loc nil)
5306 ;; Protect a bunch of variables from being overwritten
5307 ;; by the context of the remote table
5308 org-table-column-names org-table-column-name-regexp
5309 org-table-local-parameters org-table-named-field-locations
5310 org-table-current-line-types org-table-current-begin-line
5311 org-table-current-begin-pos org-table-dlines
5312 org-table-current-ncol
5313 org-table-hlines org-table-last-alignment
5314 org-table-last-column-widths org-table-last-alignment
5315 org-table-last-column-widths tbeg
5316 buffer loc)
5317 (setq form (org-table-convert-refs-to-rc form))
5318 (save-excursion
5319 (save-restriction
5320 (widen)
5321 (save-excursion
5322 (goto-char (point-min))
5323 (if (re-search-forward
5324 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5325 (regexp-quote name-or-id) "[ \t]*$")
5326 nil t)
5327 (setq buffer (current-buffer) loc (match-beginning 0))
5328 (setq id-loc (org-id-find name-or-id 'marker))
5329 (unless (and id-loc (markerp id-loc))
5330 (user-error "Can't find remote table \"%s\"" name-or-id))
5331 (setq buffer (marker-buffer id-loc)
5332 loc (marker-position id-loc))
5333 (move-marker id-loc nil)))
5334 (with-current-buffer buffer
5335 (save-excursion
5336 (save-restriction
5337 (widen)
5338 (goto-char loc)
5339 (forward-char 1)
5340 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5341 (not (match-beginning 1)))
5342 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5343 (setq tbeg (point-at-bol))
5344 (org-table-get-specials)
5345 (setq form (org-table-formula-substitute-names
5346 (org-table-formula-handle-first/last-rc form)))
5347 (if (and (string-match org-table-range-regexp form)
5348 (> (length (match-string 0 form)) 1))
5349 (save-match-data
5350 (org-table-get-range (match-string 0 form) tbeg 1))
5351 form)))))))))
5353 (defun org-table-remote-reference-indirection (form)
5354 "Return formula with table remote references substituted by indirection.
5355 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5356 This indirection works only with the format @ROW$COLUMN. The
5357 format \"B3\" is not supported because it can not be
5358 distinguished from a plain table name or ID."
5359 (let ((start 0))
5360 (while (string-match (concat
5361 ;; Same as in `org-table-eval-formula'.
5362 "\\<remote([ \t]*\\("
5363 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5364 "[@$][^ \t,]+"
5365 ;; Same as in `org-table-eval-formula'.
5366 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5367 form
5368 start)
5369 ;; The position of the character as far as possible to the right
5370 ;; that will not be replaced and particularly not be shifted by
5371 ;; `replace-match'.
5372 (setq start (match-beginning 1))
5373 ;; Substitute the remote reference with the value found in the
5374 ;; field.
5375 (setq form
5376 (replace-match
5377 (save-match-data
5378 (org-table-get-range (org-table-formula-handle-first/last-rc
5379 (match-string 1 form))))
5380 t t form 1))))
5381 form)
5383 (defmacro org-define-lookup-function (mode)
5384 (let ((mode-str (symbol-name mode))
5385 (first-p (equal mode 'first))
5386 (all-p (equal mode 'all)))
5387 (let ((plural-str (if all-p "s" "")))
5388 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5389 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5390 If R-LIST is nil, return matching element%s of S-LIST.
5391 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5392 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5393 This function is generated by a call to the macro `org-define-lookup-function'."
5394 mode-str plural-str plural-str plural-str)
5395 (let ,(let ((lvars '((p (or predicate 'equal))
5396 (sl s-list)
5397 (rl (or r-list s-list))
5398 (ret nil))))
5399 (if first-p (add-to-list 'lvars '(match-p nil)))
5400 lvars)
5401 (while ,(if first-p '(and (not match-p) sl) 'sl)
5402 (progn
5403 (if (funcall p val (car sl))
5404 (progn
5405 ,(if first-p '(setq match-p t))
5406 (let ((rval (car rl)))
5407 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5408 (setq sl (cdr sl) rl (cdr rl))))
5409 ret)))))
5411 (org-define-lookup-function first)
5412 (org-define-lookup-function last)
5413 (org-define-lookup-function all)
5415 (provide 'org-table)
5417 ;; Local variables:
5418 ;; generated-autoload-file: "org-loaddefs.el"
5419 ;; End:
5421 ;;; org-table.el ends here