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