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