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