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