Revert "ox-html.el (org-html-fontify-code): Possibly deactivate fci-mode"
[org-mode.git] / lisp / org-table.el
blob8a6e22b67fb8a65e42b4f76c1aab5e47dfe82b69
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
2794 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2795 (setq form
2796 (replace-match
2797 (save-match-data
2798 (org-table-make-reference
2799 (org-sublist
2800 fields (string-to-number (match-string 1 form))
2801 (string-to-number (match-string 2 form)))
2802 keep-empty numbers lispp))
2803 t t form)))
2804 (setq form0 form)
2805 ;; Insert the references to fields in same row
2806 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2807 (setq n (+ (string-to-number (match-string 1 form))
2808 (if (match-end 2) n0 0))
2809 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2810 formrpl (save-match-data
2811 (org-table-make-reference
2812 x keep-empty numbers lispp)))
2813 (when (or (not x)
2814 (save-match-data
2815 (string-match (regexp-quote formula) formrpl)))
2816 (user-error "Invalid field specifier \"%s\""
2817 (match-string 0 form)))
2818 (setq form (replace-match formrpl t t form)))
2820 (if lispp
2821 (setq ev (condition-case nil
2822 (eval (eval (read form)))
2823 (error "#ERROR"))
2824 ev (if (numberp ev) (number-to-string ev) ev)
2825 ev (if duration (org-table-time-seconds-to-string
2826 (string-to-number ev)
2827 duration-output-format) ev))
2828 (or (fboundp 'calc-eval)
2829 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2830 ;; Use <...> time-stamps so that Calc can handle them
2831 (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
2832 (setq form (replace-match "<\\1>" nil nil form)))
2833 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2834 (when (string-match org-ts-regexp2 form)
2835 (let* ((ts (match-string 0 form))
2836 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2837 (system-time-locale "C")
2838 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2839 (cdr org-time-stamp-formats))
2840 (car org-time-stamp-formats))))
2841 (setq form (replace-match (format-time-string tf tsp) t t form))))
2843 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2844 form
2845 (calc-eval (cons form org-tbl-calc-modes)
2846 (when (and (not keep-empty) numbers) 'num)))
2847 ev (if duration (org-table-time-seconds-to-string
2848 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2849 (string-to-number (org-table-time-string-to-seconds ev))
2850 (string-to-number ev))
2851 duration-output-format)
2852 ev)))
2854 (when org-table-formula-debug
2855 (with-output-to-temp-buffer "*Substitution History*"
2856 (princ (format "Substitution history of formula
2857 Orig: %s
2858 $xyz-> %s
2859 @r$c-> %s
2860 $1-> %s\n" orig formula form0 form))
2861 (if (consp ev)
2862 (princ (format " %s^\nError: %s"
2863 (make-string (car ev) ?\-) (nth 1 ev)))
2864 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2865 ev (or fmt "NONE")
2866 (if fmt (format fmt (string-to-number ev)) ev)))))
2867 (setq bw (get-buffer-window "*Substitution History*"))
2868 (org-fit-window-to-buffer bw)
2869 (unless (and (org-called-interactively-p 'any) (not ndown))
2870 (unless (let (inhibit-redisplay)
2871 (y-or-n-p "Debugging Formula. Continue to next? "))
2872 (org-table-align)
2873 (user-error "Abort"))
2874 (delete-window bw)
2875 (message "")))
2876 (when (consp ev) (setq fmt nil ev "#ERROR"))
2877 (org-table-justify-field-maybe
2878 (format org-table-formula-field-format
2879 (if fmt (format fmt (string-to-number ev)) ev)))
2880 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2881 (call-interactively 'org-return)
2882 (setq ndown 0)))
2883 (and down (org-table-maybe-recalculate-line))
2884 (or suppress-align (and org-table-may-need-update
2885 (org-table-align))))))
2887 (defun org-table-put-field-property (prop value)
2888 (save-excursion
2889 (put-text-property (progn (skip-chars-backward "^|") (point))
2890 (progn (skip-chars-forward "^|") (point))
2891 prop value)))
2893 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2894 "Get a calc vector from a column, according to descriptor DESC.
2895 Optional arguments TBEG and COL can give the beginning of the table and
2896 the current column, to avoid unnecessary parsing.
2898 HIGHLIGHT means just highlight the range.
2900 When CORNERS-ONLY is set, only return the corners of the range as
2901 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2902 in the buffer and column1 and column2 are table column numbers."
2903 (if (not (equal (string-to-char desc) ?@))
2904 (setq desc (concat "@" desc)))
2905 (save-excursion
2906 (or tbeg (setq tbeg (org-table-begin)))
2907 (or col (setq col (org-table-current-column)))
2908 (let ((thisline (org-current-line))
2909 beg end c1 c2 r1 r2 rangep tmp)
2910 (unless (string-match org-table-range-regexp desc)
2911 (user-error "Invalid table range specifier `%s'" desc))
2912 (setq rangep (match-end 3)
2913 r1 (and (match-end 1) (match-string 1 desc))
2914 r2 (and (match-end 4) (match-string 4 desc))
2915 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2916 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2918 (and c1 (setq c1 (+ (string-to-number c1)
2919 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2920 (and c2 (setq c2 (+ (string-to-number c2)
2921 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2922 (if (equal r1 "") (setq r1 nil))
2923 (if (equal r2 "") (setq r2 nil))
2924 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2925 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2926 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2927 (if (not r1) (setq r1 thisline))
2928 (if (not r2) (setq r2 thisline))
2929 (if (or (not c1) (= 0 c1)) (setq c1 col))
2930 (if (or (not c2) (= 0 c2)) (setq c2 col))
2931 (if (and (not corners-only)
2932 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2933 ;; just one field
2934 (progn
2935 (org-goto-line r1)
2936 (while (not (looking-at org-table-dataline-regexp))
2937 (beginning-of-line 2))
2938 (prog1 (org-trim (org-table-get-field c1))
2939 (if highlight (org-table-highlight-rectangle (point) (point)))))
2940 ;; A range, return a vector
2941 ;; First sort the numbers to get a regular rectangle
2942 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2943 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2944 (if corners-only
2945 ;; Only return the corners of the range
2946 (list r1 c1 r2 c2)
2947 ;; Copy the range values into a list
2948 (org-goto-line r1)
2949 (while (not (looking-at org-table-dataline-regexp))
2950 (beginning-of-line 2))
2951 (org-table-goto-column c1)
2952 (setq beg (point))
2953 (org-goto-line r2)
2954 (while (not (looking-at org-table-dataline-regexp))
2955 (beginning-of-line 0))
2956 (org-table-goto-column c2)
2957 (setq end (point))
2958 (if highlight
2959 (org-table-highlight-rectangle
2960 beg (progn (skip-chars-forward "^|\n") (point))))
2961 ;; return string representation of calc vector
2962 (mapcar 'org-trim
2963 (apply 'append (org-table-copy-region beg end))))))))
2965 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2966 "Analyze descriptor DESC and retrieve the corresponding line number.
2967 The cursor is currently in line CLINE, the table begins in line BLINE,
2968 and TABLE is a vector with line types."
2969 (if (string-match "^[0-9]+$" desc)
2970 (aref org-table-dlines (string-to-number desc))
2971 (setq cline (or cline (org-current-line))
2972 bline (or bline org-table-current-begin-line)
2973 table (or table org-table-current-line-types))
2974 (if (or
2975 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2976 ;; 1 2 3 4 5 6
2977 (and (not (match-end 3)) (not (match-end 6)))
2978 (and (match-end 3) (match-end 6) (not (match-end 5))))
2979 (user-error "Invalid row descriptor `%s'" desc))
2980 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2981 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2982 (odir (and (match-end 5) (match-string 5 desc)))
2983 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2984 (i (- cline bline))
2985 (rel (and (match-end 6)
2986 (or (and (match-end 1) (not (match-end 3)))
2987 (match-end 5)))))
2988 (if (and hn (not hdir))
2989 (progn
2990 (setq i 0 hdir "+")
2991 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2992 (if (and (not hn) on (not odir))
2993 (user-error "Should never happen");;(aref org-table-dlines on)
2994 (if (and hn (> hn 0))
2995 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2996 nil hn cline desc)))
2997 (if on
2998 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2999 rel on cline desc)))
3000 (+ bline i)))))
3002 (defun org-table-find-row-type (table i type backwards relative n cline desc)
3003 "FIXME: Needs more documentation."
3004 (let ((l (length table)))
3005 (while (> n 0)
3006 (while (and (setq i (+ i (if backwards -1 1)))
3007 (>= i 0) (< i l)
3008 (not (eq (aref table i) type))
3009 (if (and relative (eq (aref table i) 'hline))
3010 (cond
3011 ((eq org-table-relative-ref-may-cross-hline t) t)
3012 ((eq org-table-relative-ref-may-cross-hline 'error)
3013 (user-error "Row descriptor %s used in line %d crosses hline" desc cline))
3014 (t (setq i (- i (if backwards -1 1))
3015 n 1)
3016 nil))
3017 t)))
3018 (setq n (1- n)))
3019 (cond ((or (< i 0) (>= i l))
3020 (user-error "Row descriptor %s used in line %d leads outside table"
3021 desc cline))
3022 ;; The last hline doesn't exist. Instead, point to last row
3023 ;; in table.
3024 ((= i (1- l)) (1- i))
3025 (t i))))
3027 (defun org-table--error-on-old-row-references (s)
3028 (when (string-match "&[-+0-9I]" s)
3029 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3031 (defun org-table-make-reference (elements keep-empty numbers lispp)
3032 "Convert list ELEMENTS to something appropriate to insert into formula.
3033 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3034 NUMBERS indicates that everything should be converted to numbers.
3035 LISPP non-nil means to return something appropriate for a Lisp
3036 list, 'literal is for the format specifier L."
3037 ;; Calc nan (not a number) is used for the conversion of the empty
3038 ;; field to a reference for several reasons: (i) It is accepted in a
3039 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3040 ;; (ii) In a single field (not in range) it can be distinguished
3041 ;; from "(nan)" which is the reference made from a single field
3042 ;; containing "nan".
3043 (if (stringp elements)
3044 ;; field reference
3045 (if lispp
3046 (if (eq lispp 'literal)
3047 elements
3048 (if (and (eq elements "") (not keep-empty))
3050 (prin1-to-string
3051 (if numbers (string-to-number elements) elements))))
3052 (if (string-match "\\S-" elements)
3053 (progn
3054 (when numbers (setq elements (number-to-string
3055 (string-to-number elements))))
3056 (concat "(" elements ")"))
3057 (if (or (not keep-empty) numbers) "(0)" "nan")))
3058 ;; range reference
3059 (unless keep-empty
3060 (setq elements
3061 (delq nil
3062 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
3063 elements))))
3064 (setq elements (or elements '())) ; if delq returns nil then we need '()
3065 (if lispp
3066 (mapconcat
3067 (lambda (x)
3068 (if (eq lispp 'literal)
3070 (prin1-to-string (if numbers (string-to-number x) x))))
3071 elements " ")
3072 (concat "[" (mapconcat
3073 (lambda (x)
3074 (if (string-match "\\S-" x)
3075 (if numbers
3076 (number-to-string (string-to-number x))
3078 (if (or (not keep-empty) numbers) "0" "nan")))
3079 elements
3080 ",") "]"))))
3082 (defun org-table-message-once-per-second (t1 &rest args)
3083 "If there has been more than one second since T1, display message.
3084 ARGS are passed as arguments to the `message' function. Returns
3085 current time if a message is printed, otherwise returns T1. If
3086 T1 is nil, always messages."
3087 (let ((curtime (current-time)))
3088 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3089 (progn (apply 'message args)
3090 curtime)
3091 t1)))
3093 ;;;###autoload
3094 (defun org-table-recalculate (&optional all noalign)
3095 "Recalculate the current table line by applying all stored formulas.
3096 With prefix arg ALL, do this for all lines in the table.
3097 With the prefix argument ALL is `(16)' \
3098 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3099 it is the symbol `iterate', recompute the table until it no longer changes.
3100 If NOALIGN is not nil, do not re-align the table after the computations
3101 are done. This is typically used internally to save time, if it is
3102 known that the table will be realigned a little later anyway."
3103 (interactive "P")
3104 (or (memq this-command org-recalc-commands)
3105 (setq org-recalc-commands (cons this-command org-recalc-commands)))
3106 (unless (org-at-table-p) (user-error "Not at a table"))
3107 (if (or (eq all 'iterate) (equal all '(16)))
3108 (org-table-iterate)
3109 (org-table-get-specials)
3110 (let* ((eqlist (sort (org-table-get-stored-formulas)
3111 (lambda (a b) (string< (car a) (car b)))))
3112 (eqlist1 (copy-sequence eqlist))
3113 (inhibit-redisplay (not debug-on-error))
3114 (line-re org-table-dataline-regexp)
3115 (thisline (org-current-line))
3116 (thiscol (org-table-current-column))
3117 (log-first-time (current-time))
3118 (log-last-time log-first-time)
3119 seen-fields lhs1
3120 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
3121 ;; Insert constants in all formulas
3122 (when eqlist
3123 (setq eqlist
3124 (mapcar
3125 (lambda (x)
3126 (if (string-match "^@-?I+" (car x))
3127 (user-error "Can't assign to hline relative reference"))
3128 (when (string-match "\\`$[<>]" (car x))
3129 (setq lhs1 (car x))
3130 (setq x (cons (substring
3131 (org-table-formula-handle-first/last-rc
3132 (car x)) 1)
3133 (cdr x)))
3134 (if (assoc (car x) eqlist1)
3135 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3136 lhs1 (car x))))
3137 (cons
3138 (org-table-formula-handle-first/last-rc (car x))
3139 (org-table-formula-substitute-names
3140 (org-table-formula-handle-first/last-rc (cdr x)))))
3141 eqlist))
3142 ;; Split the equation list
3143 (while (setq eq (pop eqlist))
3144 (if (<= (string-to-char (car eq)) ?9)
3145 (push eq eqlnum)
3146 (push eq eqlname)))
3147 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
3148 ;; Expand ranges in lhs of formulas
3149 (setq eqlname (org-table-expand-lhs-ranges eqlname))
3151 ;; Get the correct line range to process
3152 (if all
3153 (progn
3154 (setq end (copy-marker (1+ (org-table-end))))
3155 (goto-char (setq beg (org-table-begin)))
3156 (if (re-search-forward org-table-calculate-mark-regexp end t)
3157 ;; This is a table with marked lines, compute selected lines
3158 (setq line-re org-table-recalculate-regexp)
3159 ;; Move forward to the first non-header line
3160 (if (and (re-search-forward org-table-dataline-regexp end t)
3161 (re-search-forward org-table-hline-regexp end t)
3162 (re-search-forward org-table-dataline-regexp end t))
3163 (setq beg (match-beginning 0))
3164 nil))) ;; just leave beg where it is
3165 (setq beg (point-at-bol)
3166 end (move-marker (make-marker) (1+ (point-at-eol)))))
3167 (goto-char beg)
3169 ;; First find the named fields, and mark them untouchable.
3170 ;; Also check if several field/range formulas try to set the same field.
3171 (remove-text-properties beg end '(org-untouchable t))
3172 (while (setq eq (pop eqlname))
3173 (setq name (car eq)
3174 a (assoc name org-table-named-field-locations))
3175 (setq name1 name)
3176 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
3177 (nth 2 a))))
3178 (when (member name1 seen-fields)
3179 (user-error "Several field/range formulas try to set %s" name1))
3180 (push name1 seen-fields)
3182 (and (not a)
3183 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
3184 (setq a (list name
3185 (condition-case nil
3186 (aref org-table-dlines
3187 (string-to-number (match-string 1 name)))
3188 (error (user-error "Invalid row number in %s"
3189 name)))
3190 (string-to-number (match-string 2 name)))))
3191 (when (and a (or all (equal (nth 1 a) thisline)))
3192 (setq log-last-time
3193 (org-table-message-once-per-second
3194 (and all log-last-time)
3195 "Re-applying formula to field: %s" name))
3196 (org-goto-line (nth 1 a))
3197 (org-table-goto-column (nth 2 a))
3198 (push (append a (list (cdr eq))) eqlname1)
3199 (org-table-put-field-property :org-untouchable t)))
3200 (setq eqlname1 (nreverse eqlname1))
3202 ;; Now evaluate the column formulas, but skip fields covered
3203 ;; by field formulas
3204 (goto-char beg)
3205 (while (re-search-forward line-re end t)
3206 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3207 ;; Unprotected line, recalculate
3208 (setq cnt (1+ cnt))
3209 (and all (setq log-last-time
3210 (org-table-message-once-per-second
3211 log-last-time
3212 "Re-applying formulas to full table...(line %d)" cnt)))
3213 (setq org-last-recalc-line (org-current-line))
3214 (setq eql eqlnum)
3215 (while (setq entry (pop eql))
3216 (org-goto-line org-last-recalc-line)
3217 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3218 (unless (get-text-property (point) :org-untouchable)
3219 (org-table-eval-formula
3220 nil (cdr entry)
3221 'noalign 'nocst 'nostore 'noanalysis)))))
3223 ;; Now evaluate the field formulas
3224 (while (setq eq (pop eqlname1))
3225 (setq log-last-time
3226 (org-table-message-once-per-second
3227 (and all log-last-time)
3228 "Re-applying formula to field: %s" (car eq)))
3229 (org-goto-line (nth 1 eq))
3230 (let ((column-target (nth 2 eq)))
3231 (when (> column-target 1000)
3232 (user-error "Formula column target too large"))
3233 (let* ((column-count (progn (end-of-line)
3234 (1- (org-table-current-column))))
3235 (create-new-column
3236 (and (> column-target column-count)
3237 (or (eq org-table-formula-create-columns t)
3238 (and
3239 (eq org-table-formula-create-columns 'warn)
3240 (progn
3241 (org-display-warning
3242 "Out-of-bounds formula added columns")
3244 (and
3245 (eq org-table-formula-create-columns 'prompt)
3246 (yes-or-no-p
3247 "Out-of-bounds formula. Add columns?"))))))
3248 (org-table-goto-column column-target nil create-new-column))
3250 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
3251 'nostore 'noanalysis)))
3253 (org-goto-line thisline)
3254 (org-table-goto-column thiscol)
3255 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3256 (or noalign (and org-table-may-need-update (org-table-align))
3257 (and all (org-table-message-once-per-second
3258 log-first-time
3259 "Re-applying formulas to %d lines...done" cnt)))
3262 ;; back to initial position
3263 (org-table-message-once-per-second
3264 (and all log-first-time)
3265 "Re-applying formulas...done")
3267 (org-goto-line thisline)
3268 (org-table-goto-column thiscol)
3269 (or noalign (and org-table-may-need-update (org-table-align)))))))
3271 ;;;###autoload
3272 (defun org-table-iterate (&optional arg)
3273 "Recalculate the table until it does not change anymore.
3274 The maximum number of iterations is 10, but you can choose a different value
3275 with the prefix ARG."
3276 (interactive "P")
3277 (let ((imax (if arg (prefix-numeric-value arg) 10))
3278 (i 0)
3279 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3280 thistbl)
3281 (catch 'exit
3282 (while (< i imax)
3283 (setq i (1+ i))
3284 (org-table-recalculate 'all)
3285 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3286 (if (not (string= lasttbl thistbl))
3287 (setq lasttbl thistbl)
3288 (if (> i 1)
3289 (message "Convergence after %d iterations" i)
3290 (message "Table was already stable"))
3291 (throw 'exit t)))
3292 (user-error "No convergence after %d iterations" i))))
3294 ;;;###autoload
3295 (defun org-table-recalculate-buffer-tables ()
3296 "Recalculate all tables in the current buffer."
3297 (interactive)
3298 (save-excursion
3299 (save-restriction
3300 (widen)
3301 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3303 ;;;###autoload
3304 (defun org-table-iterate-buffer-tables ()
3305 "Iterate all tables in the buffer, to converge inter-table dependencies."
3306 (interactive)
3307 (let* ((imax 10)
3308 (i imax)
3309 (checksum (md5 (buffer-string)))
3311 (save-excursion
3312 (save-restriction
3313 (widen)
3314 (catch 'exit
3315 (while (> i 0)
3316 (setq i (1- i))
3317 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3318 (if (equal checksum (setq c1 (md5 (buffer-string))))
3319 (progn
3320 (message "Convergence after %d iterations" (- imax i))
3321 (throw 'exit t))
3322 (setq checksum c1)))
3323 (user-error "No convergence after %d iterations" imax))))))
3325 (defun org-table-calc-current-TBLFM (&optional arg)
3326 "Apply the #+TBLFM in the line at point to the table."
3327 (interactive "P")
3328 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3329 (let ((formula (buffer-substring
3330 (line-beginning-position)
3331 (line-end-position))))
3332 (save-excursion
3333 ;; Insert a temporary formula at right after the table
3334 (goto-char (org-table-TBLFM-begin))
3335 (let ((s (point-marker)))
3336 (insert formula "\n")
3337 (let ((e (point-marker)))
3338 ;; Recalculate the table.
3339 (beginning-of-line 0) ; move to the inserted line
3340 (skip-chars-backward " \r\n\t")
3341 (unwind-protect
3342 (org-call-with-arg #'org-table-recalculate (or arg t))
3343 ;; Delete the formula inserted temporarily.
3344 (delete-region s e)
3345 (set-marker s nil)
3346 (set-marker e nil)))))))
3348 (defun org-table-TBLFM-begin ()
3349 "Find the beginning of the TBLFM lines and return its position.
3350 Return nil when the beginning of TBLFM line was not found."
3351 (save-excursion
3352 (when (progn (forward-line 1)
3353 (re-search-backward org-table-TBLFM-begin-regexp nil t))
3354 (line-beginning-position 2))))
3356 (defun org-table-expand-lhs-ranges (equations)
3357 "Expand list of formulas.
3358 If some of the RHS in the formulas are ranges or a row reference, expand
3359 them to individual field equations for each field."
3360 (let (e res lhs rhs range r1 r2 c1 c2)
3361 (while (setq e (pop equations))
3362 (setq lhs (car e) rhs (cdr e))
3363 (cond
3364 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3365 ;; This just refers to one fixed field
3366 (push e res))
3367 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3368 ;; This just refers to one fixed named field
3369 (push e res))
3370 ((string-match "^@[0-9]+$" lhs)
3371 (loop for ic from 1 to org-table-current-ncol do
3372 (push (cons (format "%s$%d" lhs ic) rhs) res)
3373 (put-text-property 0 (length (caar res))
3374 :orig-eqn e (caar res))))
3376 (setq range (org-table-get-range lhs org-table-current-begin-pos
3377 1 nil 'corners))
3378 (setq r1 (nth 0 range) c1 (nth 1 range)
3379 r2 (nth 2 range) c2 (nth 3 range))
3380 (setq r1 (org-table-line-to-dline r1))
3381 (setq r2 (org-table-line-to-dline r2 'above))
3382 (loop for ir from r1 to r2 do
3383 (loop for ic from c1 to c2 do
3384 (push (cons (format "@%d$%d" ir ic) rhs) res)
3385 (put-text-property 0 (length (caar res))
3386 :orig-eqn e (caar res)))))))
3387 (nreverse res)))
3389 (defun org-table-formula-handle-first/last-rc (s)
3390 "Replace @<, @>, $<, $> with first/last row/column of the table.
3391 So @< and $< will always be replaced with @1 and $1, respectively.
3392 The advantage of these special markers are that structure editing of
3393 the table will not change them, while @1 and $1 will be modified
3394 when a line/row is swapped out of that privileged position. So for
3395 formulas that use a range of rows or columns, it may often be better
3396 to anchor the formula with \"I\" row markers, or to offset from the
3397 borders of the table using the @< @> $< $> makers."
3398 (let (n nmax len char (start 0))
3399 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3400 s start)
3401 (if (match-end 3)
3402 (setq start (match-end 3))
3403 (setq nmax (if (equal (match-string 1 s) "@")
3404 (1- (length org-table-dlines))
3405 org-table-current-ncol)
3406 len (- (match-end 2) (match-beginning 2))
3407 char (string-to-char (match-string 2 s))
3408 n (if (= char ?<)
3410 (- nmax len -1)))
3411 (if (or (< n 1) (> n nmax))
3412 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3413 (match-string 0 s) s))
3414 (setq start (match-beginning 0))
3415 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3418 (defun org-table-formula-substitute-names (f)
3419 "Replace $const with values in string F."
3420 (let ((start 0)
3421 (pp (/= (string-to-char f) ?'))
3422 (duration (org-string-match-p ";.*[Tt].*\\'" f))
3423 (new (replace-regexp-in-string ; Check for column names.
3424 org-table-column-name-regexp
3425 (lambda (m)
3426 (concat "$" (cdr (assoc (match-string 1 m)
3427 org-table-column-names))))
3428 f t t)))
3429 ;; Parameters and constants.
3430 (while (setq start
3431 (string-match
3432 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3433 new start))
3434 (if (match-end 2) (setq start (match-end 2))
3435 (incf start)
3436 ;; When a duration is expected, convert value on the fly.
3437 (let ((value
3438 (save-match-data
3439 (let ((v (org-table-get-constant (match-string 1 new))))
3440 (if (and (org-string-nw-p v) duration)
3441 (org-table-time-string-to-seconds v)
3442 v)))))
3443 (when value
3444 (setq new (replace-match
3445 (concat (and pp "(") value (and pp ")")) t t new))))))
3446 (if org-table-formula-debug (org-propertize new :orig-formula f)) new))
3448 (defun org-table-get-constant (const)
3449 "Find the value for a parameter or constant in a formula.
3450 Parameters get priority."
3451 (or (cdr (assoc const org-table-local-parameters))
3452 (cdr (assoc const org-table-formula-constants-local))
3453 (cdr (assoc const org-table-formula-constants))
3454 (and (fboundp 'constants-get) (constants-get const))
3455 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3456 (org-entry-get nil (substring const 5) 'inherit))
3457 "#UNDEFINED_NAME"))
3459 (defvar org-table-fedit-map
3460 (let ((map (make-sparse-keymap)))
3461 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3462 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3463 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3464 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3465 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3466 (org-defkey map "\C-c?" 'org-table-show-reference)
3467 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3468 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3469 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3470 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3471 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3472 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3473 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3474 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3475 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3476 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3477 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3478 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3479 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3480 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3481 map))
3483 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3484 '("Edit-Formulas"
3485 ["Finish and Install" org-table-fedit-finish t]
3486 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3487 ["Abort" org-table-fedit-abort t]
3488 "--"
3489 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3490 ["Complete Lisp Symbol" lisp-complete-symbol t]
3491 "--"
3492 "Shift Reference at Point"
3493 ["Up" org-table-fedit-ref-up t]
3494 ["Down" org-table-fedit-ref-down t]
3495 ["Left" org-table-fedit-ref-left t]
3496 ["Right" org-table-fedit-ref-right t]
3498 "Change Test Row for Column Formulas"
3499 ["Up" org-table-fedit-line-up t]
3500 ["Down" org-table-fedit-line-down t]
3501 "--"
3502 ["Scroll Table Window" org-table-fedit-scroll t]
3503 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3504 ["Show Table Grid" org-table-fedit-toggle-coordinates
3505 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3506 org-table-overlay-coordinates)]
3507 "--"
3508 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3509 :style toggle :selected org-table-buffer-is-an]))
3511 (defvar org-pos)
3513 ;;;###autoload
3514 (defun org-table-edit-formulas ()
3515 "Edit the formulas of the current table in a separate buffer."
3516 (interactive)
3517 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3518 (beginning-of-line 0))
3519 (unless (org-at-table-p) (user-error "Not at a table"))
3520 (org-table-get-specials)
3521 (let ((key (org-table-current-field-formula 'key 'noerror))
3522 (eql (sort (org-table-get-stored-formulas 'noerror)
3523 'org-table-formula-less-p))
3524 (pos (point-marker))
3525 (startline 1)
3526 (wc (current-window-configuration))
3527 (sel-win (selected-window))
3528 (titles '((column . "# Column Formulas\n")
3529 (field . "# Field and Range Formulas\n")
3530 (named . "# Named Field Formulas\n")))
3531 entry s type title)
3532 (org-switch-to-buffer-other-window "*Edit Formulas*")
3533 (erase-buffer)
3534 ;; Keep global-font-lock-mode from turning on font-lock-mode
3535 (let ((font-lock-global-modes '(not fundamental-mode)))
3536 (fundamental-mode))
3537 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3538 (org-set-local 'org-pos pos)
3539 (org-set-local 'org-window-configuration wc)
3540 (org-set-local 'org-selected-window sel-win)
3541 (use-local-map org-table-fedit-map)
3542 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3543 (easy-menu-add org-table-fedit-menu)
3544 (setq startline (org-current-line))
3545 (while (setq entry (pop eql))
3546 (setq type (cond
3547 ((string-match "\\`$[<>]" (car entry)) 'column)
3548 ((equal (string-to-char (car entry)) ?@) 'field)
3549 ((string-match "^[0-9]" (car entry)) 'column)
3550 (t 'named)))
3551 (when (setq title (assq type titles))
3552 (or (bobp) (insert "\n"))
3553 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3554 (setq titles (remove title titles)))
3555 (if (equal key (car entry)) (setq startline (org-current-line)))
3556 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3557 (car entry) " = " (cdr entry) "\n"))
3558 (remove-text-properties 0 (length s) '(face nil) s)
3559 (insert s))
3560 (if (eq org-table-use-standard-references t)
3561 (org-table-fedit-toggle-ref-type))
3562 (org-goto-line startline)
3563 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3565 (defun org-table-fedit-post-command ()
3566 (when (not (memq this-command '(lisp-complete-symbol)))
3567 (let ((win (selected-window)))
3568 (save-excursion
3569 (condition-case nil
3570 (org-table-show-reference)
3571 (error nil))
3572 (select-window win)))))
3574 (defun org-table-formula-to-user (s)
3575 "Convert a formula from internal to user representation."
3576 (if (eq org-table-use-standard-references t)
3577 (org-table-convert-refs-to-an s)
3580 (defun org-table-formula-from-user (s)
3581 "Convert a formula from user to internal representation."
3582 (if org-table-use-standard-references
3583 (org-table-convert-refs-to-rc s)
3586 (defun org-table-convert-refs-to-rc (s)
3587 "Convert spreadsheet references from A7 to @7$28.
3588 Works for single references, but also for entire formulas and even the
3589 full TBLFM line."
3590 (let ((start 0))
3591 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3592 (cond
3593 ((match-end 3)
3594 ;; format match, just advance
3595 (setq start (match-end 0)))
3596 ((and (> (match-beginning 0) 0)
3597 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3598 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3599 ;; 3.e5 or something like this.
3600 (setq start (match-end 0)))
3601 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3602 ;; (member (match-string 1 s)
3603 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3605 ;; function name, just advance
3606 (setq start (match-end 0)))
3608 (setq start (match-beginning 0)
3609 s (replace-match
3610 (if (equal (match-string 2 s) "&")
3611 (format "$%d" (org-letters-to-number (match-string 1 s)))
3612 (format "@%d$%d"
3613 (string-to-number (match-string 2 s))
3614 (org-letters-to-number (match-string 1 s))))
3615 t t s)))))
3618 (defun org-table-convert-refs-to-an (s)
3619 "Convert spreadsheet references from to @7$28 to AB7.
3620 Works for single references, but also for entire formulas and even the
3621 full TBLFM line."
3622 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3623 (setq s (replace-match
3624 (format "%s%d"
3625 (org-number-to-letters
3626 (string-to-number (match-string 2 s)))
3627 (string-to-number (match-string 1 s)))
3628 t t s)))
3629 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3630 (setq s (replace-match (concat "\\1"
3631 (org-number-to-letters
3632 (string-to-number (match-string 2 s))) "&")
3633 t nil s)))
3636 (defun org-letters-to-number (s)
3637 "Convert a base 26 number represented by letters into an integer.
3638 For example: AB -> 28."
3639 (let ((n 0))
3640 (setq s (upcase s))
3641 (while (> (length s) 0)
3642 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3643 s (substring s 1)))
3646 (defun org-number-to-letters (n)
3647 "Convert an integer into a base 26 number represented by letters.
3648 For example: 28 -> AB."
3649 (let ((s ""))
3650 (while (> n 0)
3651 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3652 n (/ (1- n) 26)))
3655 (defun org-table-time-string-to-seconds (s)
3656 "Convert a time string into numerical duration in seconds.
3657 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3658 If S is a string representing a number, keep this number."
3659 (if (equal s "")
3661 (let (hour minus min sec res)
3662 (cond
3663 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3664 (setq minus (< 0 (length (match-string 1 s)))
3665 hour (string-to-number (match-string 2 s))
3666 min (string-to-number (match-string 3 s))
3667 sec (string-to-number (match-string 4 s)))
3668 (if minus
3669 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3670 (setq res (+ (* hour 3600) (* min 60) sec))))
3671 ((and (not (string-match org-ts-regexp-both s))
3672 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3673 (setq minus (< 0 (length (match-string 1 s)))
3674 hour (string-to-number (match-string 2 s))
3675 min (string-to-number (match-string 3 s)))
3676 (if minus
3677 (setq res (- (+ (* hour 3600) (* min 60))))
3678 (setq res (+ (* hour 3600) (* min 60)))))
3679 (t (setq res (string-to-number s))))
3680 (number-to-string res))))
3682 (defun org-table-time-seconds-to-string (secs &optional output-format)
3683 "Convert a number of seconds to a time string.
3684 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3685 minutes or seconds."
3686 (let* ((secs0 (abs secs))
3687 (res
3688 (cond ((eq output-format 'days)
3689 (format "%.3f" (/ (float secs0) 86400)))
3690 ((eq output-format 'hours)
3691 (format "%.2f" (/ (float secs0) 3600)))
3692 ((eq output-format 'minutes)
3693 (format "%.1f" (/ (float secs0) 60)))
3694 ((eq output-format 'seconds)
3695 (format "%d" secs0))
3696 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3697 (if (< secs 0) (concat "-" res) res)))
3699 (defun org-table-fedit-convert-buffer (function)
3700 "Convert all references in this buffer, using FUNCTION."
3701 (let ((line (org-current-line)))
3702 (goto-char (point-min))
3703 (while (not (eobp))
3704 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3705 (delete-region (point) (point-at-eol))
3706 (or (eobp) (forward-char 1)))
3707 (org-goto-line line)))
3709 (defun org-table-fedit-toggle-ref-type ()
3710 "Convert all references in the buffer from B3 to @3$2 and back."
3711 (interactive)
3712 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3713 (org-table-fedit-convert-buffer
3714 (if org-table-buffer-is-an
3715 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3716 (message "Reference type switched to %s"
3717 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3719 (defun org-table-fedit-ref-up ()
3720 "Shift the reference at point one row/hline up."
3721 (interactive)
3722 (org-table-fedit-shift-reference 'up))
3723 (defun org-table-fedit-ref-down ()
3724 "Shift the reference at point one row/hline down."
3725 (interactive)
3726 (org-table-fedit-shift-reference 'down))
3727 (defun org-table-fedit-ref-left ()
3728 "Shift the reference at point one field to the left."
3729 (interactive)
3730 (org-table-fedit-shift-reference 'left))
3731 (defun org-table-fedit-ref-right ()
3732 "Shift the reference at point one field to the right."
3733 (interactive)
3734 (org-table-fedit-shift-reference 'right))
3736 (defun org-table-fedit-shift-reference (dir)
3737 (cond
3738 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3739 (if (memq dir '(left right))
3740 (org-rematch-and-replace 1 (eq dir 'left))
3741 (user-error "Cannot shift reference in this direction")))
3742 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3743 ;; A B3-like reference
3744 (if (memq dir '(up down))
3745 (org-rematch-and-replace 2 (eq dir 'up))
3746 (org-rematch-and-replace 1 (eq dir 'left))))
3747 ((org-in-regexp
3748 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3749 ;; An internal reference
3750 (if (memq dir '(up down))
3751 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3752 (org-rematch-and-replace 5 (eq dir 'left))))))
3754 (defun org-rematch-and-replace (n &optional decr hline)
3755 "Re-match the group N, and replace it with the shifted reference."
3756 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3757 (goto-char (match-beginning n))
3758 (and (looking-at (regexp-quote (match-string n)))
3759 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3760 t t)))
3762 (defun org-table-shift-refpart (ref &optional decr hline)
3763 "Shift a reference part REF.
3764 If DECR is set, decrease the references row/column, else increase.
3765 If HLINE is set, this may be a hline reference, it certainly is not
3766 a translation reference."
3767 (save-match-data
3768 (let* ((sign (string-match "^[-+]" ref)) n)
3770 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3771 (cond
3772 ((and hline (string-match "^I+" ref))
3773 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3774 (setq n (+ n (if decr -1 1)))
3775 (if (= n 0) (setq n (+ n (if decr -1 1))))
3776 (if sign
3777 (setq sign (if (< n 0) "-" "+") n (abs n))
3778 (setq n (max 1 n)))
3779 (concat sign (make-string n ?I)))
3781 ((string-match "^[0-9]+" ref)
3782 (setq n (string-to-number (concat sign ref)))
3783 (setq n (+ n (if decr -1 1)))
3784 (if sign
3785 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3786 (number-to-string (max 1 n))))
3788 ((string-match "^[a-zA-Z]+" ref)
3789 (org-number-to-letters
3790 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3792 (t (user-error "Cannot shift reference"))))))
3794 (defun org-table-fedit-toggle-coordinates ()
3795 "Toggle the display of coordinates in the referenced table."
3796 (interactive)
3797 (let ((pos (marker-position org-pos)))
3798 (with-current-buffer (marker-buffer org-pos)
3799 (save-excursion
3800 (goto-char pos)
3801 (org-table-toggle-coordinate-overlays)))))
3803 (defun org-table-fedit-finish (&optional arg)
3804 "Parse the buffer for formula definitions and install them.
3805 With prefix ARG, apply the new formulas to the table."
3806 (interactive "P")
3807 (org-table-remove-rectangle-highlight)
3808 (if org-table-use-standard-references
3809 (progn
3810 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3811 (setq org-table-buffer-is-an nil)))
3812 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3813 (goto-char (point-min))
3814 (while (re-search-forward
3815 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3816 nil t)
3817 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3818 form (match-string 3))
3819 (setq form (org-trim form))
3820 (when (not (equal form ""))
3821 (while (string-match "[ \t]*\n[ \t]*" form)
3822 (setq form (replace-match " " t t form)))
3823 (when (assoc var eql)
3824 (user-error "Double formulas for %s" var))
3825 (push (cons var form) eql)))
3826 (setq org-pos nil)
3827 (set-window-configuration org-window-configuration)
3828 (select-window sel-win)
3829 (goto-char pos)
3830 (unless (org-at-table-p)
3831 (user-error "Lost table position - cannot install formulas"))
3832 (org-table-store-formulas eql)
3833 (move-marker pos nil)
3834 (kill-buffer "*Edit Formulas*")
3835 (if arg
3836 (org-table-recalculate 'all)
3837 (message "New formulas installed - press C-u C-c C-c to apply."))))
3839 (defun org-table-fedit-abort ()
3840 "Abort editing formulas, without installing the changes."
3841 (interactive)
3842 (org-table-remove-rectangle-highlight)
3843 (let ((pos org-pos) (sel-win org-selected-window))
3844 (set-window-configuration org-window-configuration)
3845 (select-window sel-win)
3846 (goto-char pos)
3847 (move-marker pos nil)
3848 (message "Formula editing aborted without installing changes")))
3850 (defun org-table-fedit-lisp-indent ()
3851 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3852 (interactive)
3853 (let ((pos (point)) beg end ind)
3854 (beginning-of-line 1)
3855 (cond
3856 ((looking-at "[ \t]")
3857 (goto-char pos)
3858 (call-interactively 'lisp-indent-line))
3859 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3860 ((not (fboundp 'pp-buffer))
3861 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3862 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3863 (goto-char (- (match-end 0) 2))
3864 (setq beg (point))
3865 (setq ind (make-string (current-column) ?\ ))
3866 (condition-case nil (forward-sexp 1)
3867 (error
3868 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3869 (setq end (point))
3870 (save-restriction
3871 (narrow-to-region beg end)
3872 (if (eq last-command this-command)
3873 (progn
3874 (goto-char (point-min))
3875 (setq this-command nil)
3876 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3877 (replace-match " ")))
3878 (pp-buffer)
3879 (untabify (point-min) (point-max))
3880 (goto-char (1+ (point-min)))
3881 (while (re-search-forward "^." nil t)
3882 (beginning-of-line 1)
3883 (insert ind))
3884 (goto-char (point-max))
3885 (org-delete-backward-char 1)))
3886 (goto-char beg))
3887 (t nil))))
3889 (defvar org-show-positions nil)
3891 (defun org-table-show-reference (&optional local)
3892 "Show the location/value of the $ expression at point."
3893 (interactive)
3894 (org-table-remove-rectangle-highlight)
3895 (catch 'exit
3896 (let ((pos (if local (point) org-pos))
3897 (face2 'highlight)
3898 (org-inhibit-highlight-removal t)
3899 (win (selected-window))
3900 (org-show-positions nil)
3901 var name e what match dest)
3902 (if local (org-table-get-specials))
3903 (setq what (cond
3904 ((org-in-regexp "^@[0-9]+[ \t=]")
3905 (setq match (concat (substring (match-string 0) 0 -1)
3906 "$1.."
3907 (substring (match-string 0) 0 -1)
3908 "$100"))
3909 'range)
3910 ((or (org-in-regexp org-table-range-regexp2)
3911 (org-in-regexp org-table-translate-regexp)
3912 (org-in-regexp org-table-range-regexp))
3913 (setq match
3914 (save-match-data
3915 (org-table-convert-refs-to-rc (match-string 0))))
3916 'range)
3917 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3918 ((org-in-regexp "\\$[0-9]+") 'column)
3919 ((not local) nil)
3920 (t (user-error "No reference at point")))
3921 match (and what (or match (match-string 0))))
3922 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3923 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3924 'secondary-selection))
3925 (org-add-hook 'before-change-functions
3926 'org-table-remove-rectangle-highlight)
3927 (if (eq what 'name) (setq var (substring match 1)))
3928 (when (eq what 'range)
3929 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3930 (setq match (org-table-formula-substitute-names match)))
3931 (unless local
3932 (save-excursion
3933 (end-of-line 1)
3934 (re-search-backward "^\\S-" nil t)
3935 (beginning-of-line 1)
3936 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3937 (setq dest
3938 (save-match-data
3939 (org-table-convert-refs-to-rc (match-string 1))))
3940 (org-table-add-rectangle-overlay
3941 (match-beginning 1) (match-end 1) face2))))
3942 (if (and (markerp pos) (marker-buffer pos))
3943 (if (get-buffer-window (marker-buffer pos))
3944 (select-window (get-buffer-window (marker-buffer pos)))
3945 (org-switch-to-buffer-other-window (get-buffer-window
3946 (marker-buffer pos)))))
3947 (goto-char pos)
3948 (org-table-force-dataline)
3949 (when dest
3950 (setq name (substring dest 1))
3951 (cond
3952 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3953 (setq e (assoc name org-table-named-field-locations))
3954 (org-goto-line (nth 1 e))
3955 (org-table-goto-column (nth 2 e)))
3956 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3957 (let ((l (string-to-number (match-string 1 dest)))
3958 (c (string-to-number (match-string 2 dest))))
3959 (org-goto-line (aref org-table-dlines l))
3960 (org-table-goto-column c)))
3961 (t (org-table-goto-column (string-to-number name))))
3962 (move-marker pos (point))
3963 (org-table-highlight-rectangle nil nil face2))
3964 (cond
3965 ((equal dest match))
3966 ((not match))
3967 ((eq what 'range)
3968 (condition-case nil
3969 (save-excursion
3970 (org-table-get-range match nil nil 'highlight))
3971 (error nil)))
3972 ((setq e (assoc var org-table-named-field-locations))
3973 (org-goto-line (nth 1 e))
3974 (org-table-goto-column (nth 2 e))
3975 (org-table-highlight-rectangle (point) (point))
3976 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3977 ((setq e (assoc var org-table-column-names))
3978 (org-table-goto-column (string-to-number (cdr e)))
3979 (org-table-highlight-rectangle (point) (point))
3980 (goto-char (org-table-begin))
3981 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3982 (org-table-end) t)
3983 (progn
3984 (goto-char (match-beginning 1))
3985 (org-table-highlight-rectangle)
3986 (message "Named column (column %s)" (cdr e)))
3987 (user-error "Column name not found")))
3988 ((eq what 'column)
3989 ;; column number
3990 (org-table-goto-column (string-to-number (substring match 1)))
3991 (org-table-highlight-rectangle (point) (point))
3992 (message "Column %s" (substring match 1)))
3993 ((setq e (assoc var org-table-local-parameters))
3994 (goto-char (org-table-begin))
3995 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3996 (progn
3997 (goto-char (match-beginning 1))
3998 (org-table-highlight-rectangle)
3999 (message "Local parameter."))
4000 (user-error "Parameter not found")))
4002 (cond
4003 ((not var) (user-error "No reference at point"))
4004 ((setq e (assoc var org-table-formula-constants-local))
4005 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4006 var (cdr e)))
4007 ((setq e (assoc var org-table-formula-constants))
4008 (message "Constant: $%s=%s in `org-table-formula-constants'."
4009 var (cdr e)))
4010 ((setq e (and (fboundp 'constants-get) (constants-get var)))
4011 (message "Constant: $%s=%s, from `constants.el'%s."
4012 var e (format " (%s units)" constants-unit-system)))
4013 (t (user-error "Undefined name $%s" var)))))
4014 (goto-char pos)
4015 (when (and org-show-positions
4016 (not (memq this-command '(org-table-fedit-scroll
4017 org-table-fedit-scroll-down))))
4018 (push pos org-show-positions)
4019 (push org-table-current-begin-pos org-show-positions)
4020 (let ((min (apply 'min org-show-positions))
4021 (max (apply 'max org-show-positions)))
4022 (set-window-start (selected-window) min)
4023 (goto-char max)
4024 (or (pos-visible-in-window-p max)
4025 (set-window-start (selected-window) max))))
4026 (select-window win))))
4028 (defun org-table-force-dataline ()
4029 "Make sure the cursor is in a dataline in a table."
4030 (unless (save-excursion
4031 (beginning-of-line 1)
4032 (looking-at org-table-dataline-regexp))
4033 (let* ((re org-table-dataline-regexp)
4034 (p1 (save-excursion (re-search-forward re nil 'move)))
4035 (p2 (save-excursion (re-search-backward re nil 'move))))
4036 (cond ((and p1 p2)
4037 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
4038 p1 p2)))
4039 ((or p1 p2) (goto-char (or p1 p2)))
4040 (t (user-error "No table dataline around here"))))))
4042 (defun org-table-fedit-line-up ()
4043 "Move cursor one line up in the window showing the table."
4044 (interactive)
4045 (org-table-fedit-move 'previous-line))
4047 (defun org-table-fedit-line-down ()
4048 "Move cursor one line down in the window showing the table."
4049 (interactive)
4050 (org-table-fedit-move 'next-line))
4052 (defun org-table-fedit-move (command)
4053 "Move the cursor in the window showing the table.
4054 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4055 (let ((org-table-allow-automatic-line-recalculation nil)
4056 (pos org-pos) (win (selected-window)) p)
4057 (select-window (get-buffer-window (marker-buffer org-pos)))
4058 (setq p (point))
4059 (call-interactively command)
4060 (while (and (org-at-table-p)
4061 (org-at-table-hline-p))
4062 (call-interactively command))
4063 (or (org-at-table-p) (goto-char p))
4064 (move-marker pos (point))
4065 (select-window win)))
4067 (defun org-table-fedit-scroll (N)
4068 (interactive "p")
4069 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
4070 (scroll-other-window N)))
4072 (defun org-table-fedit-scroll-down (N)
4073 (interactive "p")
4074 (org-table-fedit-scroll (- N)))
4076 (defvar org-table-rectangle-overlays nil)
4078 (defun org-table-add-rectangle-overlay (beg end &optional face)
4079 "Add a new overlay."
4080 (let ((ov (make-overlay beg end)))
4081 (overlay-put ov 'face (or face 'secondary-selection))
4082 (push ov org-table-rectangle-overlays)))
4084 (defun org-table-highlight-rectangle (&optional beg end face)
4085 "Highlight rectangular region in a table."
4086 (setq beg (or beg (point)) end (or end (point)))
4087 (let ((b (min beg end))
4088 (e (max beg end))
4089 l1 c1 l2 c2 tmp)
4090 (and (boundp 'org-show-positions)
4091 (setq org-show-positions (cons b (cons e org-show-positions))))
4092 (goto-char (min beg end))
4093 (setq l1 (org-current-line)
4094 c1 (org-table-current-column))
4095 (goto-char (max beg end))
4096 (setq l2 (org-current-line)
4097 c2 (org-table-current-column))
4098 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
4099 (org-goto-line l1)
4100 (beginning-of-line 1)
4101 (loop for line from l1 to l2 do
4102 (when (looking-at org-table-dataline-regexp)
4103 (org-table-goto-column c1)
4104 (skip-chars-backward "^|\n") (setq beg (point))
4105 (org-table-goto-column c2)
4106 (skip-chars-forward "^|\n") (setq end (point))
4107 (org-table-add-rectangle-overlay beg end face))
4108 (beginning-of-line 2))
4109 (goto-char b))
4110 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
4112 (defun org-table-remove-rectangle-highlight (&rest ignore)
4113 "Remove the rectangle overlays."
4114 (unless org-inhibit-highlight-removal
4115 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4116 (mapc 'delete-overlay org-table-rectangle-overlays)
4117 (setq org-table-rectangle-overlays nil)))
4119 (defvar org-table-coordinate-overlays nil
4120 "Collects the coordinate grid overlays, so that they can be removed.")
4121 (make-variable-buffer-local 'org-table-coordinate-overlays)
4123 (defun org-table-overlay-coordinates ()
4124 "Add overlays to the table at point, to show row/column coordinates."
4125 (interactive)
4126 (mapc 'delete-overlay org-table-coordinate-overlays)
4127 (setq org-table-coordinate-overlays nil)
4128 (save-excursion
4129 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4130 (goto-char (org-table-begin))
4131 (while (org-at-table-p)
4132 (setq eol (point-at-eol))
4133 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4134 (push ov org-table-coordinate-overlays)
4135 (setq hline (looking-at org-table-hline-regexp))
4136 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4137 (format "%4d" (setq id (1+ id)))))
4138 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4139 (when hline
4140 (setq ic 0)
4141 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4142 (setq beg (1+ (match-beginning 0))
4143 ic (1+ ic)
4144 s1 (concat "$" (int-to-string ic))
4145 s2 (org-number-to-letters ic)
4146 str (if (eq org-table-use-standard-references t) s2 s1))
4147 (setq ov (make-overlay beg (+ beg (length str))))
4148 (push ov org-table-coordinate-overlays)
4149 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4150 (beginning-of-line 2)))))
4152 ;;;###autoload
4153 (defun org-table-toggle-coordinate-overlays ()
4154 "Toggle the display of Row/Column numbers in tables."
4155 (interactive)
4156 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4157 (message "Tables Row/Column numbers display turned %s"
4158 (if org-table-overlay-coordinates "on" "off"))
4159 (if (and (org-at-table-p) org-table-overlay-coordinates)
4160 (org-table-align))
4161 (unless org-table-overlay-coordinates
4162 (mapc 'delete-overlay org-table-coordinate-overlays)
4163 (setq org-table-coordinate-overlays nil)))
4165 ;;;###autoload
4166 (defun org-table-toggle-formula-debugger ()
4167 "Toggle the formula debugger in tables."
4168 (interactive)
4169 (setq org-table-formula-debug (not org-table-formula-debug))
4170 (message "Formula debugging has been turned %s"
4171 (if org-table-formula-debug "on" "off")))
4173 ;;; The orgtbl minor mode
4175 ;; Define a minor mode which can be used in other modes in order to
4176 ;; integrate the org-mode table editor.
4178 ;; This is really a hack, because the org-mode table editor uses several
4179 ;; keys which normally belong to the major mode, for example the TAB and
4180 ;; RET keys. Here is how it works: The minor mode defines all the keys
4181 ;; necessary to operate the table editor, but wraps the commands into a
4182 ;; function which tests if the cursor is currently inside a table. If that
4183 ;; is the case, the table editor command is executed. However, when any of
4184 ;; those keys is used outside a table, the function uses `key-binding' to
4185 ;; look up if the key has an associated command in another currently active
4186 ;; keymap (minor modes, major mode, global), and executes that command.
4187 ;; There might be problems if any of the keys used by the table editor is
4188 ;; otherwise used as a prefix key.
4190 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4191 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4192 ;; addresses this by checking explicitly for both bindings.
4194 ;; The optimized version (see variable `orgtbl-optimized') takes over
4195 ;; all keys which are bound to `self-insert-command' in the *global map*.
4196 ;; Some modes bind other commands to simple characters, for example
4197 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4198 ;; active, this binding is ignored inside tables and replaced with a
4199 ;; modified self-insert.
4202 (defvar orgtbl-mode-map (make-keymap)
4203 "Keymap for `orgtbl-mode'.")
4205 (defvar org-old-auto-fill-inhibit-regexp nil
4206 "Local variable used by `orgtbl-mode'.")
4208 (defconst orgtbl-line-start-regexp
4209 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4210 "Matches a line belonging to an orgtbl.")
4212 (defconst orgtbl-extra-font-lock-keywords
4213 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4214 0 (quote 'org-table) 'prepend))
4215 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4217 ;; Install it as a minor mode.
4218 (put 'orgtbl-mode :included t)
4219 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4221 ;;;###autoload
4222 (define-minor-mode orgtbl-mode
4223 "The `org-mode' table editor as a minor mode for use in other modes."
4224 :lighter " OrgTbl" :keymap orgtbl-mode-map
4225 (org-load-modules-maybe)
4226 (cond
4227 ((derived-mode-p 'org-mode)
4228 ;; Exit without error, in case some hook functions calls this
4229 ;; by accident in org-mode.
4230 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4231 (orgtbl-mode
4232 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4233 ;; Make sure we are first in minor-mode-map-alist
4234 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4235 ;; FIXME: maybe it should use emulation-mode-map-alists?
4236 (and c (setq minor-mode-map-alist
4237 (cons c (delq c minor-mode-map-alist)))))
4238 (org-set-local (quote org-table-may-need-update) t)
4239 (org-add-hook 'before-change-functions 'org-before-change-function
4240 nil 'local)
4241 (org-set-local 'org-old-auto-fill-inhibit-regexp
4242 auto-fill-inhibit-regexp)
4243 (org-set-local 'auto-fill-inhibit-regexp
4244 (if auto-fill-inhibit-regexp
4245 (concat orgtbl-line-start-regexp "\\|"
4246 auto-fill-inhibit-regexp)
4247 orgtbl-line-start-regexp))
4248 (add-to-invisibility-spec '(org-cwidth))
4249 (when (fboundp 'font-lock-add-keywords)
4250 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4251 (org-restart-font-lock))
4252 (easy-menu-add orgtbl-mode-menu))
4254 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4255 (org-table-cleanup-narrow-column-properties)
4256 (org-remove-from-invisibility-spec '(org-cwidth))
4257 (remove-hook 'before-change-functions 'org-before-change-function t)
4258 (when (fboundp 'font-lock-remove-keywords)
4259 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4260 (org-restart-font-lock))
4261 (easy-menu-remove orgtbl-mode-menu)
4262 (force-mode-line-update 'all))))
4264 (defun org-table-cleanup-narrow-column-properties ()
4265 "Remove all properties related to narrow-column invisibility."
4266 (let ((s (point-min)))
4267 (while (setq s (text-property-any s (point-max)
4268 'display org-narrow-column-arrow))
4269 (remove-text-properties s (1+ s) '(display t)))
4270 (setq s (point-min))
4271 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4272 (remove-text-properties s (1+ s) '(org-cwidth t)))
4273 (setq s (point-min))
4274 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4275 (remove-text-properties s (1+ s) '(invisible t)))))
4277 (defun orgtbl-make-binding (fun n &rest keys)
4278 "Create a function for binding in the table minor mode.
4279 FUN is the command to call inside a table. N is used to create a unique
4280 command name. KEYS are keys that should be checked in for a command
4281 to execute outside of tables."
4282 (eval
4283 (list 'defun
4284 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4285 '(arg)
4286 (concat "In tables, run `" (symbol-name fun) "'.\n"
4287 "Outside of tables, run the binding of `"
4288 (mapconcat #'key-description keys "' or `")
4289 "'.")
4290 '(interactive "p")
4291 (list 'if
4292 '(org-at-table-p)
4293 (list 'call-interactively (list 'quote fun))
4294 (list 'let '(orgtbl-mode)
4295 (list 'call-interactively
4296 (append '(or)
4297 (mapcar (lambda (k)
4298 (list 'key-binding k))
4299 keys)
4300 '('orgtbl-error))))))))
4302 (defun orgtbl-error ()
4303 "Error when there is no default binding for a table key."
4304 (interactive)
4305 (user-error "This key has no function outside tables"))
4307 (defun orgtbl-setup ()
4308 "Setup orgtbl keymaps."
4309 (let ((nfunc 0)
4310 (bindings
4311 '(([(meta shift left)] org-table-delete-column)
4312 ([(meta left)] org-table-move-column-left)
4313 ([(meta right)] org-table-move-column-right)
4314 ([(meta shift right)] org-table-insert-column)
4315 ([(meta shift up)] org-table-kill-row)
4316 ([(meta shift down)] org-table-insert-row)
4317 ([(meta up)] org-table-move-row-up)
4318 ([(meta down)] org-table-move-row-down)
4319 ("\C-c\C-w" org-table-cut-region)
4320 ("\C-c\M-w" org-table-copy-region)
4321 ("\C-c\C-y" org-table-paste-rectangle)
4322 ("\C-c\C-w" org-table-wrap-region)
4323 ("\C-c-" org-table-insert-hline)
4324 ("\C-c}" org-table-toggle-coordinate-overlays)
4325 ("\C-c{" org-table-toggle-formula-debugger)
4326 ("\C-m" org-table-next-row)
4327 ([(shift return)] org-table-copy-down)
4328 ("\C-c?" org-table-field-info)
4329 ("\C-c " org-table-blank-field)
4330 ("\C-c+" org-table-sum)
4331 ("\C-c=" org-table-eval-formula)
4332 ("\C-c'" org-table-edit-formulas)
4333 ("\C-c`" org-table-edit-field)
4334 ("\C-c*" org-table-recalculate)
4335 ("\C-c^" org-table-sort-lines)
4336 ("\M-a" org-table-beginning-of-field)
4337 ("\M-e" org-table-end-of-field)
4338 ([(control ?#)] org-table-rotate-recalc-marks)))
4339 elt key fun cmd)
4340 (while (setq elt (pop bindings))
4341 (setq nfunc (1+ nfunc))
4342 (setq key (org-key (car elt))
4343 fun (nth 1 elt)
4344 cmd (orgtbl-make-binding fun nfunc key))
4345 (org-defkey orgtbl-mode-map key cmd))
4347 ;; Special treatment needed for TAB and RET
4348 (org-defkey orgtbl-mode-map [(return)]
4349 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4350 (org-defkey orgtbl-mode-map "\C-m"
4351 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4353 (org-defkey orgtbl-mode-map [(tab)]
4354 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4355 (org-defkey orgtbl-mode-map "\C-i"
4356 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4358 (org-defkey orgtbl-mode-map [(shift tab)]
4359 (orgtbl-make-binding 'org-table-previous-field 104
4360 [(shift tab)] [(tab)] "\C-i"))
4363 (unless (featurep 'xemacs)
4364 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4365 (orgtbl-make-binding 'org-table-previous-field 107
4366 [S-iso-lefttab] [backtab] [(shift tab)]
4367 [(tab)] "\C-i")))
4369 (org-defkey orgtbl-mode-map [backtab]
4370 (orgtbl-make-binding 'org-table-previous-field 108
4371 [backtab] [S-iso-lefttab] [(shift tab)]
4372 [(tab)] "\C-i"))
4374 (org-defkey orgtbl-mode-map "\M-\C-m"
4375 (orgtbl-make-binding 'org-table-wrap-region 105
4376 "\M-\C-m" [(meta return)]))
4377 (org-defkey orgtbl-mode-map [(meta return)]
4378 (orgtbl-make-binding 'org-table-wrap-region 106
4379 [(meta return)] "\M-\C-m"))
4381 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4382 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4384 (when orgtbl-optimized
4385 ;; If the user wants maximum table support, we need to hijack
4386 ;; some standard editing functions
4387 (org-remap orgtbl-mode-map
4388 'self-insert-command 'orgtbl-self-insert-command
4389 'delete-char 'org-delete-char
4390 'delete-backward-char 'org-delete-backward-char)
4391 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4392 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4393 '("OrgTbl"
4394 ["Create or convert" org-table-create-or-convert-from-region
4395 :active (not (org-at-table-p)) :keys "C-c |" ]
4396 "--"
4397 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4398 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4399 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4400 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4401 "--"
4402 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4403 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4404 ["Copy Field from Above"
4405 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4406 "--"
4407 ("Column"
4408 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4409 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4410 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4411 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4412 ("Row"
4413 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4414 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4415 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4416 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4417 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4418 "--"
4419 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4420 ("Rectangle"
4421 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4422 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4423 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4424 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4425 "--"
4426 ("Radio tables"
4427 ["Insert table template" orgtbl-insert-radio-table
4428 (assq major-mode orgtbl-radio-table-templates)]
4429 ["Comment/uncomment table" orgtbl-toggle-comment t])
4430 "--"
4431 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4432 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4433 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4434 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4435 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4436 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4437 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4438 ["Sum Column/Rectangle" org-table-sum
4439 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4440 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4441 ["Debug Formulas"
4442 org-table-toggle-formula-debugger :active (org-at-table-p)
4443 :keys "C-c {"
4444 :style toggle :selected org-table-formula-debug]
4445 ["Show Col/Row Numbers"
4446 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4447 :keys "C-c }"
4448 :style toggle :selected org-table-overlay-coordinates]
4449 "--"
4450 ("Plot"
4451 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4452 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4455 (defun orgtbl-ctrl-c-ctrl-c (arg)
4456 "If the cursor is inside a table, realign the table.
4457 If it is a table to be sent away to a receiver, do it.
4458 With prefix arg, also recompute table."
4459 (interactive "P")
4460 (let ((case-fold-search t) (pos (point)) action)
4461 (save-excursion
4462 (beginning-of-line 1)
4463 (setq action (cond
4464 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4465 ((looking-at "[ \t]*|") pos)
4466 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4467 (cond
4468 ((integerp action)
4469 (goto-char action)
4470 (org-table-maybe-eval-formula)
4471 (if arg
4472 (call-interactively 'org-table-recalculate)
4473 (org-table-maybe-recalculate-line))
4474 (call-interactively 'org-table-align)
4475 (when (orgtbl-send-table 'maybe)
4476 (run-hooks 'orgtbl-after-send-table-hook)))
4477 ((eq action 'recalc)
4478 (save-excursion
4479 (beginning-of-line 1)
4480 (skip-chars-backward " \r\n\t")
4481 (if (org-at-table-p)
4482 (org-call-with-arg 'org-table-recalculate t))))
4483 (t (let (orgtbl-mode)
4484 (call-interactively (key-binding "\C-c\C-c")))))))
4486 (defun orgtbl-create-or-convert-from-region (arg)
4487 "Create table or convert region to table, if no conflicting binding.
4488 This installs the table binding `C-c |', but only if there is no
4489 conflicting binding to this key outside orgtbl-mode."
4490 (interactive "P")
4491 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4492 (if cmd
4493 (call-interactively cmd)
4494 (call-interactively 'org-table-create-or-convert-from-region))))
4496 (defun orgtbl-tab (arg)
4497 "Justification and field motion for `orgtbl-mode'."
4498 (interactive "P")
4499 (if arg (org-table-edit-field t)
4500 (org-table-justify-field-maybe)
4501 (org-table-next-field)))
4503 (defun orgtbl-ret ()
4504 "Justification and field motion for `orgtbl-mode'."
4505 (interactive)
4506 (if (bobp)
4507 (newline)
4508 (org-table-justify-field-maybe)
4509 (org-table-next-row)))
4511 (defun orgtbl-self-insert-command (N)
4512 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4513 If the cursor is in a table looking at whitespace, the whitespace is
4514 overwritten, and the table is not marked as requiring realignment."
4515 (interactive "p")
4516 (if (and (org-at-table-p)
4518 (and org-table-auto-blank-field
4519 (member last-command
4520 '(orgtbl-hijacker-command-100
4521 orgtbl-hijacker-command-101
4522 orgtbl-hijacker-command-102
4523 orgtbl-hijacker-command-103
4524 orgtbl-hijacker-command-104
4525 orgtbl-hijacker-command-105
4526 yas/expand))
4527 (org-table-blank-field))
4529 (eq N 1)
4530 (looking-at "[^|\n]* +|"))
4531 (let (org-table-may-need-update)
4532 (goto-char (1- (match-end 0)))
4533 (org-delete-backward-char 1)
4534 (goto-char (match-beginning 0))
4535 (self-insert-command N))
4536 (setq org-table-may-need-update t)
4537 (let* (orgtbl-mode
4539 (cmd (or (key-binding
4540 (or (and (listp function-key-map)
4541 (setq a (assoc last-input-event function-key-map))
4542 (cdr a))
4543 (vector last-input-event)))
4544 'self-insert-command)))
4545 (call-interactively cmd)
4546 (if (and org-self-insert-cluster-for-undo
4547 (eq cmd 'self-insert-command))
4548 (if (not (eq last-command 'orgtbl-self-insert-command))
4549 (setq org-self-insert-command-undo-counter 1)
4550 (if (>= org-self-insert-command-undo-counter 20)
4551 (setq org-self-insert-command-undo-counter 1)
4552 (and (> org-self-insert-command-undo-counter 0)
4553 buffer-undo-list
4554 (not (cadr buffer-undo-list)) ; remove nil entry
4555 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4556 (setq org-self-insert-command-undo-counter
4557 (1+ org-self-insert-command-undo-counter))))))))
4559 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4560 "Regular expression matching exponentials as produced by calc.")
4562 (defun orgtbl-gather-send-defs ()
4563 "Gather a plist of :name, :transform, :params for each destination before
4564 a radio table."
4565 (save-excursion
4566 (goto-char (org-table-begin))
4567 (let (rtn)
4568 (beginning-of-line 0)
4569 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4570 (let ((name (org-no-properties (match-string 1)))
4571 (transform (intern (match-string 2)))
4572 (params (if (match-end 3)
4573 (read (concat "(" (match-string 3) ")")))))
4574 (push (list :name name :transform transform :params params)
4575 rtn)
4576 (beginning-of-line 0)))
4577 rtn)))
4579 (defun orgtbl-send-replace-tbl (name txt)
4580 "Find and replace table NAME with TXT."
4581 (save-excursion
4582 (goto-char (point-min))
4583 (unless (re-search-forward
4584 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4585 (user-error "Don't know where to insert translated table"))
4586 (let ((beg (line-beginning-position 2)))
4587 (unless (re-search-forward
4588 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4589 (user-error "Cannot find end of insertion region"))
4590 (beginning-of-line)
4591 (delete-region beg (point)))
4592 (insert txt "\n")))
4594 ;;;###autoload
4595 (defun org-table-to-lisp (&optional txt)
4596 "Convert the table at point to a Lisp structure.
4597 The structure will be a list. Each item is either the symbol `hline'
4598 for a horizontal separator line, or a list of field values as strings.
4599 The table is taken from the parameter TXT, or from the buffer at point."
4600 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4601 (let ((txt (or txt
4602 (buffer-substring-no-properties (org-table-begin)
4603 (org-table-end)))))
4604 (mapcar (lambda (x)
4605 (if (string-match org-table-hline-regexp x) 'hline
4606 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4607 (org-split-string txt "[ \t]*\n[ \t]*"))))
4609 (defun orgtbl-send-table (&optional maybe)
4610 "Send a transformed version of table at point to the receiver position.
4611 With argument MAYBE, fail quietly if no transformation is defined
4612 for this table."
4613 (interactive)
4614 (catch 'exit
4615 (unless (org-at-table-p) (user-error "Not at a table"))
4616 ;; when non-interactive, we assume align has just happened.
4617 (when (org-called-interactively-p 'any) (org-table-align))
4618 (let ((dests (orgtbl-gather-send-defs))
4619 (table (org-table-to-lisp
4620 (buffer-substring-no-properties (org-table-begin)
4621 (org-table-end))))
4622 (ntbl 0))
4623 (unless dests
4624 (if maybe (throw 'exit nil)
4625 (user-error "Don't know how to transform this table")))
4626 (dolist (dest dests)
4627 (let ((name (plist-get dest :name))
4628 (transform (plist-get dest :transform))
4629 (params (plist-get dest :params)))
4630 (unless (fboundp transform)
4631 (user-error "No such transformation function %s" transform))
4632 (orgtbl-send-replace-tbl name (funcall transform table params)))
4633 (incf ntbl))
4634 (message "Table converted and installed at %d receiver location%s"
4635 ntbl (if (> ntbl 1) "s" ""))
4636 (and (> ntbl 0) ntbl))))
4638 (defun org-remove-by-index (list indices &optional i0)
4639 "Remove the elements in LIST with indices in INDICES.
4640 First element has index 0, or I0 if given."
4641 (if (not indices)
4642 list
4643 (if (integerp indices) (setq indices (list indices)))
4644 (setq i0 (1- (or i0 0)))
4645 (delq :rm (mapcar (lambda (x)
4646 (setq i0 (1+ i0))
4647 (if (memq i0 indices) :rm x))
4648 list))))
4650 (defun orgtbl-toggle-comment ()
4651 "Comment or uncomment the orgtbl at point."
4652 (interactive)
4653 (let* ((case-fold-search t)
4654 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4655 (re2 (concat "^" orgtbl-line-start-regexp))
4656 (commented (save-excursion (beginning-of-line 1)
4657 (cond ((looking-at re1) t)
4658 ((looking-at re2) nil)
4659 (t (user-error "Not at an org table")))))
4660 (re (if commented re1 re2))
4661 beg end)
4662 (save-excursion
4663 (beginning-of-line 1)
4664 (while (looking-at re) (beginning-of-line 0))
4665 (beginning-of-line 2)
4666 (setq beg (point))
4667 (while (looking-at re) (beginning-of-line 2))
4668 (setq end (point)))
4669 (comment-region beg end (if commented '(4) nil))))
4671 (defun orgtbl-insert-radio-table ()
4672 "Insert a radio table template appropriate for this major mode."
4673 (interactive)
4674 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4675 (txt (nth 1 e))
4676 name pos)
4677 (unless e (user-error "No radio table setup defined for %s" major-mode))
4678 (setq name (read-string "Table name: "))
4679 (while (string-match "%n" txt)
4680 (setq txt (replace-match name t t txt)))
4681 (or (bolp) (insert "\n"))
4682 (setq pos (point))
4683 (insert txt)
4684 (goto-char pos)))
4686 ;;;###autoload
4687 (defun orgtbl-to-generic (table params)
4688 "Convert the orgtbl-mode TABLE to some other format.
4690 This generic routine can be used for many standard cases.
4692 TABLE is a list, each entry either the symbol `hline' for
4693 a horizontal separator line, or a list of fields for that
4694 line. PARAMS is a property list of parameters that can
4695 influence the conversion.
4697 Valid parameters are:
4699 :backend, :raw
4701 Export back-end used as a basis to transcode elements of the
4702 table, when no specific parameter applies to it. It is also
4703 used to translate cells contents. You can prevent this by
4704 setting :raw property to a non-nil value.
4706 :splice
4708 When non-nil, only convert rows, not the table itself. This is
4709 equivalent to setting to the empty string both :tstart
4710 and :tend, which see.
4712 :skip
4714 When set to an integer N, skip the first N lines of the table.
4715 Horizontal separation lines do count for this parameter!
4717 :skipcols
4719 List of columns that should be skipped. If the table has
4720 a column with calculation marks, that column is automatically
4721 discarded beforehand.
4723 :hline
4725 String to be inserted on horizontal separation lines. May be
4726 nil to ignore these lines altogether.
4728 :sep
4730 Separator between two fields, as a string.
4732 Each in the following group may be either a string or a function
4733 of no arguments returning a string:
4735 :tstart, :tend
4737 Strings to start and end the table. Ignored when :splice is t.
4739 :lstart, :lend
4741 Strings to start and end a new table line.
4743 :llstart, :llend
4745 Strings to start and end the last table line. Default,
4746 respectively, to :lstart and :lend.
4748 Each in the following group may be a string or a function of one
4749 argument (either the cells in the current row, as a list of
4750 strings, or the current cell) returning a string:
4752 :lfmt
4754 Format string for an entire row, with enough %s to capture all
4755 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4757 :llfmt
4759 Format for the entire last line, defaults to :lfmt.
4761 :fmt
4763 A format to be used to wrap the field, should contain %s for
4764 the original field value. For example, to wrap everything in
4765 dollars, you could use :fmt \"$%s$\". This may also be
4766 a property list with column numbers and format strings, or
4767 functions, e.g.,
4769 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4771 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4773 Same as above, specific for the header lines in the table.
4774 All lines before the first hline are treated as header. If
4775 any of these is not present, the data line value is used.
4777 This may be either a string or a function of two arguments:
4779 :efmt
4781 Use this format to print numbers with exponential. The format
4782 should have %s twice for inserting mantissa and exponent, for
4783 example \"%s\\\\times10^{%s}\". This may also be a property
4784 list with column numbers and format strings or functions.
4785 :fmt will still be applied after :efmt."
4786 (let ((backend (plist-get params :backend))
4787 ;; Disable user-defined export filters and hooks.
4788 (org-export-filters-alist nil)
4789 (org-export-before-parsing-hook nil)
4790 (org-export-before-processing-hook nil))
4791 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4792 (user-error "Unknown :backend value"))
4793 (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
4794 (org-trim
4795 (org-export-string-as
4796 ;; Return TABLE as Org syntax. Tolerate non-string cells.
4797 (with-output-to-string
4798 (dolist (e table)
4799 (cond ((eq e 'hline) (princ "|--\n"))
4800 ((consp e)
4801 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4802 (princ "\n")))))
4803 ;; Build a custom back-end according to PARAMS. Before defining
4804 ;; a translator, check if there is anything to do. When there
4805 ;; isn't, let BACKEND handle the element.
4806 (org-export-create-backend
4807 :parent (or backend 'org)
4808 :filters
4809 '((:filter-parse-tree
4810 ;; Handle :skip parameter.
4811 (lambda (tree backend info)
4812 (let ((skip (plist-get info :skip)))
4813 (when skip
4814 (unless (wholenump skip) (user-error "Wrong :skip value"))
4815 (let ((n 0))
4816 (org-element-map tree 'table-row
4817 (lambda (row)
4818 (if (>= n skip) t
4819 (org-element-extract-element row)
4820 (incf n)
4821 nil))
4822 info t))
4823 tree)))
4824 ;; Handle :skipcols parameter.
4825 (lambda (tree backend info)
4826 (let ((skipcols (plist-get info :skipcols)))
4827 (when skipcols
4828 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4829 (org-element-map tree 'table
4830 (lambda (table)
4831 (let ((specialp
4832 (org-export-table-has-special-column-p table)))
4833 (dolist (row (org-element-contents table))
4834 (when (eq (org-element-property :type row) 'standard)
4835 (let ((c 1))
4836 (dolist (cell (nthcdr (if specialp 1 0)
4837 (org-element-contents row)))
4838 (when (memq c skipcols)
4839 (org-element-extract-element cell))
4840 (incf c)))))))
4841 info)
4842 tree)))))
4843 :transcoders
4844 `((table . ,(org-table--to-generic-table params))
4845 (table-row . ,(org-table--to-generic-row params))
4846 (table-cell . ,(org-table--to-generic-cell params))
4847 ;; Section. Return contents to avoid garbage around table.
4848 (section . (lambda (s c i) c))))
4849 'body-only (org-combine-plists params '(:with-tables t))))))
4851 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4852 (cond ((null value) nil)
4853 ((functionp value) `(funcall ',value ,@args))
4854 ((stringp value)
4855 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4856 (args `(format ,value ,@args))
4857 (t value)))
4858 ((and with-cons (consp value))
4859 `(let ((val (cadr (memq column ',value))))
4860 (cond ((null val) contents)
4861 ((stringp val) (format val ,@args))
4862 ((functionp val) (funcall val ,@args))
4863 (t (user-error "Wrong %s value" ,name)))))
4864 (t (user-error "Wrong %s value" name))))
4866 (defun org-table--to-generic-table (params)
4867 "Return custom table transcoder according to PARAMS.
4868 PARAMS is a plist. See `orgtbl-to-generic' for more
4869 information."
4870 (let ((backend (plist-get params :backend))
4871 (splice (plist-get params :splice))
4872 (tstart (plist-get params :tstart))
4873 (tend (plist-get params :tend)))
4874 `(lambda (table contents info)
4875 (concat
4876 ,(and tstart (not splice)
4877 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4878 ,(if (or (not backend) tstart tend splice) 'contents
4879 `(org-export-with-backend ',backend table contents info))
4880 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4882 (defun org-table--to-generic-row (params)
4883 "Return custom table row transcoder according to PARAMS.
4884 PARAMS is a plist. See `orgtbl-to-generic' for more
4885 information."
4886 (let* ((backend (plist-get params :backend))
4887 (lstart (plist-get params :lstart))
4888 (llstart (plist-get params :llstart))
4889 (hlstart (plist-get params :hlstart))
4890 (hllstart (plist-get params :hllstart))
4891 (lend (plist-get params :lend))
4892 (llend (plist-get params :llend))
4893 (hlend (plist-get params :hlend))
4894 (hllend (plist-get params :hllend))
4895 (lfmt (plist-get params :lfmt))
4896 (llfmt (plist-get params :llfmt))
4897 (hlfmt (plist-get params :hlfmt))
4898 (hllfmt (plist-get params :hllfmt)))
4899 `(lambda (row contents info)
4900 (if (eq (org-element-property :type row) 'rule)
4901 ,(cond
4902 ((plist-member params :hline)
4903 (org-table--generic-apply (plist-get params :hline) ":hline"))
4904 (backend `(org-export-with-backend ',backend row nil info)))
4905 (let ((headerp (org-export-table-row-in-header-p row info))
4906 (lastp (not (org-export-get-next-element row info)))
4907 (last-header-p (org-export-table-row-ends-header-p row info)))
4908 (when contents
4909 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4910 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4911 ;; `:lstart', `:lend' and their relatives.
4912 ,(let ((cells
4913 '(org-element-map row 'table-cell
4914 (lambda (cell)
4915 ;; Export all cells, without separators.
4917 ;; Use `org-export-data-with-backend'
4918 ;; instead of `org-export-data' to eschew
4919 ;; cached values, which
4920 ;; ignore :orgtbl-ignore-sep parameter.
4921 (org-export-data-with-backend
4922 cell
4923 (plist-get info :back-end)
4924 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4925 info)))
4926 `(cond
4927 ,(and hllfmt
4928 `(last-header-p ,(org-table--generic-apply
4929 hllfmt ":hllfmt" nil cells)))
4930 ,(and hlfmt
4931 `(headerp ,(org-table--generic-apply
4932 hlfmt ":hlfmt" nil cells)))
4933 ,(and llfmt
4934 `(lastp ,(org-table--generic-apply
4935 llfmt ":llfmt" nil cells)))
4937 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4938 `(concat
4939 (cond
4940 ,(and
4941 (or hllstart hllend)
4942 `(last-header-p
4943 (concat
4944 ,(org-table--generic-apply hllstart ":hllstart")
4945 contents
4946 ,(org-table--generic-apply hllend ":hllend"))))
4947 ,(and
4948 (or hlstart hlend)
4949 `(headerp
4950 (concat
4951 ,(org-table--generic-apply hlstart ":hlstart")
4952 contents
4953 ,(org-table--generic-apply hlend ":hlend"))))
4954 ,(and
4955 (or llstart llend)
4956 `(lastp
4957 (concat
4958 ,(org-table--generic-apply llstart ":llstart")
4959 contents
4960 ,(org-table--generic-apply llend ":llend"))))
4962 ,(cond
4963 ((or lstart lend)
4964 `(concat
4965 ,(org-table--generic-apply lstart ":lstart")
4966 contents
4967 ,(org-table--generic-apply lend ":lend")))
4968 (backend
4969 `(org-export-with-backend
4970 ',backend row contents info))
4971 (t 'contents)))))))))))))))
4973 (defun org-table--to-generic-cell (params)
4974 "Return custom table cell transcoder according to PARAMS.
4975 PARAMS is a plist. See `orgtbl-to-generic' for more
4976 information."
4977 (let* ((backend (plist-get params :backend))
4978 (efmt (plist-get params :efmt))
4979 (fmt (plist-get params :fmt))
4980 (hfmt (plist-get params :hfmt))
4981 (sep (plist-get params :sep))
4982 (hsep (plist-get params :hsep)))
4983 `(lambda (cell contents info)
4984 (let ((headerp (org-export-table-row-in-header-p
4985 (org-export-get-parent-element cell) info))
4986 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4987 ;; Make sure that contents are exported as Org data when :raw
4988 ;; parameter is non-nil.
4989 ,(when (and backend (plist-get params :raw))
4990 `(setq contents
4991 ;; Since we don't know what are the pseudo object
4992 ;; types defined in backend, we cannot pass them to
4993 ;; `org-element-interpret-data'. As a consequence,
4994 ;; they will be treated as pseudo elements, and
4995 ;; will have newlines appended instead of spaces.
4996 ;; Therefore, we must make sure :post-blank value
4997 ;; is really turned into spaces.
4998 (replace-regexp-in-string
4999 "\n" " "
5000 (org-trim
5001 (org-element-interpret-data
5002 (org-element-contents cell))))))
5003 (when contents
5004 ;; Check if we can apply `:efmt' on CONTENTS.
5005 ,(when efmt
5006 `(when (string-match orgtbl-exp-regexp contents)
5007 (let ((mantissa (match-string 1 contents))
5008 (exponent (match-string 2 contents)))
5009 (setq contents ,(org-table--generic-apply
5010 efmt ":efmt" t 'mantissa 'exponent)))))
5011 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5012 (cond
5013 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5014 hfmt ":hfmt" t 'contents))))
5015 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5016 fmt ":fmt" t 'contents))))))
5017 ;; If a separator is provided, use it instead of BACKEND's.
5018 ;; Separators are ignored when LFMT (or equivalent) is
5019 ;; provided.
5020 ,(cond
5021 ((or hsep sep)
5022 `(if (or ,(and (not sep) '(not headerp))
5023 (plist-get info :orgtbl-ignore-sep)
5024 (not (org-export-get-next-element cell info)))
5025 ,(if (not backend) 'contents
5026 `(org-export-with-backend ',backend cell contents info))
5027 (concat contents
5028 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5029 (or hsep sep)))))
5030 (backend `(org-export-with-backend ',backend cell contents info))
5031 (t 'contents))))))
5033 ;;;###autoload
5034 (defun orgtbl-to-tsv (table params)
5035 "Convert the orgtbl-mode table to TAB separated material."
5036 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5038 ;;;###autoload
5039 (defun orgtbl-to-csv (table params)
5040 "Convert the orgtbl-mode table to CSV material.
5041 This does take care of the proper quoting of fields with comma or quotes."
5042 (orgtbl-to-generic table
5043 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5044 params)))
5046 ;;;###autoload
5047 (defun orgtbl-to-latex (table params)
5048 "Convert the orgtbl-mode TABLE to LaTeX.
5050 TABLE is a list, each entry either the symbol `hline' for
5051 a horizontal separator line, or a list of fields for that line.
5052 PARAMS is a property list of parameters that can influence the
5053 conversion. All parameters from `orgtbl-to-generic' are
5054 supported. It is also possible to use the following ones:
5056 :booktabs
5058 When non-nil, use formal \"booktabs\" style.
5060 :environment
5062 Specify environment to use, as a string. If you use
5063 \"longtable\", you may also want to specify :language property,
5064 as a string, to get proper continuation strings."
5065 (require 'ox-latex)
5066 (orgtbl-to-generic
5067 table
5068 (org-combine-plists
5069 ;; Provide sane default values.
5070 (list :backend 'latex
5071 :latex-default-table-mode 'table
5072 :latex-tables-centered nil
5073 :latex-tables-booktabs (plist-get params :booktabs)
5074 :latex-table-scientific-notation nil
5075 :latex-default-table-environment
5076 (or (plist-get params :environment) "tabular"))
5077 params)))
5079 ;;;###autoload
5080 (defun orgtbl-to-html (table params)
5081 "Convert the orgtbl-mode TABLE to HTML.
5083 TABLE is a list, each entry either the symbol `hline' for
5084 a horizontal separator line, or a list of fields for that line.
5085 PARAMS is a property list of parameters that can influence the
5086 conversion. All parameters from `orgtbl-to-generic' are
5087 supported. It is also possible to use the following one:
5089 :attributes
5091 Attributes and values, as a plist, which will be used in
5092 <table> tag."
5093 (require 'ox-html)
5094 (orgtbl-to-generic
5095 table
5096 (org-combine-plists
5097 ;; Provide sane default values.
5098 (list :backend 'html
5099 :html-table-data-tags '("<td%s>" . "</td>")
5100 :html-table-use-header-tags-for-first-column nil
5101 :html-table-align-individual-fields t
5102 :html-table-row-tags '("<tr>" . "</tr>")
5103 :html-table-attributes
5104 (if (plist-member params :attributes)
5105 (plist-get params :attributes)
5106 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5107 :frame "hsides")))
5108 params)))
5110 ;;;###autoload
5111 (defun orgtbl-to-texinfo (table params)
5112 "Convert the orgtbl-mode TABLE to Texinfo.
5114 TABLE is a list, each entry either the symbol `hline' for
5115 a horizontal separator line, or a list of fields for that line.
5116 PARAMS is a property list of parameters that can influence the
5117 conversion. All parameters from `orgtbl-to-generic' are
5118 supported. It is also possible to use the following one:
5120 :columns
5122 Column widths, as a string. When providing column fractions,
5123 \"@columnfractions\" command can be omitted."
5124 (require 'ox-texinfo)
5125 (let ((output
5126 (orgtbl-to-generic
5127 table
5128 (org-combine-plists
5129 (list :backend 'texinfo
5130 :texinfo-tables-verbatim nil
5131 :texinfo-table-scientific-notation nil)
5132 params)))
5133 (columns (let ((w (plist-get params :columns)))
5134 (cond ((not w) nil)
5135 ((org-string-match-p "{\\|@columnfractions " w) w)
5136 (t (concat "@columnfractions " w))))))
5137 (if (not columns) output
5138 (replace-regexp-in-string
5139 "@multitable \\(.*\\)" columns output t nil 1))))
5141 ;;;###autoload
5142 (defun orgtbl-to-orgtbl (table params)
5143 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5145 TABLE is a list, each entry either the symbol `hline' for
5146 a horizontal separator line, or a list of fields for that line.
5147 PARAMS is a property list of parameters that can influence the
5148 conversion. All parameters from `orgtbl-to-generic' are
5149 supported.
5151 Useful when slicing one table into many. The :hline, :sep,
5152 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5153 be set to provide ORGTBL directives for the generated table."
5154 (require 'ox-org)
5155 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5157 (defun orgtbl-to-table.el (table params)
5158 "Convert the orgtbl-mode TABLE into a table.el table.
5159 TABLE is a list, each entry either the symbol `hline' for
5160 a horizontal separator line, or a list of fields for that line.
5161 PARAMS is a property list of parameters that can influence the
5162 conversion. All parameters from `orgtbl-to-generic' are
5163 supported."
5164 (with-temp-buffer
5165 (insert (orgtbl-to-orgtbl table params))
5166 (org-table-align)
5167 (replace-regexp-in-string
5168 "-|" "-+"
5169 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5171 (defun orgtbl-to-unicode (table params)
5172 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5174 TABLE is a list, each entry either the symbol `hline' for
5175 a horizontal separator line, or a list of fields for that line.
5176 PARAMS is a property list of parameters that can influence the
5177 conversion. All parameters from `orgtbl-to-generic' are
5178 supported. It is also possible to use the following ones:
5180 :ascii-art
5182 When non-nil, use \"ascii-art-to-unicode\" package to translate
5183 the table. You can download it here:
5184 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5186 :narrow
5188 When non-nil, narrow columns width than provided width cookie,
5189 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5190 (require 'ox-ascii)
5191 (orgtbl-to-generic
5192 table
5193 (org-combine-plists
5194 (list :backend 'ascii
5195 :ascii-charset 'utf-8
5196 :ascii-table-widen-columns (not (plist-get params :narrow))
5197 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5198 params)))
5200 ;; Put the cursor in a column containing numerical values
5201 ;; of an Org-Mode table,
5202 ;; type C-c " a
5203 ;; A new column is added with a bar plot.
5204 ;; When the table is refreshed (C-u C-c *),
5205 ;; the plot is updated to reflect the new values.
5207 (defun orgtbl-ascii-draw (value min max &optional width characters)
5208 "Draw an ascii bar in a table.
5209 VALUE is a the value to plot, the width of the bar to draw. A
5210 value equal to MIN will be displayed as empty (zero width bar).
5211 A value equal to MAX will draw a bar filling all the WIDTH.
5212 WIDTH is the expected width in characters of the column.
5213 CHARACTERS is a string that will compose the bar, with shades of
5214 grey from pure white to pure black. It defaults to a 10
5215 characters string of regular ascii characters."
5216 (let* ((characters (or characters " .:;c!lhVHW"))
5217 (width (or width 12))
5218 (value (if (numberp value) value (string-to-number value)))
5219 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5220 (cond
5221 ((< value 0) "too small")
5222 ((> value width) "too large")
5224 (let ((len (1- (length characters))))
5225 (concat
5226 (make-string (floor value) (elt characters len))
5227 (string (elt characters
5228 (floor (* (- value (floor value)) len))))))))))
5230 ;;;###autoload
5231 (defun orgtbl-ascii-plot (&optional ask)
5232 "Draw an ascii bar plot in a column.
5233 With cursor in a column containing numerical values, this
5234 function will draw a plot in a new column.
5235 ASK, if given, is a numeric prefix to override the default 12
5236 characters width of the plot. ASK may also be the
5237 \\[universal-argument] prefix, which will prompt for the width."
5238 (interactive "P")
5239 (let ((col (org-table-current-column))
5240 (min 1e999) ; 1e999 will be converted to infinity
5241 (max -1e999) ; which is the desired result
5242 (table (org-table-to-lisp))
5243 (length
5244 (cond ((consp ask)
5245 (read-number "Length of column " 12))
5246 ((numberp ask) ask)
5247 (t 12))))
5248 ;; Skip any hline a the top of table.
5249 (while (eq (car table) 'hline) (setq table (cdr table)))
5250 ;; Skip table header if any.
5251 (dolist (x (or (cdr (memq 'hline table)) table))
5252 (when (consp x)
5253 (setq x (nth (1- col) x))
5254 (when (string-match
5255 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5257 (setq x (string-to-number x))
5258 (when (> min x) (setq min x))
5259 (when (< max x) (setq max x)))))
5260 (org-table-insert-column)
5261 (org-table-move-column-right)
5262 (org-table-store-formulas
5263 (cons
5264 (cons
5265 (number-to-string (1+ col))
5266 (format "'(%s $%s %s %s %s)"
5267 "orgtbl-ascii-draw" col min max length))
5268 (org-table-get-stored-formulas)))
5269 (org-table-recalculate t)))
5271 ;; Example of extension: unicode characters
5272 ;; Here are two examples of different styles.
5274 ;; Unicode block characters are used to give a smooth effect.
5275 ;; See http://en.wikipedia.org/wiki/Block_Elements
5276 ;; Use one of those drawing functions
5277 ;; - orgtbl-ascii-draw (the default ascii)
5278 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5279 ;; - orgtbl-uc-draw-cont (smooth unicode)
5281 ;; This is best viewed with the "DejaVu Sans Mono" font
5282 ;; (use M-x set-default-font).
5284 (defun orgtbl-uc-draw-grid (value min max &optional width)
5285 "Draw a bar in a table using block unicode characters.
5286 It is a variant of orgtbl-ascii-draw with Unicode block
5287 characters, for a smooth display. Bars appear as grids (to the
5288 extent the font allows)."
5289 ;; http://en.wikipedia.org/wiki/Block_Elements
5290 ;; best viewed with the "DejaVu Sans Mono" font.
5291 (orgtbl-ascii-draw value min max width
5292 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5294 (defun orgtbl-uc-draw-cont (value min max &optional width)
5295 "Draw a bar in a table using block unicode characters.
5296 It is a variant of orgtbl-ascii-draw with Unicode block
5297 characters, for a smooth display. Bars are solid (to the extent
5298 the font allows)."
5299 (orgtbl-ascii-draw value min max width
5300 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5302 (defun org-table-get-remote-range (name-or-id form)
5303 "Get a field value or a list of values in a range from table at ID.
5305 NAME-OR-ID may be the name of a table in the current file as set
5306 by a \"#+NAME:\" directive. The first table following this line
5307 will then be used. Alternatively, it may be an ID referring to
5308 any entry, also in a different file. In this case, the first
5309 table in that entry will be referenced.
5310 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5311 \"@I$2..@II$2\". All the references must be absolute, not relative.
5313 The return value is either a single string for a single field, or a
5314 list of the fields in the rectangle."
5315 (save-match-data
5316 (let ((case-fold-search t) (id-loc nil)
5317 ;; Protect a bunch of variables from being overwritten
5318 ;; by the context of the remote table
5319 org-table-column-names org-table-column-name-regexp
5320 org-table-local-parameters org-table-named-field-locations
5321 org-table-current-line-types org-table-current-begin-line
5322 org-table-current-begin-pos org-table-dlines
5323 org-table-current-ncol
5324 org-table-hlines org-table-last-alignment
5325 org-table-last-column-widths org-table-last-alignment
5326 org-table-last-column-widths tbeg
5327 buffer loc)
5328 (setq form (org-table-convert-refs-to-rc form))
5329 (save-excursion
5330 (save-restriction
5331 (widen)
5332 (save-excursion
5333 (goto-char (point-min))
5334 (if (re-search-forward
5335 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5336 (regexp-quote name-or-id) "[ \t]*$")
5337 nil t)
5338 (setq buffer (current-buffer) loc (match-beginning 0))
5339 (setq id-loc (org-id-find name-or-id 'marker))
5340 (unless (and id-loc (markerp id-loc))
5341 (user-error "Can't find remote table \"%s\"" name-or-id))
5342 (setq buffer (marker-buffer id-loc)
5343 loc (marker-position id-loc))
5344 (move-marker id-loc nil)))
5345 (with-current-buffer buffer
5346 (save-excursion
5347 (save-restriction
5348 (widen)
5349 (goto-char loc)
5350 (forward-char 1)
5351 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5352 (not (match-beginning 1)))
5353 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5354 (setq tbeg (point-at-bol))
5355 (org-table-get-specials)
5356 (setq form (org-table-formula-substitute-names
5357 (org-table-formula-handle-first/last-rc form)))
5358 (if (and (string-match org-table-range-regexp form)
5359 (> (length (match-string 0 form)) 1))
5360 (save-match-data
5361 (org-table-get-range (match-string 0 form) tbeg 1))
5362 form)))))))))
5364 (defun org-table-remote-reference-indirection (form)
5365 "Return formula with table remote references substituted by indirection.
5366 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5367 This indirection works only with the format @ROW$COLUMN. The
5368 format \"B3\" is not supported because it can not be
5369 distinguished from a plain table name or ID."
5370 (let ((start 0))
5371 (while (string-match (concat
5372 ;; Same as in `org-table-eval-formula'.
5373 "\\<remote([ \t]*\\("
5374 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5375 "[@$][^ \t,]+"
5376 ;; Same as in `org-table-eval-formula'.
5377 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5378 form
5379 start)
5380 ;; The position of the character as far as possible to the right
5381 ;; that will not be replaced and particularly not be shifted by
5382 ;; `replace-match'.
5383 (setq start (match-beginning 1))
5384 ;; Substitute the remote reference with the value found in the
5385 ;; field.
5386 (setq form
5387 (replace-match
5388 (save-match-data
5389 (org-table-get-range (org-table-formula-handle-first/last-rc
5390 (match-string 1 form))))
5391 t t form 1))))
5392 form)
5394 (defmacro org-define-lookup-function (mode)
5395 (let ((mode-str (symbol-name mode))
5396 (first-p (equal mode 'first))
5397 (all-p (equal mode 'all)))
5398 (let ((plural-str (if all-p "s" "")))
5399 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5400 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5401 If R-LIST is nil, return matching element%s of S-LIST.
5402 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5403 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5404 This function is generated by a call to the macro `org-define-lookup-function'."
5405 mode-str plural-str plural-str plural-str)
5406 (let ,(let ((lvars '((p (or predicate 'equal))
5407 (sl s-list)
5408 (rl (or r-list s-list))
5409 (ret nil))))
5410 (if first-p (add-to-list 'lvars '(match-p nil)))
5411 lvars)
5412 (while ,(if first-p '(and (not match-p) sl) 'sl)
5413 (progn
5414 (if (funcall p val (car sl))
5415 (progn
5416 ,(if first-p '(setq match-p t))
5417 (let ((rval (car rl)))
5418 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5419 (setq sl (cdr sl) rl (cdr rl))))
5420 ret)))))
5422 (org-define-lookup-function first)
5423 (org-define-lookup-function last)
5424 (org-define-lookup-function all)
5426 (provide 'org-table)
5428 ;; Local variables:
5429 ;; generated-autoload-file: "org-loaddefs.el"
5430 ;; End:
5432 ;;; org-table.el ends here