1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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.
40 (declare-function org-element-at-point
"org-element" ())
41 (declare-function org-element-contents
"org-element" (element))
42 (declare-function org-element-extract-element
"org-element" (element))
43 (declare-function org-element-interpret-data
"org-element" (data))
44 (declare-function org-element-lineage
"org-element"
45 (blob &optional types with-self
))
46 (declare-function org-element-map
"org-element"
48 &optional info first-match no-recursion with-affiliated
))
49 (declare-function org-element-parse-buffer
"org-element"
50 (&optional granularity visible-only
))
51 (declare-function org-element-property
"org-element" (property element
))
52 (declare-function org-element-type
"org-element" (element))
54 (declare-function org-export-create-backend
"ox" (&rest rest
) t
)
55 (declare-function org-export-data-with-backend
"ox" (data backend info
))
56 (declare-function org-export-filter-apply-functions
"ox"
58 (declare-function org-export-first-sibling-p
"ox" (blob info
))
59 (declare-function org-export-get-backend
"ox" (name))
60 (declare-function org-export-get-environment
"ox"
61 (&optional backend subtreep ext-plist
))
62 (declare-function org-export-install-filters
"ox" (info))
63 (declare-function org-export-table-has-special-column-p
"ox" (table))
64 (declare-function org-export-table-row-is-special-p
"ox" (table-row info
))
66 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
68 (defvar constants-unit-system
)
69 (defvar org-element-use-cache
)
70 (defvar org-export-filters-alist
)
71 (defvar org-table-follow-field-mode
)
72 (defvar orgtbl-mode
) ; defined below
73 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
74 (defvar sort-fold-case
)
76 (defvar orgtbl-after-send-table-hook nil
77 "Hook for functions attaching to `C-c C-c', if the table is sent.
78 This can be used to add additional functionality after the table is sent
79 to the receiver position, otherwise, if table is not sent, the functions
82 (defvar org-table-TBLFM-begin-regexp
"^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
84 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
85 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
86 In the optimized version, the table editor takes over all simple keys that
87 normally just insert a character. In tables, the characters are inserted
88 in a way to minimize disturbing the table structure (i.e. in overwrite mode
89 for empty fields). Outside tables, the correct binding of the keys is
92 The default for this option is t if the optimized version is also used in
93 Org mode. See the variable `org-enable-table-editor' for details. Changing
94 this variable requires a restart of Emacs to become effective."
98 (defcustom orgtbl-radio-table-templates
99 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
100 % END RECEIVE ORGTBL %n
102 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
105 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
106 @c END RECEIVE ORGTBL %n
108 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
111 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
112 <!-- END RECEIVE ORGTBL %n -->
114 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
117 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
118 #+ END RECEIVE ORGTBL %n
120 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
123 "Templates for radio tables in different major modes.
124 Each template must define lines that will be treated as a comment and that
125 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
126 lines where \"%n\" will be replaced with the name of the table during
127 insertion of the template. The transformed table will later be inserted
130 The template should also contain a minimal table in a multiline comment.
131 If multiline comments are not possible in the buffer language,
132 you can pack it into a string that will not be used when the code
133 is compiled or executed. Above the table will you need a line with
134 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
135 convert the table into a data structure useful in the
136 language of the buffer. Check the manual for the section on
137 \"Translator functions\", and more generally check out
138 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
140 All occurrences of %n in a template will be replaced with the name of the
141 table, obtained by prompting the user."
144 (list (symbol :tag
"Major mode")
145 (string :tag
"Format"))))
147 (defgroup org-table-settings nil
148 "Settings for tables in Org mode."
149 :tag
"Org Table Settings"
152 (defcustom org-table-default-size
"5x2"
153 "The default size for newly created tables, Columns x Rows."
154 :group
'org-table-settings
157 (defcustom org-table-number-regexp
158 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
159 "Regular expression for recognizing numbers in table columns.
160 If a table column contains mostly numbers, it will be aligned to the
161 right. If not, it will be aligned to the left.
163 The default value of this option is a regular expression which allows
164 anything which looks remotely like a number as used in scientific
165 context. For example, all of the following will be considered a
167 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
169 Other options offered by the customize interface are more restrictive."
170 :group
'org-table-settings
172 (const :tag
"Positive Integers"
174 (const :tag
"Integers"
176 (const :tag
"Floating Point Numbers"
177 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
178 (const :tag
"Floating Point Number or Integer"
179 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
180 (const :tag
"Exponential, Floating point, Integer"
181 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
182 (const :tag
"Very General Number-Like, including hex and Calc radix"
183 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
184 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
185 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
186 (string :tag
"Regexp:")))
188 (defcustom org-table-number-fraction
0.5
189 "Fraction of numbers in a column required to make the column align right.
190 In a column all non-white fields are considered. If at least
191 this fraction of fields is matched by `org-table-number-regexp',
192 alignment to the right border applies."
193 :group
'org-table-settings
196 (defgroup org-table-editing nil
197 "Behavior of tables during editing in Org mode."
198 :tag
"Org Table Editing"
201 (defcustom org-table-automatic-realign t
202 "Non-nil means automatically re-align table when pressing TAB or RETURN.
203 When nil, aligning is only done with `\\[org-table-align]', or after column
205 :group
'org-table-editing
208 (defcustom org-table-auto-blank-field t
209 "Non-nil means automatically blank table field when starting to type into it.
210 This only happens when typing immediately after a field motion
211 command (TAB, S-TAB or RET).
212 Only relevant when `org-enable-table-editor' is equal to `optimized'."
213 :group
'org-table-editing
216 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
217 "Non-nil means automatically exit the follow mode.
218 When nil, the follow mode will stay on and be active in any table
219 the cursor enters. Since the table follow filed mode messes with the
220 window configuration, it is not recommended to set this variable to nil,
221 except maybe locally in a special file that has mostly tables with long
227 (defcustom org-table-fix-formulas-confirm nil
228 "Whether the user should confirm when Org fixes formulas."
229 :group
'org-table-editing
232 (const :tag
"with yes-or-no" yes-or-no-p
)
233 (const :tag
"with y-or-n" y-or-n-p
)
234 (const :tag
"no confirmation" nil
)))
235 (put 'org-table-fix-formulas-confirm
237 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
239 (defcustom org-table-tab-jumps-over-hlines t
240 "Non-nil means tab in the last column of a table with jump over a hline.
241 If a horizontal separator line is following the current line,
242 `org-table-next-field' can either create a new row before that line, or jump
243 over the line. When this option is nil, a new line will be created before
245 :group
'org-table-editing
248 (defgroup org-table-calculation nil
249 "Options concerning tables in Org mode."
250 :tag
"Org Table Calculation"
253 (defcustom org-table-use-standard-references
'from
254 "Non-nil means using table references like B3 instead of @3$2.
257 from accept as input, do not present for editing
258 t accept as input and present for editing"
259 :group
'org-table-calculation
261 (const :tag
"Never, don't even check user input for them" nil
)
262 (const :tag
"Always, both as user input, and when editing" t
)
263 (const :tag
"Convert user input, don't offer during editing" from
)))
265 (defcustom org-table-copy-increment t
266 "Non-nil means increment when copying current field with \
267 `\\[org-table-copy-down]'."
268 :group
'org-table-calculation
270 :package-version
'(Org .
"8.3")
272 (const :tag
"Use the difference between the current and the above fields" t
)
273 (integer :tag
"Use a number" 1)
274 (const :tag
"Don't increment the value when copying a field" nil
)))
276 (defcustom org-calc-default-modes
277 '(calc-internal-prec 12
278 calc-float-format
(float 8)
281 calc-symbolic-mode nil
282 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
283 calc-display-working-message t
285 "List with Calc mode settings for use in `calc-eval' for table formulas.
286 The list must contain alternating symbols (Calc modes variables and values).
287 Don't remove any of the default settings, just change the values. Org mode
288 relies on the variables to be present in the list."
289 :group
'org-table-calculation
292 (defcustom org-table-duration-custom-format
'hours
293 "Format for the output of calc computations like $1+$2;t.
294 The default value is `hours', and will output the results as a
295 number of hours. Other allowed values are `seconds', `minutes' and
296 `days', and the output will be a fraction of seconds, minutes or
298 :group
'org-table-calculation
300 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
301 (symbol :tag
"Minutes" 'minutes
)
302 (symbol :tag
"Hours " 'hours
)
303 (symbol :tag
"Days " 'days
)))
305 (defcustom org-table-formula-field-format
"%s"
306 "Format for fields which contain the result of a formula.
307 For example, using \"~%s~\" will display the result within tilde
308 characters. Beware that modifying the display can prevent the
309 field from being used in another formula."
310 :group
'org-table-settings
314 (defcustom org-table-formula-evaluate-inline t
315 "Non-nil means TAB and RET evaluate a formula in current table field.
316 If the current field starts with an equal sign, it is assumed to be a formula
317 which should be evaluated as described in the manual and in the documentation
318 string of the command `org-table-eval-formula'. This feature requires the
320 When this variable is nil, formula calculation is only available through
321 the command `\\[org-table-eval-formula]'."
322 :group
'org-table-calculation
325 (defcustom org-table-formula-use-constants t
326 "Non-nil means interpret constants in formulas in tables.
327 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
328 by the value given in `org-table-formula-constants', or by a value obtained
329 from the `constants.el' package."
330 :group
'org-table-calculation
333 (defcustom org-table-formula-constants nil
334 "Alist with constant names and values, for use in table formulas.
335 The car of each element is a name of a constant, without the `$' before it.
336 The cdr is the value as a string. For example, if you'd like to use the
337 speed of light in a formula, you would configure
339 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
341 and then use it in an equation like `$1*$c'.
343 Constants can also be defined on a per-file basis using a line like
345 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
346 :group
'org-table-calculation
348 (cons (string :tag
"name")
349 (string :tag
"value"))))
351 (defcustom org-table-allow-automatic-line-recalculation t
352 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
354 Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
355 are pressed in the line."
356 :group
'org-table-calculation
359 (defcustom org-table-relative-ref-may-cross-hline t
360 "Non-nil means relative formula references may cross hlines.
361 Here are the allowed values:
363 nil Relative references may not cross hlines. They will reference the
364 field next to the hline instead. Coming from below, the reference
365 will be to the field below the hline. Coming from above, it will be
367 t Relative references may cross hlines.
368 error An attempt to cross a hline will throw an error.
370 It is probably good to never set this variable to nil, for the sake of
371 portability of tables."
372 :group
'org-table-calculation
374 (const :tag
"Allow to cross" t
)
375 (const :tag
"Stick to hline" nil
)
376 (const :tag
"Error on attempt to cross" error
)))
378 (defcustom org-table-formula-create-columns nil
379 "Non-nil means that evaluation of a field formula can add new
380 columns if an out-of-bounds field is being set."
381 :group
'org-table-calculation
383 :package-version
'(Org .
"8.3")
385 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
386 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
387 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
388 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
390 (defgroup org-table-import-export nil
391 "Options concerning table import and export in Org mode."
392 :tag
"Org Table Import Export"
395 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
396 "Default export parameters for `org-table-export'.
397 These can be overridden for a specific table by setting the
398 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
399 radio tables for the different export transformations and
400 available parameters."
401 :group
'org-table-import-export
404 (defcustom org-table-convert-region-max-lines
999
405 "Max lines that `org-table-convert-region' will attempt to process.
407 The function can be slow on larger regions; this safety feature
408 prevents it from hanging emacs."
409 :group
'org-table-import-export
412 :package-version
'(Org .
"8.3"))
414 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
415 "Regexp matching a line marked for automatic recalculation.")
417 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
418 "Regexp matching a line marked for recalculation.")
420 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
421 "Regexp matching a line marked for calculation.")
423 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
424 "Regexp matching any line outside an Org table.")
426 (defvar org-table-last-highlighted-reference nil
)
428 (defvar org-table-formula-history nil
)
430 (defvar org-table-column-names nil
431 "Alist with column names, derived from the `!' line.
432 This variable is initialized with `org-table-analyze'.")
434 (defvar org-table-column-name-regexp nil
435 "Regular expression matching the current column names.
436 This variable is initialized with `org-table-analyze'.")
438 (defvar org-table-local-parameters nil
439 "Alist with parameter names, derived from the `$' line.
440 This variable is initialized with `org-table-analyze'.")
442 (defvar org-table-named-field-locations nil
443 "Alist with locations of named fields.
444 Associations follow the pattern (NAME LINE COLUMN) where
445 NAME is the name of the field as a string,
446 LINE is the number of lines from the beginning of the table,
447 COLUMN is the column of the field, as an integer.
448 This variable is initialized with `org-table-analyze'.")
450 (defvar org-table-current-line-types nil
451 "Table row types in current table.
452 This variable is initialized with `org-table-analyze'.")
454 (defvar org-table-current-begin-pos nil
455 "Current table begin position, as a marker.
456 This variable is initialized with `org-table-analyze'.")
458 (defvar org-table-current-ncol nil
459 "Number of columns in current table.
460 This variable is initialized with `org-table-analyze'.")
462 (defvar org-table-dlines nil
463 "Vector of data line line numbers in the current table.
464 Line numbers are counted from the beginning of the table. This
465 variable is initialized with `org-table-analyze'.")
467 (defvar org-table-hlines nil
468 "Vector of hline line numbers in the current table.
469 Line numbers are counted from the beginning of the table. This
470 variable is initialized with `org-table-analyze'.")
472 (defconst org-table-range-regexp
473 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
475 "Regular expression for matching ranges in formulas.")
477 (defconst org-table-range-regexp2
479 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
481 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
482 "Match a range for reference display.")
484 (defconst org-table-translate-regexp
485 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
486 "Match a reference that needs translation, for reference display.")
488 (defmacro org-table-save-field
(&rest body
)
489 "Save current field; execute BODY; restore field.
490 Field is restored even in case of abnormal exit."
491 (declare (debug (body)))
492 (org-with-gensyms (line column
)
493 `(let ((,line
(copy-marker (line-beginning-position)))
494 (,column
(org-table-current-column)))
498 (org-table-goto-column ,column
)
499 (set-marker ,line nil
)))))
502 (defun org-table-create-with-table.el
()
503 "Use the table.el package to insert a new table.
504 If there is already a table at point, convert between Org tables
505 and table.el tables."
510 (if (y-or-n-p "Convert table to Org table? ")
511 (org-table-convert)))
513 (when (y-or-n-p "Convert table to table.el table? ")
515 (org-table-convert)))
516 (t (call-interactively 'table-insert
))))
519 (defun org-table-create-or-convert-from-region (arg)
520 "Convert region to table, or create an empty table.
521 If there is an active region, convert it to a table, using the function
522 `org-table-convert-region'. See the documentation of that function
523 to learn how the prefix argument is interpreted to determine the field
525 If there is no such region, create an empty table with `org-table-create'."
527 (if (org-region-active-p)
528 (org-table-convert-region (region-beginning) (region-end) arg
)
529 (org-table-create arg
)))
532 (defun org-table-create (&optional size
)
533 "Query for a size and insert a table skeleton.
534 SIZE is a string Columns x Rows like for example \"3x2\"."
537 (setq size
(read-string
538 (concat "Table size Columns x Rows [e.g. "
539 org-table-default-size
"]: ")
540 "" nil org-table-default-size
)))
543 (indent (make-string (current-column) ?\
))
544 (split (org-split-string size
" *x *"))
545 (rows (string-to-number (nth 1 split
)))
546 (columns (string-to-number (car split
)))
547 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
549 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
550 (point-at-bol) (point)))
551 (beginning-of-line 1)
553 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
554 (dotimes (_ rows
) (insert line
))
557 ;; Insert a hline after the first row.
565 (defun org-table-convert-region (beg0 end0
&optional separator
)
566 "Convert region to a table.
568 The region goes from BEG0 to END0, but these borders will be moved
569 slightly, to make sure a beginning of line in the first line is included.
571 SEPARATOR specifies the field separator in the lines. It can have the
574 (4) Use the comma as a field separator
575 (16) Use a TAB as field separator
576 (64) Prompt for a regular expression as field separator
577 integer When a number, use that many spaces, or a TAB, as field separator
578 regexp When a regular expression, use it to match the separator
579 nil When nil, the command tries to be smart and figure out the
580 separator in the following way:
581 - when each line contains a TAB, assume TAB-separated material
582 - when each line contains a comma, assume CSV material
583 - else, assume one or more SPACE characters as separator."
585 (let* ((beg (min beg0 end0
))
586 (end (max beg0 end0
))
588 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
589 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
590 org-table-convert-region-max-lines
)
591 (if (equal separator
'(64))
592 (setq separator
(read-regexp "Regexp for field separator")))
594 (beginning-of-line 1)
595 (setq beg
(point-marker))
597 (if (bolp) (backward-char 1) (end-of-line 1))
598 (setq end
(point-marker))
599 ;; Get the right field separator
604 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
605 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
608 (if (equal separator
'(4))
609 (while (< (point) end
)
610 ;; parse the csv stuff
612 ((looking-at "^") (insert "| "))
613 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
614 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
615 (replace-match "\\1")
616 (if (looking-at "\"") (insert "\"")))
617 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
618 ((looking-at "[ \t]*,") (replace-match " | "))
619 (t (beginning-of-line 2))))
621 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
622 ((equal separator
'(16)) "^\\|\t")
623 ((integerp separator
)
625 (user-error "Number of spaces in separator must be >= 1")
626 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
628 (format "^ *\\|%s" separator
))
629 (t (error "This should not happen"))))
630 (while (re-search-forward re end t
)
631 (replace-match "| " t t
)))
636 (defun org-table-import (file arg
)
637 "Import FILE as a table.
638 The file is assumed to be tab-separated. Such files can be produced by most
639 spreadsheet and database applications. If no tabs (at least one per line)
640 are found, lines will be split on whitespace into fields."
642 (or (bolp) (newline))
645 (insert-file-contents file
)
646 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
650 (defun org-table-export (&optional file format
)
651 "Export table to a file, with configurable format.
652 Such a file can be imported into usual spreadsheet programs.
654 FILE can be the output file name. If not given, it will be taken
655 from a TABLE_EXPORT_FILE property in the current entry or higher
656 up in the hierarchy, or the user will be prompted for a file
657 name. FORMAT can be an export format, of the same kind as it
658 used when `orgtbl-mode' sends a table in a different format.
660 The command suggests a format depending on TABLE_EXPORT_FORMAT,
661 whether it is set locally or up in the hierarchy, then on the
662 extension of the given file name, and finally on the variable
663 `org-table-export-default-format'."
665 (unless (org-at-table-p) (user-error "No table at point"))
666 (org-table-align) ; Make sure we have everything we need.
667 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
669 (setq file
(read-file-name "Export table to: "))
670 (unless (or (not (file-exists-p file
))
671 (y-or-n-p (format "Overwrite file %s? " file
)))
672 (user-error "File not written")))
673 (when (file-directory-p file
)
674 (user-error "This is a directory path, not a file"))
675 (when (and (buffer-file-name (buffer-base-buffer))
678 (file-truename (buffer-file-name (buffer-base-buffer)))))
679 (user-error "Please specify a file name that is different from current"))
680 (let ((fileext (concat (file-name-extension file
) "$"))
681 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
683 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
684 "orgtbl-to-html" "orgtbl-to-generic"
685 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
686 "orgtbl-to-unicode"))
688 (replace-regexp-in-string
690 (replace-regexp-in-string
695 (and (string-match-p fileext f
) f
))
697 org-table-export-default-format
)
701 "Format: " formats nil nil deffmt-readable
))))
702 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
703 (let ((transform (intern (match-string 1 format
)))
704 (params (and (match-end 2)
705 (read (concat "(" (match-string 2 format
) ")"))))
706 (table (org-table-to-lisp
707 (buffer-substring-no-properties
708 (org-table-begin) (org-table-end)))))
709 (unless (fboundp transform
)
710 (user-error "No such transformation function %s" transform
))
712 (with-current-buffer (find-file-noselect file
)
713 (setq buf
(current-buffer))
716 (insert (funcall transform table params
) "\n")
719 (message "Export done."))
720 (user-error "TABLE_EXPORT_FORMAT invalid")))))
722 (defvar org-table-aligned-begin-marker
(make-marker)
723 "Marker at the beginning of the table last aligned.
724 Used to check if cursor still is in that table, to minimize realignment.")
725 (defvar org-table-aligned-end-marker
(make-marker)
726 "Marker at the end of the table last aligned.
727 Used to check if cursor still is in that table, to minimize realignment.")
728 (defvar org-table-last-alignment nil
729 "List of flags for flushright alignment, from the last re-alignment.
730 This is being used to correctly align a single field after TAB or RET.")
731 (defvar org-table-last-column-widths nil
732 "List of max width of fields in each column.
733 This is being used to correctly align a single field after TAB or RET.")
734 (defvar-local org-table-formula-debug nil
735 "Non-nil means debug table formulas.
736 When nil, simply write \"#ERROR\" in corrupted fields.")
737 (defvar-local org-table-overlay-coordinates nil
738 "Overlay coordinates after each align of a table.")
740 (defvar org-last-recalc-line nil
)
741 (defvar org-table-do-narrow t
) ; for dynamic scoping
742 (defconst org-narrow-column-arrow
"=>"
743 "Used as display property in narrowed table columns.")
746 (defun org-table-align ()
747 "Align the table at point by aligning all vertical bars."
749 (let* ((beg (org-table-begin))
750 (end (copy-marker (org-table-end))))
751 (org-table-save-field
752 ;; Make sure invisible characters in the table are at the right
753 ;; place since column widths take them into account.
754 (font-lock-fontify-region beg end
)
755 (move-marker org-table-aligned-begin-marker beg
)
756 (move-marker org-table-aligned-end-marker end
)
758 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
759 ;; Table's rows. Separators are replaced by nil. Trailing
760 ;; spaces are also removed.
761 (lines (mapcar (lambda (l)
762 (and (not (string-match-p "\\`[ \t]*|-" l
))
763 (let ((l (org-trim l
)))
764 (remove-text-properties
765 0 (length l
) '(display t org-cwidth t
) l
)
767 (org-split-string (buffer-substring beg end
) "\n")))
768 ;; Get the data fields by splitting the lines.
769 (fields (mapcar (lambda (l) (org-split-string l
" *| *"))
771 ;; Compute number of fields in the longest line. If the
772 ;; table contains no field, create a default table.
773 (maxfields (if fields
(apply #'max
(mapcar #'length fields
))
774 (kill-region beg end
)
775 (org-table-create org-table-default-size
)
776 (user-error "Empty table - created default table")))
777 ;; A list of empty strings to fill any short rows on output.
778 (emptycells (make-list maxfields
""))
780 ;; Check for special formatting.
781 (dotimes (i maxfields
)
782 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) fields
))
784 ;; Look for an explicit width or alignment.
785 (when (save-excursion
786 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t
)
787 (and org-table-do-narrow
789 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t
))))
791 (dolist (cell column
)
792 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell
)
793 (when (match-end 1) (setq falign
(match-string 1 cell
)))
794 (when (and org-table-do-narrow
(match-end 2))
795 (setq fmax
(string-to-number (match-string 2 cell
))))
796 (when (or falign fmax
) (throw :exit nil
)))))
797 ;; Find fields that are wider than FMAX, and shorten them.
800 (when (> (org-string-width x
) fmax
)
804 "Clipped table field, use `\\[org-table-edit-field]' to \
805 edit. Full value is:\n"
806 (substring-no-properties x
)))
809 (or (string-match org-bracket-link-regexp x
)
814 "Cannot narrow field starting with wide link \"%s\""
816 (if (= (org-string-width x
) l
) (setq f2 f1
)
818 (while (< (org-string-width (substring x
0 f2
)) f1
)
820 (add-text-properties f2 l
(list 'org-cwidth t
) x
)
822 (if (>= (string-width (substring x
(1- f2
) f2
)) 2) (1- f2
)
825 (list 'display org-narrow-column-arrow
)
827 ;; Get the maximum width for each column
828 (push (apply #'max
(or fmax
1) 1 (mapcar #'org-string-width column
))
830 ;; Get the fraction of numbers among non-empty cells to
831 ;; decide about alignment of the column.
832 (if falign
(push (equal (downcase falign
) "r") typenums
)
839 (if (string-match-p org-table-number-regexp x
)
843 (push (>= frac org-table-number-fraction
) typenums
)))))
844 (setq lengths
(nreverse lengths
))
845 (setq typenums
(nreverse typenums
))
846 ;; Store alignment of this table, for later editing of single
848 (setq org-table-last-alignment typenums
)
849 (setq org-table-last-column-widths lengths
)
850 ;; With invisible characters, `format' does not get the field
851 ;; width right So we need to make these fields wide by hand.
852 ;; Invisible characters may be introduced by fontified links,
853 ;; emphasis, macros or sub/superscripts.
854 (when (or (text-property-any beg end
'invisible
'org-link
)
855 (text-property-any beg end
'invisible t
))
856 (dotimes (i maxfields
)
857 (let ((len (nth i lengths
)))
858 (dotimes (j (length fields
))
859 (let* ((c (nthcdr i
(nth j fields
)))
863 (let ((l (length cell
)))
864 (or (text-property-any 0 l
'invisible
'org-link cell
)
865 (text-property-any beg end
'invisible t
)))
866 (< (org-string-width cell
) len
))
867 (let ((s (make-string (- len
(org-string-width cell
)) ?\s
)))
868 (setcar c
(if (nth i typenums
) (concat s cell
)
869 (concat cell s
))))))))))
871 ;; Compute the formats needed for output of the table.
872 (let ((hfmt (concat indent
"|"))
873 (rfmt (concat indent
"|"))
876 (dolist (l lengths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
877 (let ((ty (if (pop typenums
) "" "-"))) ; Flush numbers right.
878 (setq rfmt
(concat rfmt
(format rfmt1 ty l
)))
879 (setq hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
))))))
880 ;; Replace modified lines only. Check not only contents, but
881 ;; also columns' width.
884 (if l
(apply #'format rfmt
(append (pop fields
) emptycells
))
886 (previous (buffer-substring (point) (line-end-position))))
887 (if (and (equal previous line
)
891 (setq a
(next-single-property-change
892 a
'org-cwidth previous
))
893 (setq b
(next-single-property-change
894 b
'org-cwidth line
)))
899 (delete-region (point) (line-beginning-position 2))))))
900 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
901 (goto-char org-table-aligned-begin-marker
)
902 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
904 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
905 (setq org-table-may-need-update nil
)))))
908 (defun org-table-begin (&optional table-type
)
909 "Find the beginning of the table and return its position.
910 With a non-nil optional argument TABLE-TYPE, return the beginning
911 of a table.el-type table. This function assumes point is on
914 (org-element-property :post-affiliated
(org-element-at-point)))
916 (and (re-search-backward org-table-border-regexp nil t
)
917 (line-beginning-position 2))))
921 (defun org-table-end (&optional table-type
)
922 "Find the end of the table and return its position.
923 With a non-nil optional argument TABLE-TYPE, return the end of
924 a table.el-type table. This function assumes point is on
928 (goto-char (org-element-property :end
(org-element-at-point)))
929 (skip-chars-backward " \t\n")
930 (line-beginning-position 2))
931 ((re-search-forward org-table-border-regexp nil t
)
933 ;; When the line right after the table is the last line in
934 ;; the buffer with trailing spaces but no final newline
935 ;; character, be sure to catch the correct ending at its
936 ;; beginning. In any other case, ending is expected to be
938 (t (goto-char (point-max))
939 (skip-chars-backward " \t")
940 (if (bolp) (point) (line-end-position))))))
943 (defun org-table-justify-field-maybe (&optional new
)
944 "Justify the current field, text to left, number to right.
945 Optional argument NEW may specify text to replace the current field content."
947 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
948 ((org-at-table-hline-p))
950 (or (not (eq (marker-buffer org-table-aligned-begin-marker
)
952 (< (point) org-table-aligned-begin-marker
)
953 (>= (point) org-table-aligned-end-marker
)))
954 ;; This is not the same table, force a full re-align.
955 (setq org-table-may-need-update t
))
957 ;; Realign the current field, based on previous full realign.
959 (col (org-table-current-column)))
961 (skip-chars-backward "^|")
962 (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
963 (setq org-table-may-need-update t
)
964 (let* ((numbers?
(nth (1- col
) org-table-last-alignment
))
965 (cell (match-string 0))
966 (field (match-string 1))
967 (len (max 1 (- (org-string-width cell
) 3)))
968 (properly-closed?
(/= (match-beginning 2) (match-end 2)))
969 (fmt (format (if numbers?
" %%%ds %s" " %%-%ds %s")
971 (if properly-closed?
"|"
972 (setq org-table-may-need-update t
)
975 (cond ((not new
) (format fmt field
))
976 ((<= (org-string-width new
) len
) (format fmt new
))
978 (setq org-table-may-need-update t
)
979 (format " %s |" new
)))))
980 (unless (equal new-cell cell
)
981 (let (org-table-may-need-update)
982 (replace-match new-cell t t
)))
983 (goto-char pos
))))))))
986 (defun org-table-next-field ()
987 "Go to the next field in the current table, creating new lines as needed.
988 Before doing so, re-align the table if necessary."
990 (org-table-maybe-eval-formula)
991 (org-table-maybe-recalculate-line)
992 (if (and org-table-automatic-realign
993 org-table-may-need-update
)
995 (let ((end (org-table-end)))
996 (if (org-at-table-hline-p)
1000 (re-search-forward "|" end
)
1001 (if (looking-at "[ \t]*$")
1002 (re-search-forward "|" end
))
1003 (if (and (looking-at "-")
1004 org-table-tab-jumps-over-hlines
1005 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1006 (goto-char (match-beginning 1)))
1007 (if (looking-at "-")
1009 (beginning-of-line 0)
1010 (org-table-insert-row 'below
))
1011 (if (looking-at " ") (forward-char 1))))
1013 (org-table-insert-row 'below
)))))
1016 (defun org-table-previous-field ()
1017 "Go to the previous field in the table.
1018 Before doing so, re-align the table if necessary."
1020 (org-table-justify-field-maybe)
1021 (org-table-maybe-recalculate-line)
1022 (if (and org-table-automatic-realign
1023 org-table-may-need-update
)
1025 (if (org-at-table-hline-p)
1029 (re-search-backward "|" (org-table-begin))
1030 (re-search-backward "|" (org-table-begin)))
1031 (error (user-error "Cannot move to previous table field")))
1032 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1033 (re-search-backward "|" (org-table-begin)))
1034 (if (looking-at "| ?")
1035 (goto-char (match-end 0))))
1037 (defun org-table-beginning-of-field (&optional n
)
1038 "Move to the beginning of the current table field.
1039 If already at or before the beginning, move to the beginning of the
1041 With numeric argument N, move N-1 fields backward first."
1043 (let ((pos (point)))
1046 (org-table-previous-field))
1047 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1048 (user-error "No more table fields before the current")
1049 (goto-char (match-end 0))
1050 (and (looking-at " ") (forward-char 1)))
1051 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1053 (defun org-table-end-of-field (&optional n
)
1054 "Move to the end of the current table field.
1055 If already at or after the end, move to the end of the next table field.
1056 With numeric argument N, move N-1 fields forward first."
1058 (let ((pos (point)))
1061 (org-table-next-field))
1062 (when (re-search-forward "|" (point-at-eol 1) t
)
1064 (skip-chars-backward " ")
1065 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1067 (if (<= (point) pos
) (org-table-end-of-field 2))))
1070 (defun org-table-next-row ()
1071 "Go to the next row (same column) in the current table.
1072 Before doing so, re-align the table if necessary."
1074 (org-table-maybe-eval-formula)
1075 (org-table-maybe-recalculate-line)
1076 (if (or (looking-at "[ \t]*$")
1077 (save-excursion (skip-chars-backward " \t") (bolp)))
1079 (if (and org-table-automatic-realign
1080 org-table-may-need-update
)
1082 (let ((col (org-table-current-column)))
1083 (beginning-of-line 2)
1084 (if (or (not (org-at-table-p))
1085 (org-at-table-hline-p))
1087 (beginning-of-line 0)
1088 (org-table-insert-row 'below
)))
1089 (org-table-goto-column col
)
1090 (skip-chars-backward "^|\n\r")
1091 (if (looking-at " ") (forward-char 1)))))
1094 (defun org-table-copy-down (n)
1095 "Copy the value of the current field one row below.
1097 If the field at the cursor is empty, copy the content of the
1098 nearest non-empty field above. With argument N, use the Nth
1101 If the current field is not empty, it is copied down to the next
1102 row, and the cursor is moved with it. Therefore, repeating this
1103 command causes the column to be filled row-by-row.
1105 If the variable `org-table-copy-increment' is non-nil and the
1106 field is an integer or a timestamp, it will be incremented while
1107 copying. By default, increment by the difference between the
1108 value in the current field and the one in the field above. To
1109 increment using a fixed integer, set `org-table-copy-increment'
1110 to a number. In the case of a timestamp, increment by days."
1112 (let* ((colpos (org-table-current-column))
1113 (col (current-column))
1114 (field (save-excursion (org-table-get-field)))
1115 (field-up (or (save-excursion
1116 (org-table-get (1- (org-table-current-line))
1117 (org-table-current-column))) ""))
1118 (non-empty (string-match "[^ \t]" field
))
1119 (non-empty-up (string-match "[^ \t]" field-up
))
1120 (beg (org-table-begin))
1123 (org-table-check-inside-data-field)
1128 (while (progn (beginning-of-line 1)
1129 (re-search-backward org-table-dataline-regexp
1131 (org-table-goto-column colpos t
)
1132 (if (and (looking-at
1133 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1134 (<= (setq n
(1- n
)) 0))
1135 (throw 'exit
(match-string 1))))))
1138 (while (progn (beginning-of-line 1)
1139 (re-search-backward org-table-dataline-regexp
1141 (org-table-goto-column colpos t
)
1142 (if (and (looking-at
1143 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1144 (<= (setq n
(1- n
)) 0))
1145 (throw 'exit
(match-string 1))))))
1146 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1147 ;; Above field was not empty, go down to the next row
1148 (setq txt
(org-trim field
))
1149 (org-table-next-row)
1150 (org-table-blank-field))
1151 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1153 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1154 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1155 (string-match org-ts-regexp3 txt
))
1156 (- (org-time-string-to-absolute txt
)
1157 (org-time-string-to-absolute txt-up
)))
1158 ((string-match org-ts-regexp3 txt
) 1)
1159 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1160 (- (string-to-number txt
)
1161 (string-to-number (match-string 0 txt-up
))))
1165 (user-error "No non-empty field found")
1166 (if (and org-table-copy-increment
1167 (not (equal orig-n
0))
1168 (string-match-p "^[-+^/*0-9eE.]+$" txt
)
1169 (< (string-to-number txt
) 100000000))
1170 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1172 (org-move-to-column col
)
1173 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1174 (org-timestamp-up-day inc
)
1175 (org-table-maybe-recalculate-line))
1177 (org-move-to-column col
))))
1179 (defun org-table-check-inside-data-field (&optional noerror
)
1180 "Is point inside a table data field?
1181 I.e. not on a hline or before the first or after the last column?
1182 This actually throws an error, so it aborts the current command."
1183 (cond ((and (org-at-table-p)
1184 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1185 (not (org-at-table-hline-p))
1186 (not (looking-at "[ \t]*$"))))
1188 (t (user-error "Not in table data field"))))
1190 (defvar org-table-clip nil
1191 "Clipboard for table regions.")
1193 (defun org-table-get (line column
)
1194 "Get the field in table line LINE, column COLUMN.
1195 If LINE is larger than the number of data lines in the table, the function
1196 returns nil. However, if COLUMN is too large, we will simply return an
1198 If LINE is nil, use the current line.
1199 If COLUMN is nil, use the current column."
1200 (setq column
(or column
(org-table-current-column)))
1202 (and (or (not line
) (org-table-goto-line line
))
1203 (org-trim (org-table-get-field column
)))))
1205 (defun org-table-put (line column value
&optional align
)
1206 "Put VALUE into line LINE, column COLUMN.
1207 When ALIGN is set, also realign the table."
1208 (setq column
(or column
(org-table-current-column)))
1209 (prog1 (save-excursion
1210 (and (or (not line
) (org-table-goto-line line
))
1211 (progn (org-table-goto-column column nil
'force
) t
)
1212 (org-table-get-field column value
)))
1213 (and align
(org-table-align))))
1215 (defun org-table-current-line ()
1216 "Return the index of the current data line."
1217 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1219 (goto-char (org-table-begin))
1220 (while (and (re-search-forward org-table-dataline-regexp end t
)
1222 (< (point-at-eol) pos
))))
1225 (defun org-table-goto-line (N)
1226 "Go to the Nth data line in the current table.
1227 Return t when the line exists, nil if it does not exist."
1228 (goto-char (org-table-begin))
1229 (let ((end (org-table-end)) (cnt 0))
1230 (while (and (re-search-forward org-table-dataline-regexp end t
)
1231 (< (setq cnt
(1+ cnt
)) N
)))
1235 (defun org-table-blank-field ()
1236 "Blank the current table field or active region."
1238 (org-table-check-inside-data-field)
1239 (if (and (called-interactively-p 'any
) (org-region-active-p))
1240 (let (org-table-clip)
1241 (org-table-cut-region (region-beginning) (region-end)))
1242 (skip-chars-backward "^|")
1244 (if (looking-at "|[^|\n]+")
1245 (let* ((pos (match-beginning 0))
1246 (match (match-string 0))
1247 (len (org-string-width match
)))
1248 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1249 (goto-char (+ 2 pos
))
1250 (substring match
1)))))
1252 (defun org-table-get-field (&optional n replace
)
1253 "Return the value of the field in column N of current row.
1254 N defaults to current column. If REPLACE is a string, replace
1255 field with this value. The return value is always the old
1257 (when n
(org-table-goto-column n
))
1258 (skip-chars-backward "^|\n")
1259 (if (or (bolp) (looking-at-p "[ \t]*$"))
1260 ;; Before first column or after last one.
1262 (looking-at "[^|\r\n]*")
1263 (let* ((pos (match-beginning 0))
1264 (val (buffer-substring pos
(match-end 0))))
1266 (replace-match (if (equal replace
"") " " replace
) t t
))
1267 (goto-char (min (line-end-position) (1+ pos
)))
1271 (defun org-table-field-info (_arg)
1272 "Show info about the current field, and highlight any reference at point."
1274 (unless (org-at-table-p) (user-error "Not at a table"))
1277 (let* ((pos (point))
1278 (col (org-table-current-column))
1279 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1280 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1281 (line-beginning-position))
1283 org-table-named-field-locations
)))
1284 (eql (org-table-expand-lhs-ranges
1287 (cons (org-table-formula-handle-first/last-rc
(car e
))
1289 (org-table-get-stored-formulas))))
1290 (dline (org-table-current-dline))
1291 (ref (format "@%d$%d" dline col
))
1292 (ref1 (org-table-convert-refs-to-an ref
))
1293 ;; Prioritize field formulas over column formulas.
1294 (fequation (or (assoc name eql
) (assoc ref eql
)))
1295 (cequation (assoc (format "$%d" col
) eql
))
1296 (eqn (or fequation cequation
)))
1297 (let ((p (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))))
1298 (when p
(setq eqn p
)))
1300 (ignore-errors (org-table-show-reference 'local
))
1301 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1303 (if cname
(concat " or $" cname
) "")
1305 (if name
(concat " or $" name
) "")
1306 ;; FIXME: formula info not correct if special table line
1308 (concat ", formula: "
1309 (org-table-formula-to-user
1311 (if (or (string-prefix-p "$" (car eqn
))
1312 (string-prefix-p "@" (car eqn
)))
1315 (car eqn
) "=" (cdr eqn
))))
1318 (defun org-table-current-column ()
1319 "Find out which column we are in."
1322 (let ((column 0) (pos (point)))
1324 (while (search-forward "|" pos t
) (cl-incf column
))
1327 (defun org-table-current-dline ()
1328 "Find out what table data line we are in.
1329 Only data lines count for this."
1333 (goto-char (org-table-begin))
1334 (while (<= (point) pos
)
1335 (when (looking-at org-table-dataline-regexp
) (cl-incf c
))
1340 (defun org-table-goto-column (n &optional on-delim force
)
1341 "Move the cursor to the Nth column in the current table line.
1342 With optional argument ON-DELIM, stop with point before the left delimiter
1344 If there are less than N fields, just go to after the last delimiter.
1345 However, when FORCE is non-nil, create new columns if necessary."
1347 (beginning-of-line 1)
1349 (while (and (> (setq n
(1- n
)) -
1)
1350 (or (search-forward "|" (point-at-eol) t
)
1352 (progn (end-of-line 1)
1353 (skip-chars-backward "^|")
1356 (when (and force
(not (looking-at ".*|")))
1357 (save-excursion (end-of-line 1) (insert " | ")))
1360 (if (looking-at " ") (forward-char 1)))))
1363 (defun org-table-insert-column ()
1364 "Insert a new column into the table."
1366 (unless (org-at-table-p) (user-error "Not at a table"))
1367 (org-table-find-dataline)
1368 (let* ((col (max 1 (org-table-current-column)))
1369 (beg (org-table-begin))
1370 (end (copy-marker (org-table-end))))
1371 (org-table-save-field
1373 (while (< (point) end
)
1374 (unless (org-at-table-hline-p)
1375 (org-table-goto-column col t
)
1378 (set-marker end nil
)
1380 (when (or (not org-table-fix-formulas-confirm
)
1381 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1382 (org-table-fix-formulas "$" nil
(1- col
) 1)
1383 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1385 (defun org-table-find-dataline ()
1386 "Find a data line in the current table, which is needed for column commands."
1387 (if (and (org-at-table-p)
1388 (not (org-at-table-hline-p)))
1390 (let ((col (current-column))
1391 (end (org-table-end)))
1392 (org-move-to-column col
)
1393 (while (and (< (point) end
)
1394 (or (not (= (current-column) col
))
1395 (org-at-table-hline-p)))
1396 (beginning-of-line 2)
1397 (org-move-to-column col
))
1398 (if (and (org-at-table-p)
1399 (not (org-at-table-hline-p)))
1402 "Please position cursor in a data line for column operations")))))
1404 (defun org-table-line-to-dline (line &optional above
)
1405 "Turn a buffer line number into a data line number.
1407 If there is no data line in this line, return nil.
1409 If there is no matching dline (most likely the reference was
1410 a hline), the first dline below it is used. When ABOVE is
1411 non-nil, the one above is used."
1413 (max (1- (length org-table-dlines
))))
1414 (cond ((or (> (aref org-table-dlines min
) line
)
1415 (< (aref org-table-dlines max
) line
))
1417 ((= (aref org-table-dlines max
) line
) max
)
1419 (while (> (- max min
) 1)
1420 (let* ((mean (/ (+ max min
) 2))
1421 (v (aref org-table-dlines mean
)))
1422 (cond ((= v line
) (throw 'exit mean
))
1423 ((> v line
) (setq max mean
))
1424 (t (setq min mean
)))))
1425 (if above min max
))))))
1428 (defun org-table-delete-column ()
1429 "Delete a column from the table."
1431 (unless (org-at-table-p) (user-error "Not at a table"))
1432 (org-table-find-dataline)
1433 (org-table-check-inside-data-field)
1434 (let ((col (org-table-current-column))
1435 (beg (org-table-begin))
1436 (end (copy-marker (org-table-end))))
1437 (org-table-save-field
1439 (while (< (point) end
)
1440 (if (org-at-table-hline-p)
1442 (org-table-goto-column col t
)
1443 (and (looking-at "|[^|\n]+|")
1444 (replace-match "|")))
1446 (set-marker end nil
)
1447 (org-table-goto-column (max 1 (1- col
)))
1449 (when (or (not org-table-fix-formulas-confirm
)
1450 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1451 (org-table-fix-formulas
1452 "$" (list (cons (number-to-string col
) "INVALID")) col -
1 col
)
1453 (org-table-fix-formulas
1454 "$LR" (list (cons (number-to-string col
) "INVALID")) col -
1 col
))))
1457 (defun org-table-move-column-right ()
1458 "Move column to the right."
1460 (org-table-move-column nil
))
1462 (defun org-table-move-column-left ()
1463 "Move column to the left."
1465 (org-table-move-column 'left
))
1468 (defun org-table-move-column (&optional left
)
1469 "Move the current column to the right. With arg LEFT, move to the left."
1471 (unless (org-at-table-p) (user-error "Not at a table"))
1472 (org-table-find-dataline)
1473 (org-table-check-inside-data-field)
1474 (let* ((col (org-table-current-column))
1475 (col1 (if left
(1- col
) col
))
1476 (colpos (if left
(1- col
) (1+ col
)))
1477 (beg (org-table-begin))
1478 (end (copy-marker (org-table-end))))
1479 (when (and left
(= col
1))
1480 (user-error "Cannot move column further left"))
1481 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1482 (user-error "Cannot move column further right"))
1483 (org-table-save-field
1485 (while (< (point) end
)
1486 (unless (org-at-table-hline-p)
1487 (org-table-goto-column col1 t
)
1488 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1489 (replace-match "|\\2|\\1|")))
1491 (set-marker end nil
)
1492 (org-table-goto-column colpos
)
1494 (when (or (not org-table-fix-formulas-confirm
)
1495 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1496 (org-table-fix-formulas
1497 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1498 (cons (number-to-string colpos
) (number-to-string col
))))
1499 (org-table-fix-formulas
1500 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1501 (cons (number-to-string colpos
) (number-to-string col
)))))))
1504 (defun org-table-move-row-down ()
1505 "Move table row down."
1507 (org-table-move-row nil
))
1509 (defun org-table-move-row-up ()
1510 "Move table row up."
1512 (org-table-move-row 'up
))
1515 (defun org-table-move-row (&optional up
)
1516 "Move the current table line down. With arg UP, move it up."
1518 (let* ((col (current-column))
1520 (hline1p (save-excursion (beginning-of-line 1)
1521 (looking-at org-table-hline-regexp
)))
1522 (dline1 (org-table-current-dline))
1523 (dline2 (+ dline1
(if up -
1 1)))
1526 (beginning-of-line tonew
)
1527 (unless (org-at-table-p)
1529 (user-error "Cannot move row further"))
1530 (setq hline2p
(looking-at org-table-hline-regexp
))
1532 (beginning-of-line 1)
1534 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1535 (delete-region (point) (1+ (point-at-eol)))
1536 (beginning-of-line tonew
)
1538 (beginning-of-line 0)
1539 (org-move-to-column col
)
1540 (unless (or hline1p hline2p
1541 (not (or (not org-table-fix-formulas-confirm
)
1542 (funcall org-table-fix-formulas-confirm
1543 "Fix formulas? "))))
1544 (org-table-fix-formulas
1545 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1546 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1549 (defun org-table-insert-row (&optional arg
)
1550 "Insert a new row above the current line into the table.
1551 With prefix ARG, insert below the current line."
1553 (unless (org-at-table-p) (user-error "Not at a table"))
1554 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1555 (new (org-table-clean-line line
)))
1556 ;; Fix the first field if necessary
1557 (if (string-match "^[ \t]*| *[#$] *|" line
)
1558 (setq new
(replace-match (match-string 0 line
) t t new
)))
1559 (beginning-of-line (if arg
2 1))
1560 ;; Buffer may not end of a newline character, so ensure
1561 ;; (beginning-of-line 2) moves point to a new line.
1562 (unless (bolp) (insert "\n"))
1563 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1564 (beginning-of-line 0)
1565 (re-search-forward "| ?" (line-end-position) t
)
1566 (when (or org-table-may-need-update org-table-overlay-coordinates
)
1568 (when (or (not org-table-fix-formulas-confirm
)
1569 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1570 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1573 (defun org-table-insert-hline (&optional above
)
1574 "Insert a horizontal-line below the current line into the table.
1575 With prefix ABOVE, insert above the current line."
1577 (if (not (org-at-table-p))
1578 (user-error "Not at a table"))
1579 (when (eobp) (insert "\n") (backward-char 1))
1580 (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
1582 (let ((line (org-table-clean-line
1583 (buffer-substring (point-at-bol) (point-at-eol))))
1584 (col (current-column)))
1585 (while (string-match "|\\( +\\)|" line
)
1586 (setq line
(replace-match
1587 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1588 ?-
) "|") t t line
)))
1589 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1590 (beginning-of-line (if above
1 2))
1592 (beginning-of-line (if above
1 -
1))
1593 (org-move-to-column col
)
1594 (and org-table-overlay-coordinates
(org-table-align))))
1597 (defun org-table-hline-and-move (&optional same-column
)
1598 "Insert a hline and move to the row below that line."
1600 (let ((col (org-table-current-column)))
1601 (org-table-maybe-eval-formula)
1602 (org-table-maybe-recalculate-line)
1603 (org-table-insert-hline)
1605 (if (looking-at "\n[ \t]*|-")
1606 (progn (insert "\n|") (org-table-align))
1607 (org-table-next-field))
1608 (if same-column
(org-table-goto-column col
))))
1610 (defun org-table-clean-line (s)
1611 "Convert a table line S into a string with only \"|\" and space.
1612 In particular, this does handle wide and invisible characters."
1613 (if (string-match "^[ \t]*|-" s
)
1614 ;; It's a hline, just map the characters
1615 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1616 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1617 (setq s
(replace-match
1618 (concat "|" (make-string (org-string-width (match-string 1 s
))
1624 (defun org-table-kill-row ()
1625 "Delete the current row or horizontal line from the table."
1627 (if (not (org-at-table-p))
1628 (user-error "Not at a table"))
1629 (let ((col (current-column))
1630 (dline (org-table-current-dline)))
1631 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1632 (if (not (org-at-table-p)) (beginning-of-line 0))
1633 (org-move-to-column col
)
1634 (when (or (not org-table-fix-formulas-confirm
)
1635 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1636 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1640 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func
)
1641 "Sort table lines according to the column at point.
1643 The position of point indicates the column to be used for
1644 sorting, and the range of lines is the range between the nearest
1645 horizontal separator lines, or the entire table of no such lines
1646 exist. If point is before the first column, you will be prompted
1647 for the sorting column. If there is an active region, the mark
1648 specifies the first line and the sorting column, while point
1649 should be in the last line to be included into the sorting.
1651 The command then prompts for the sorting type which can be
1652 alphabetically, numerically, or by time (as given in a time stamp
1653 in the field, or as a HH:MM value). Sorting in reverse order is
1656 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1658 If SORTING-TYPE is specified when this function is called from a Lisp
1659 program, no prompting will take place. SORTING-TYPE must be a character,
1660 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1661 sorting should be done in reverse order.
1663 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1664 a function to be called to extract the key. It must return either
1665 a string or a number that should serve as the sorting key for that
1666 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1667 is specified interactively, the comparison will be either a string or
1668 numeric compare based on the type of the first key in the table."
1670 (when (org-region-active-p) (goto-char (region-beginning)))
1671 ;; Point must be either within a field or before a data line.
1673 (skip-chars-backward " \t")
1674 (when (bolp) (search-forward "|" (line-end-position) t
))
1675 (org-table-check-inside-data-field))
1676 ;; Set appropriate case sensitivity and column used for sorting.
1677 (let ((column (let ((c (org-table-current-column)))
1679 ((called-interactively-p 'any
)
1680 (read-number "Use column N for sorting: "))
1684 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1685 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1687 ;; Narrow buffer to appropriate sorting area.
1688 (if (org-region-active-p)
1689 (progn (goto-char (region-beginning))
1692 (save-excursion (goto-char (region-end))
1693 (line-beginning-position 2))))
1694 (let ((start (org-table-begin))
1695 (end (org-table-end)))
1698 (if (re-search-backward org-table-hline-regexp start t
)
1699 (line-beginning-position 2)
1701 (if (save-excursion (re-search-forward org-table-hline-regexp end t
))
1704 ;; Determine arguments for `sort-subr'. Also record original
1705 ;; position. `org-table-save-field' cannot help here since
1706 ;; sorting is too much destructive.
1707 (let* ((sort-fold-case (not with-case
))
1709 (cons (count-lines (point-min) (line-beginning-position))
1711 (extract-key-from-field
1712 ;; Function to be called on the contents of the field
1713 ;; used for sorting in the current row.
1714 (cl-case sorting-type
1715 ((?n ?N
) #'string-to-number
)
1716 ((?a ?A
) #'org-sort-remove-invisible
)
1719 (cond ((string-match org-ts-regexp-both f
)
1721 (org-time-string-to-time (match-string 0 f
))))
1722 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" f
)
1723 (org-hh:mm-string-to-minutes f
))
1727 (and (called-interactively-p 'any
)
1729 (completing-read "Sort using function: "
1730 obarray
#'fboundp t
)))
1731 (error "Missing key extractor to sort rows")))
1732 (t (user-error "Invalid sorting type `%c'" sorting-type
))))
1734 (cl-case sorting-type
1737 ((?f ?F
) compare-func
))))
1738 (goto-char (point-min))
1739 (sort-subr (memq sorting-type
'(?A ?N ?T ?F
))
1742 (while (and (not (eobp))
1743 (not (looking-at org-table-dataline-regexp
)))
1747 (funcall extract-key-from-field
1748 (org-trim (org-table-get-field column
))))
1751 ;; Move back to initial field.
1752 (forward-line (car coordinates
))
1753 (move-to-column (cdr coordinates
))))))
1756 (defun org-table-cut-region (beg end
)
1757 "Copy region in table to the clipboard and blank all relevant fields.
1758 If there is no active region, use just the field at point."
1760 (if (org-region-active-p) (region-beginning) (point))
1761 (if (org-region-active-p) (region-end) (point))))
1762 (org-table-copy-region beg end
'cut
))
1765 (defun org-table-copy-region (beg end
&optional cut
)
1766 "Copy rectangular region in table to clipboard.
1767 A special clipboard is used which can only be accessed
1768 with `org-table-paste-rectangle'."
1770 (if (org-region-active-p) (region-beginning) (point))
1771 (if (org-region-active-p) (region-end) (point))
1772 current-prefix-arg
))
1773 (goto-char (min beg end
))
1774 (org-table-check-inside-data-field)
1775 (let ((beg (line-beginning-position))
1776 (c01 (org-table-current-column))
1778 (goto-char (max beg end
))
1779 (org-table-check-inside-data-field)
1780 (let* ((end (copy-marker (line-end-position)))
1781 (c02 (org-table-current-column))
1782 (column-start (min c01 c02
))
1783 (column-end (max c01 c02
))
1784 (column-number (1+ (- column-end column-start
)))
1785 (rpl (and cut
" ")))
1787 (while (< (point) end
)
1788 (unless (org-at-table-hline-p)
1789 ;; Collect every cell between COLUMN-START and COLUMN-END.
1791 (dotimes (c column-number
)
1792 (push (org-table-get-field (+ c column-start
) rpl
) cols
))
1793 (push (nreverse cols
) region
)))
1795 (set-marker end nil
))
1796 (when cut
(org-table-align))
1797 (setq org-table-clip
(nreverse region
))))
1800 (defun org-table-paste-rectangle ()
1801 "Paste a rectangular region into a table.
1802 The upper right corner ends up in the current field. All involved fields
1803 will be overwritten. If the rectangle does not fit into the present table,
1804 the table is enlarged as needed. The process ignores horizontal separator
1807 (unless (consp org-table-clip
)
1808 (user-error "First cut/copy a region to paste!"))
1809 (org-table-check-inside-data-field)
1810 (let* ((column (org-table-current-column))
1811 (org-enable-table-editor t
)
1812 (org-table-automatic-realign nil
))
1813 (org-table-save-field
1814 (dolist (row org-table-clip
)
1815 (while (org-at-table-hline-p) (forward-line))
1816 ;; If we left the table, create a new row.
1817 (when (and (bolp) (not (looking-at "[ \t]*|")))
1819 (org-table-next-field))
1822 (org-table-goto-column c nil
'force
)
1823 (org-table-get-field nil field
)
1829 (defun org-table-convert ()
1830 "Convert from `org-mode' table to table.el and back.
1831 Obviously, this only works within limits. When an Org table is converted
1832 to table.el, all horizontal separator lines get lost, because table.el uses
1833 these as cell boundaries and has no notion of horizontal lines. A table.el
1834 table can be converted to an Org table only if it does not do row or column
1835 spanning. Multiline cells will become multiple cells. Beware, Org mode
1836 does not test if the table can be successfully converted - it blindly
1837 applies a recipe that works for simple tables."
1840 (if (org-at-table.el-p
)
1841 ;; convert to Org table
1842 (let ((beg (copy-marker (org-table-begin t
)))
1843 (end (copy-marker (org-table-end t
))))
1844 (table-unrecognize-region beg end
)
1846 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1849 (if (org-at-table-p)
1850 ;; convert to table.el table
1851 (let ((beg (copy-marker (org-table-begin)))
1852 (end (copy-marker (org-table-end))))
1853 ;; first, get rid of all horizontal lines
1855 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1857 ;; insert a hline before first
1859 (org-table-insert-hline 'above
)
1860 (beginning-of-line -
1)
1861 ;; insert a hline after each line
1862 (while (progn (beginning-of-line 3) (< (point) end
))
1863 (org-table-insert-hline))
1865 (setq end
(move-marker end
(org-table-end)))
1866 ;; replace "+" at beginning and ending of hlines
1867 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1868 (replace-match "\\1+-"))
1870 (while (re-search-forward "-|[ \t]*$" end t
)
1871 (replace-match "-+"))
1874 (defun org-table-transpose-table-at-point ()
1875 "Transpose Org table at point and eliminate hlines.
1883 will be transposed as
1890 Note that horizontal lines disappear."
1892 (let* ((table (delete 'hline
(org-table-to-lisp)))
1893 (dline_old (org-table-current-line))
1894 (col_old (org-table-current-column))
1895 (contents (mapcar (lambda (_)
1901 (setq tp
(cdr tp
))))
1904 (goto-char (org-table-begin))
1905 (re-search-forward "|")
1907 (delete-region (point) (org-table-end))
1910 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1912 (org-table-goto-line col_old
)
1913 (org-table-goto-column dline_old
))
1917 (defun org-table-wrap-region (arg)
1918 "Wrap several fields in a column like a paragraph.
1919 This is useful if you'd like to spread the contents of a field over several
1920 lines, in order to keep the table compact.
1922 If there is an active region, and both point and mark are in the same column,
1923 the text in the column is wrapped to minimum width for the given number of
1924 lines. Generally, this makes the table more compact. A prefix ARG may be
1925 used to change the number of desired lines. For example, \
1926 `C-2 \\[org-table-wrap-region]'
1927 formats the selected text to two lines. If the region was longer than two
1928 lines, the remaining lines remain empty. A negative prefix argument reduces
1929 the current number of lines by that amount. The wrapped text is pasted back
1930 into the table. If you formatted it to more lines than it was before, fields
1931 further down in the table get overwritten - so you might need to make space in
1934 If there is no region, the current field is split at the cursor position and
1935 the text fragment to the right of the cursor is prepended to the field one
1938 If there is no region, but you specify a prefix ARG, the current field gets
1939 blank, and the content is appended to the field above."
1941 (org-table-check-inside-data-field)
1942 (if (org-region-active-p)
1943 ;; There is a region: fill as a paragraph.
1944 (let ((start (region-beginning)))
1945 (org-table-cut-region (region-beginning) (region-end))
1946 (when (> (length (car org-table-clip
)) 1)
1947 (user-error "Region must be limited to single column"))
1948 (let ((nlines (cond ((not arg
) (length org-table-clip
))
1949 ((< arg
1) (+ (length org-table-clip
) arg
))
1951 (setq org-table-clip
1953 (org-wrap (mapconcat #'car org-table-clip
" ")
1957 (org-table-paste-rectangle))
1958 ;; No region, split the current field at point.
1959 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1960 (skip-chars-forward "^\r\n|"))
1962 (arg ; Combine with field above.
1963 (let ((s (org-table-blank-field))
1964 (col (org-table-current-column)))
1966 (while (org-at-table-hline-p) (forward-line -
1))
1967 (org-table-goto-column col
)
1968 (skip-chars-forward "^|")
1969 (skip-chars-backward " ")
1970 (insert " " (org-trim s
))
1972 ((looking-at "\\([^|]+\\)+|") ; Split field.
1973 (let ((s (match-string 1)))
1974 (replace-match " |")
1975 (goto-char (match-beginning 0))
1976 (org-table-next-row)
1977 (insert (org-trim s
) " ")
1979 (t (org-table-next-row)))))
1981 (defvar org-field-marker nil
)
1984 (defun org-table-edit-field (arg)
1985 "Edit table field in a different window.
1986 This is mainly useful for fields that contain hidden parts.
1988 When called with a `\\[universal-argument]' prefix, just make the full field
1989 visible so that it can be edited in place.
1991 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
1992 toggle `org-table-follow-field-mode'."
1994 (unless (org-at-table-p) (user-error "Not at a table"))
1997 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1999 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2000 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2001 (remove-text-properties b e
'(org-cwidth t invisible t
2002 display t intangible t
))
2003 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2004 (font-lock-fontify-block))))
2006 (let ((pos (point-marker))
2008 (if (eq org-table-use-standard-references t
)
2009 (concat (org-number-to-letters (org-table-current-column))
2010 (int-to-string (org-table-current-dline)))
2011 (concat "@" (int-to-string (org-table-current-dline))
2012 "$" (int-to-string (org-table-current-column)))))
2013 (field (org-table-get-field))
2014 (cw (current-window-configuration))
2017 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2018 (when (and (local-variable-p 'org-field-marker
)
2019 (markerp org-field-marker
))
2020 (move-marker org-field-marker nil
))
2022 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2023 (let ((org-inhibit-startup t
)) (org-mode))
2025 (setq truncate-lines nil
)
2027 (goto-char (setq p
(point-max)))
2028 (insert (org-trim field
))
2029 (remove-text-properties p
(point-max)
2030 '(invisible t org-cwidth t display t
2033 (setq-local org-finish-function
'org-table-finish-edit-field
)
2034 (setq-local org-window-configuration cw
)
2035 (setq-local org-field-marker pos
)
2036 (message "Edit and finish with C-c C-c")))))
2038 (defun org-table-finish-edit-field ()
2039 "Finish editing a table data field.
2040 Remove all newline characters, insert the result into the table, realign
2041 the table and kill the editing buffer."
2042 (let ((pos org-field-marker
)
2043 (cw org-window-configuration
)
2044 (cb (current-buffer))
2046 (goto-char (point-min))
2047 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2048 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2049 (replace-match " "))
2050 (setq text
(org-trim (buffer-string)))
2051 (set-window-configuration cw
)
2053 (select-window (get-buffer-window (marker-buffer pos
)))
2055 (move-marker pos nil
)
2056 (org-table-check-inside-data-field)
2057 (org-table-get-field nil text
)
2059 (message "New field value inserted")))
2061 (define-minor-mode org-table-follow-field-mode
2062 "Minor mode to make the table field editor window follow the cursor.
2063 When this mode is active, the field editor window will always show the
2064 current field. The mode exits automatically when the cursor leaves the
2065 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2066 nil
" TblFollow" nil
2067 (if org-table-follow-field-mode
2068 (add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2070 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2071 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2072 (win (and buf
(get-buffer-window buf
))))
2073 (when win
(delete-window win
))
2075 (with-current-buffer buf
2076 (move-marker org-field-marker nil
))
2077 (kill-buffer buf
)))))
2079 (defun org-table-follow-fields-with-editor ()
2080 (if (and org-table-exit-follow-field-mode-when-leaving-table
2081 (not (org-at-table-p)))
2082 ;; We have left the table, exit the follow mode
2083 (org-table-follow-field-mode -
1)
2084 (when (org-table-check-inside-data-field 'noerror
)
2085 (let ((win (selected-window)))
2086 (org-table-edit-field nil
)
2087 (org-fit-window-to-buffer)
2088 (select-window win
)))))
2090 (defvar org-timecnt
) ; dynamically scoped parameter
2093 (defun org-table-sum (&optional beg end nlast
)
2094 "Sum numbers in region of current table column.
2095 The result will be displayed in the echo area, and will be available
2096 as kill to be inserted with \\[yank].
2098 If there is an active region, it is interpreted as a rectangle and all
2099 numbers in that rectangle will be summed. If there is no active
2100 region and point is located in a table column, sum all numbers in that
2103 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2104 numbers are assumed to be times as well (in decimal hours) and the
2105 numbers are added as such.
2107 If NLAST is a number, only the NLAST fields will actually be summed."
2110 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2112 ((and beg end
)) ; beg and end given explicitly
2113 ((org-region-active-p)
2114 (setq beg
(region-beginning) end
(region-end)))
2116 (setq col
(org-table-current-column))
2117 (goto-char (org-table-begin))
2118 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2119 (user-error "No table data"))
2120 (org-table-goto-column col
)
2122 (goto-char (org-table-end))
2123 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2124 (user-error "No table data"))
2125 (org-table-goto-column col
)
2126 (setq end
(point))))
2127 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2128 (items1 (cond ((not nlast
) items
)
2129 ((>= nlast
(length items
)) items
)
2130 (t (setq items
(reverse items
))
2131 (setcdr (nthcdr (1- nlast
) items
) nil
)
2133 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2135 (res (apply '+ numbers
))
2136 (sres (if (= org-timecnt
0)
2137 (number-to-string res
)
2138 (setq diff
(* 3600 res
)
2139 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2140 m
(floor (/ diff
60)) diff
(mod diff
60)
2142 (format "%.0f:%02.0f:%02.0f" h m s
))))
2144 (when (called-interactively-p 'interactive
)
2145 (message "%s" (substitute-command-keys
2146 (format "Sum of %d items: %-20s \
2147 \(\\[yank] will insert result into buffer)" (length numbers
) sres
))))
2150 (defun org-table-get-number-for-summing (s)
2152 (if (string-match "^ *|? *" s
)
2153 (setq s
(replace-match "" nil nil s
)))
2154 (if (string-match " *|? *$" s
)
2155 (setq s
(replace-match "" nil nil s
)))
2156 (setq n
(string-to-number s
))
2158 ((and (string-match "0" s
)
2159 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2160 ((string-match "\\`[ \t]+\\'" s
) nil
)
2161 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2162 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2163 (m (string-to-number (or (match-string 2 s
) "0")))
2164 (s (string-to-number (or (match-string 4 s
) "0"))))
2165 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2166 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2170 (defun org-table-current-field-formula (&optional key noerror
)
2171 "Return the formula active for the current field.
2173 Assumes that table is already analyzed. If KEY is given, return
2174 the key to this formula. Otherwise return the formula preceded
2175 with \"=\" or \":=\"."
2176 (let* ((line (count-lines org-table-current-begin-pos
2177 (line-beginning-position)))
2178 (row (org-table-line-to-dline line
)))
2181 (let* ((col (org-table-current-column))
2182 (name (car (rassoc (list line col
)
2183 org-table-named-field-locations
)))
2184 (scol (format "$%d" col
))
2185 (ref (format "@%d$%d" (org-table-current-dline) col
))
2186 (stored-list (org-table-get-stored-formulas noerror
))
2187 (ass (or (assoc name stored-list
)
2188 (assoc ref stored-list
)
2189 (assoc scol stored-list
))))
2190 (cond (key (car ass
))
2191 (ass (concat (if (string-match-p "^[0-9]+$" (car ass
)) "=" ":=")
2194 (t (error "No formula active for the current field")))))
2196 (defun org-table-get-formula (&optional equation named
)
2197 "Read a formula from the minibuffer, offer stored formula as default.
2198 When NAMED is non-nil, look for a named equation."
2199 (let* ((stored-list (org-table-get-stored-formulas))
2200 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2201 (line-beginning-position))
2202 (org-table-current-column))
2203 org-table-named-field-locations
)))
2204 (ref (format "@%d$%d"
2205 (org-table-current-dline)
2206 (org-table-current-column)))
2208 ((not named
) (format "$%d" (org-table-current-column)))
2209 ((and name
(not (string-match "\\`LR[0-9]+\\'" name
))) name
)
2211 (name (or name ref
))
2212 (org-table-may-need-update nil
)
2213 (stored (cdr (assoc scol stored-list
)))
2215 ((and stored equation
(string-match-p "^ *=? *$" equation
))
2219 (t (org-table-formula-from-user
2221 (org-table-formula-to-user
2222 (format "%s formula %s="
2223 (if named
"Field" "Column")
2225 (if stored
(org-table-formula-to-user stored
) "")
2226 'org-table-formula-history
2229 (when (not (string-match "\\S-" eq
))
2231 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2232 (org-table-store-formulas stored-list
)
2233 (user-error "Formula removed"))
2234 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2235 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2236 (if (and name
(not named
))
2237 ;; We set the column equation, delete the named one.
2238 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2241 (setcdr (assoc scol stored-list
) eq
)
2242 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2243 (if (or mustsave
(not (equal stored eq
)))
2244 (org-table-store-formulas stored-list
))
2247 (defun org-table-store-formulas (alist &optional location
)
2248 "Store the list of formulas below the current table.
2249 If optional argument LOCATION is a buffer position, insert it at
2253 (progn (goto-char location
) (beginning-of-line))
2254 (goto-char (org-table-end)))
2255 (let ((case-fold-search t
))
2256 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2258 ;; Don't overwrite TBLFM, we might use text properties to
2260 (goto-char (match-beginning 3))
2261 (delete-region (match-beginning 3) (match-end 0)))
2263 (insert (or (match-string 2) "#+TBLFM:")))
2265 (mapconcat (lambda (x) (concat (car x
) "=" (cdr x
)))
2266 (sort alist
#'org-table-formula-less-p
)
2270 (defsubst org-table-formula-make-cmp-string
(a)
2271 (when (string-match "\\`$[<>]" a
)
2272 (let ((arrow (string-to-char (substring a
1))))
2273 ;; Fake a high number to make sure this is sorted at the end.
2274 (setq a
(org-table-formula-handle-first/last-rc a
))
2275 (setq a
(format "$%d" (+ 10000
2276 (if (= arrow ?
<) -
1000 0)
2277 (string-to-number (substring a
1)))))))
2279 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2283 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2285 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2287 (concat "@@" (match-string 5 a
))))))
2289 (defun org-table-formula-less-p (a b
)
2290 "Compare two formulas for sorting."
2291 (let ((as (org-table-formula-make-cmp-string (car a
)))
2292 (bs (org-table-formula-make-cmp-string (car b
))))
2293 (and as bs
(string< as bs
))))
2296 (defun org-table-get-stored-formulas (&optional noerror location
)
2297 "Return an alist with the stored formulas directly after current table.
2298 By default, only return active formulas, i.e., formulas located
2299 on the first line after the table. However, if optional argument
2300 LOCATION is a buffer position, consider the formulas there."
2303 (progn (goto-char location
) (beginning-of-line))
2304 (goto-char (org-table-end)))
2305 (let ((case-fold-search t
))
2306 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2307 (let ((strings (org-split-string (match-string-no-properties 2)
2310 (dolist (string strings
(nreverse eq-alist
))
2311 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2312 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2315 (let ((m (match-string 1 string
)))
2317 ((not (match-end 2)) m
)
2318 ;; Is it a column reference?
2319 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m
) m
)
2320 ;; Since named columns are not possible in
2321 ;; LHS, assume this is a named field.
2322 (t (match-string 2 string
)))))
2323 (rhs (match-string 3 string
)))
2324 (push (cons lhs rhs
) eq-alist
)
2326 ((not (member lhs seen
)) (push lhs seen
))
2329 "Double definition `%s=' in TBLFM line, please fix by hand"
2335 "Double definition `%s=' in TBLFM line, please fix by hand"
2338 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2339 "Modify the equations after the table structure has been edited.
2340 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2341 For all numbers larger than LIMIT, shift them by DELTA."
2343 (goto-char (org-table-end))
2344 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2345 (let ((msg "The formulas in #+TBLFM have been updated")
2346 (re (concat key
"\\([0-9]+\\)"))
2349 (if (or (equal key
"$") (equal key
"$LR"))
2350 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2351 (regexp-quote key
) remove
)
2352 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2355 (while (re-search-forward re2
(point-at-eol) t
)
2356 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2357 (if (equal (char-before (match-beginning 0)) ?.
)
2359 "Change makes TBLFM term %s invalid, use undo to recover"
2361 (replace-match "")))))
2362 (while (re-search-forward re
(point-at-eol) t
)
2363 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2364 (setq s
(match-string 1) n
(string-to-number s
))
2366 ((setq a
(assoc s replace
))
2367 (replace-match (concat key
(cdr a
)) t t
)
2369 ((and limit
(> n limit
))
2370 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2375 (defun org-table-maybe-eval-formula ()
2376 "Check if the current field starts with \"=\" or \":=\".
2377 If yes, store the formula and apply it."
2378 ;; We already know we are in a table. Get field will only return a formula
2379 ;; when appropriate. It might return a separator line, but no problem.
2380 (when org-table-formula-evaluate-inline
2381 (let* ((field (org-trim (or (org-table-get-field) "")))
2383 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2384 (setq named
(equal (string-to-char field
) ?
:)
2385 eq
(match-string 1 field
))
2386 (org-table-eval-formula (and named
'(4))
2387 (org-table-formula-from-user eq
))))))
2389 (defvar org-recalc-commands nil
2390 "List of commands triggering the recalculation of a line.
2391 Will be filled automatically during use.")
2393 (defvar org-recalc-marks
2394 '((" " .
"Unmarked: no special line, no automatic recalculation")
2395 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2396 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2397 ("!" .
"Column name definition line. Reference in formula as $name.")
2398 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2399 ("_" .
"Names for values in row below this one.")
2400 ("^" .
"Names for values in row above this one.")))
2403 (defun org-table-rotate-recalc-marks (&optional newchar
)
2404 "Rotate the recalculation mark in the first column.
2405 If in any row, the first field is not consistent with a mark,
2406 insert a new column for the markers.
2407 When there is an active region, change all the lines in the region,
2408 after prompting for the marking character.
2409 After each change, a message will be displayed indicating the meaning
2412 (unless (org-at-table-p) (user-error "Not at a table"))
2413 (let* ((region (org-region-active-p))
2415 (save-excursion (goto-char (region-beginning))
2416 (copy-marker (line-beginning-position)))))
2418 (save-excursion (goto-char (region-end))
2419 (copy-marker (line-beginning-position)))))
2420 (l (copy-marker (line-beginning-position)))
2421 (col (org-table-current-column))
2424 (read-char-exclusive
2425 "Change region to what mark? Type # * ! $ or SPC: "))
2429 (goto-char (org-table-begin))
2431 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2432 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2433 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2435 (when l1
(goto-char l1
))
2438 (unless (looking-at org-table-dataline-regexp
)
2439 (user-error "Not at a table data line")))
2440 (when no-special-column
2441 (org-table-goto-column 1)
2442 (org-table-insert-column))
2443 (let ((previous-line-end (line-end-position))
2447 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2449 (t (cadr (member (match-string 1)
2450 (append (mapcar #'car org-recalc-marks
)
2452 ;; Rotate mark in first row.
2453 (org-table-get-field 1 (format " %s " newchar
))
2454 ;; Rotate marks in additional rows if a region is active.
2458 (while (<= (point) l2
)
2459 (when (looking-at org-table-dataline-regexp
)
2460 (org-table-get-field 1 (format " %s " newchar
)))
2462 ;; Only align if rotation actually changed lines' length.
2463 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2465 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2466 (when l1
(set-marker l1 nil
))
2467 (when l2
(set-marker l2 nil
))
2469 (when (called-interactively-p 'interactive
)
2470 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2473 (defun org-table-analyze ()
2474 "Analyze table at point and store results.
2476 This function sets up the following dynamically scoped variables:
2478 `org-table-column-name-regexp',
2479 `org-table-column-names',
2480 `org-table-current-begin-pos',
2481 `org-table-current-line-types',
2482 `org-table-current-ncol',
2485 `org-table-local-parameters',
2486 `org-table-named-field-locations'."
2487 (let ((beg (org-table-begin))
2488 (end (org-table-end)))
2491 ;; Extract column names.
2492 (setq org-table-column-names nil
)
2493 (when (save-excursion
2494 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
2496 (dolist (name (org-split-string (match-string 1) " *| *"))
2498 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
2499 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
2500 (setq org-table-column-names
(nreverse org-table-column-names
))
2501 (setq org-table-column-name-regexp
2502 (format "\\$\\(%s\\)\\>"
2503 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
2504 ;; Extract local parameters.
2505 (setq org-table-local-parameters nil
)
2507 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2508 (dolist (field (org-split-string (match-string 1) " *| *"))
2510 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2511 (push (cons (match-string 1 field
) (match-string 2 field
))
2512 org-table-local-parameters
)))))
2513 ;; Update named fields locations. We minimize `count-lines'
2514 ;; processing by storing last known number of lines in LAST.
2515 (setq org-table-named-field-locations nil
)
2517 (let ((last (cons (point) 0)))
2518 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2519 (let ((c (match-string 1))
2520 (fields (org-split-string (match-string 2) " *| *")))
2522 (forward-line (if (equal c
"_") 1 -
1))
2524 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2525 (org-split-string (match-string 1) " *| *")))
2526 (line (cl-incf (cdr last
) (count-lines (car last
) (point))))
2528 (setcar last
(point)) ; Update last known position.
2529 (while (and fields fields1
)
2530 (let ((field (pop fields
))
2533 (when (and (stringp field
)
2535 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2537 (push (cons field v
) org-table-local-parameters
)
2538 (push (list field line col
)
2539 org-table-named-field-locations
))))))))))
2540 ;; Re-use existing markers when possible.
2541 (if (markerp org-table-current-begin-pos
)
2542 (move-marker org-table-current-begin-pos
(point))
2543 (setq org-table-current-begin-pos
(point-marker)))
2544 ;; Analyze the line types.
2545 (let ((l 0) hlines dlines types
)
2546 (while (looking-at "[ \t]*|\\(-\\)?")
2547 (push (if (match-end 1) 'hline
'dline
) types
)
2548 (if (match-end 1) (push l hlines
) (push l dlines
))
2551 (push 'hline types
) ; Add an imaginary extra hline to the end.
2552 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
2553 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
2554 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
)))))
2555 ;; Get the number of columns from the first data line in table.
2557 (forward-line (aref org-table-dlines
1))
2560 (buffer-substring (line-beginning-position) (line-end-position))
2562 (nfields (length fields
))
2564 (setq org-table-current-ncol nfields
)
2566 (aref org-table-dlines
(1- (length org-table-dlines
)))))
2567 (dotimes (i nfields
)
2568 (let ((column (1+ i
)))
2569 (push (list (format "LR%d" column
) last-dline column
) al
)
2570 (push (cons (format "LR%d" column
) (nth i fields
)) al2
))))
2571 (setq org-table-named-field-locations
2572 (append org-table-named-field-locations al
))
2573 (setq org-table-local-parameters
2574 (append org-table-local-parameters al2
))))))
2576 (defun org-table-goto-field (ref &optional create-column-p
)
2577 "Move point to a specific field in the current table.
2579 REF is either the name of a field its absolute reference, as
2580 a string. No column is created unless CREATE-COLUMN-P is
2581 non-nil. If it is a function, it is called with the column
2582 number as its argument as is used as a predicate to know if the
2583 column can be created.
2585 This function assumes the table is already analyzed (i.e., using
2586 `org-table-analyze')."
2589 ((cdr (assoc ref org-table-named-field-locations
)))
2590 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
2591 (list (condition-case nil
2592 (aref org-table-dlines
2593 (string-to-number (match-string 1 ref
)))
2594 (error (user-error "Invalid row number in %s" ref
)))
2595 (string-to-number (match-string 2 ref
))))
2596 (t (user-error "Unknown field: %s" ref
))))
2597 (line (car coordinates
))
2598 (column (nth 1 coordinates
))
2599 (create-new-column (if (functionp create-column-p
)
2600 (funcall create-column-p column
)
2603 (goto-char org-table-current-begin-pos
)
2605 (org-table-goto-column column nil create-new-column
))))
2608 (defun org-table-maybe-recalculate-line ()
2609 "Recompute the current line if marked for it, and if we haven't just done it."
2611 (and org-table-allow-automatic-line-recalculation
2612 (not (and (memq last-command org-recalc-commands
)
2613 (eq org-last-recalc-line
(line-beginning-position))))
2614 (save-excursion (beginning-of-line 1)
2615 (looking-at org-table-auto-recalculate-regexp
))
2616 (org-table-recalculate) t
))
2618 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2619 (defsubst org-set-calc-mode
(var &optional value
)
2621 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2622 ("R" calc-angle-mode rad
)
2623 ("F" calc-prefer-frac t
)
2624 ("S" calc-symbolic-mode t
)))
2625 value
(nth 2 var
) var
(nth 1 var
)))
2626 (if (memq var org-tbl-calc-modes
)
2627 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2628 (cons var
(cons value org-tbl-calc-modes
)))
2632 (defun org-table-eval-formula (&optional arg equation
2633 suppress-align suppress-const
2634 suppress-store suppress-analysis
)
2635 "Replace the table field value at the cursor by the result of a calculation.
2637 In a table, this command replaces the value in the current field with the
2638 result of a formula. It also installs the formula as the \"current\" column
2639 formula, by storing it in a special line below the table. When called
2640 with a `\\[universal-argument]' prefix the formula is installed as a \
2643 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2644 insert the active equation for the field
2645 back into the current field, so that it can be edited there. This is \
2647 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2648 check the referenced fields.
2650 When called, the command first prompts for a formula, which is read in
2651 the minibuffer. Previously entered formulas are available through the
2652 history list, and the last used formula is offered as a default.
2653 These stored formulas are adapted correctly when moving, inserting, or
2654 deleting columns with the corresponding commands.
2656 The formula can be any algebraic expression understood by the Calc package.
2657 For details, see the Org mode manual.
2659 This function can also be called from Lisp programs and offers
2660 additional arguments: EQUATION can be the formula to apply. If this
2661 argument is given, the user will not be prompted.
2663 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2666 SUPPRESS-CONST suppresses the interpretation of constants in the
2667 formula, assuming that this has been done already outside the
2670 SUPPRESS-STORE means the formula should not be stored, either
2671 because it is already stored, or because it is a modified
2672 equation that should not overwrite the stored one.
2674 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2677 (unless suppress-analysis
2678 (org-table-check-inside-data-field)
2679 (org-table-analyze))
2680 (if (equal arg
'(16))
2681 (let ((eq (org-table-current-field-formula)))
2682 (org-table-get-field nil eq
)
2684 (setq org-table-may-need-update t
))
2686 (ndown (if (integerp arg
) arg
1))
2687 (org-table-automatic-realign nil
)
2688 (case-fold-search nil
)
2690 (formula (if (and equation suppress-store
)
2692 (org-table-get-formula equation
(equal arg
'(4)))))
2693 (n0 (org-table-current-column))
2694 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2695 (numbers nil
) ; was a variable, now fixed default
2697 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2698 duration duration-output-format
)
2699 ;; Parse the format string. Since we have a lot of modes, this is
2700 ;; a lot of work. However, I think calc still uses most of the time.
2701 (if (string-match ";" formula
)
2702 (let ((tmp (org-split-string formula
";")))
2703 (setq formula
(car tmp
)
2704 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2706 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2707 (setq c
(string-to-char (match-string 1 fmt
))
2708 n
(string-to-number (match-string 2 fmt
)))
2710 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2711 (setq org-tbl-calc-modes
2714 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2715 (?s . sci
) (?e . eng
))))
2717 (setq fmt
(replace-match "" t t fmt
)))
2718 (if (string-match "T" fmt
)
2719 (setq duration t numbers t
2720 duration-output-format nil
2721 fmt
(replace-match "" t t fmt
)))
2722 (if (string-match "t" fmt
)
2724 duration-output-format org-table-duration-custom-format
2726 fmt
(replace-match "" t t fmt
)))
2727 (if (string-match "N" fmt
)
2729 fmt
(replace-match "" t t fmt
)))
2730 (if (string-match "L" fmt
)
2732 fmt
(replace-match "" t t fmt
)))
2733 (if (string-match "E" fmt
)
2735 fmt
(replace-match "" t t fmt
)))
2736 (while (string-match "[DRFS]" fmt
)
2737 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2738 (setq fmt
(replace-match "" t t fmt
)))
2739 (unless (string-match "\\S-" fmt
)
2741 (when (and (not suppress-const
) org-table-formula-use-constants
)
2742 (setq formula
(org-table-formula-substitute-names formula
)))
2743 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2744 (setq formula
(org-table-formula-handle-first/last-rc formula
))
2746 (setq fields
(org-split-string
2748 (buffer-substring-no-properties
2749 (line-beginning-position) (line-end-position)))
2751 ;; replace fields with duration values if relevant
2754 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2757 (setq fields
(mapcar
2759 (if (string-match "\\S-" x
)
2760 (number-to-string (string-to-number x
))
2763 (setq ndown
(1- ndown
))
2764 (setq form
(copy-sequence formula
)
2765 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2766 (if (and lispp literal
) (setq lispp
'literal
))
2768 ;; Insert row and column number of formula result field
2769 (while (string-match "[@$]#" form
)
2774 (if (equal (substring form
(match-beginning 0)
2775 (1+ (match-beginning 0)))
2777 (org-table-current-dline)
2778 (org-table-current-column))))
2781 ;; Check for old vertical references
2782 (org-table--error-on-old-row-references form
)
2783 ;; Insert remote references
2784 (setq form
(org-table-remote-reference-indirection form
))
2785 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2789 (org-table-make-reference
2790 (let ((rmtrng (org-table-get-remote-range
2791 (match-string 1 form
) (match-string 2 form
))))
2794 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2795 (org-table-time-string-to-seconds rmtrng
))
2797 keep-empty numbers lispp
))
2799 ;; Insert complex ranges
2800 (while (and (string-match org-table-range-regexp form
)
2801 (> (length (match-string 0 form
)) 1))
2804 (org-table-get-range
2805 (match-string 0 form
) org-table-current-begin-pos n0
)))
2808 (org-table-make-reference
2809 ;; possibly handle durations
2812 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2813 (org-table-time-string-to-seconds formrg
))
2815 keep-empty numbers lispp
)))
2816 (if (not (save-match-data
2817 (string-match (regexp-quote form
) formrpl
)))
2818 (setq form
(replace-match formrpl t t form
))
2819 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2820 ;; Insert simple ranges, i.e. included in the current row.
2821 (while (string-match
2822 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2827 (org-table-make-reference
2829 (+ (if (match-end 2) n0
0)
2830 (string-to-number (match-string 1 form
))
2832 (+ (if (match-end 4) n0
0)
2833 (string-to-number (match-string 3 form
))))
2834 keep-empty numbers lispp
))
2837 ;; Insert the references to fields in same row
2838 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2839 (setq n
(+ (string-to-number (match-string 1 form
))
2840 (if (match-end 2) n0
0))
2841 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2842 formrpl
(save-match-data
2843 (org-table-make-reference
2844 x keep-empty numbers lispp
)))
2847 (string-match (regexp-quote formula
) formrpl
)))
2848 (user-error "Invalid field specifier \"%s\""
2849 (match-string 0 form
)))
2850 (setq form
(replace-match formrpl t t form
)))
2853 (setq ev
(condition-case nil
2854 (eval (eval (read form
)))
2856 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2857 ev
(if duration
(org-table-time-seconds-to-string
2858 (string-to-number ev
)
2859 duration-output-format
) ev
))
2861 ;; Use <...> time-stamps so that Calc can handle them.
2863 (replace-regexp-in-string org-ts-regexp-inactive
"<\\1>" form
))
2864 ;; Internationalize local time-stamps by setting locale to
2867 (replace-regexp-in-string
2870 (let ((system-time-locale "C"))
2872 (org-time-stamp-format
2873 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2874 (apply #'encode-time
2875 (save-match-data (org-parse-time-string ts
))))))
2878 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2880 (calc-eval (cons form org-tbl-calc-modes
)
2881 (when (and (not keep-empty
) numbers
) 'num
)))
2882 ev
(if duration
(org-table-time-seconds-to-string
2883 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2884 (string-to-number (org-table-time-string-to-seconds ev
))
2885 (string-to-number ev
))
2886 duration-output-format
)
2889 (when org-table-formula-debug
2890 (with-output-to-temp-buffer "*Substitution History*"
2891 (princ (format "Substitution history of formula
2895 $1-> %s\n" orig formula form0 form
))
2897 (princ (format " %s^\nError: %s"
2898 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2899 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2901 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2902 (setq bw
(get-buffer-window "*Substitution History*"))
2903 (org-fit-window-to-buffer bw
)
2904 (unless (and (called-interactively-p 'any
) (not ndown
))
2905 (unless (let (inhibit-redisplay)
2906 (y-or-n-p "Debugging Formula. Continue to next? "))
2908 (user-error "Abort"))
2911 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2912 (org-table-justify-field-maybe
2913 (format org-table-formula-field-format
2915 ((not (stringp ev
)) ev
)
2916 (fmt (format fmt
(string-to-number ev
)))
2917 ;; Replace any active time stamp in the result with
2918 ;; an inactive one. Dates in tables are likely
2919 ;; piece of regular data, not meant to appear in the
2921 (t (replace-regexp-in-string org-ts-regexp
"[\\1]" ev
)))))
2922 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2923 (call-interactively 'org-return
)
2925 (and down
(org-table-maybe-recalculate-line))
2926 (or suppress-align
(and org-table-may-need-update
2927 (org-table-align))))))
2929 (defun org-table-put-field-property (prop value
)
2931 (put-text-property (progn (skip-chars-backward "^|") (point))
2932 (progn (skip-chars-forward "^|") (point))
2935 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2936 "Get a calc vector from a column, according to descriptor DESC.
2938 Optional arguments TBEG and COL can give the beginning of the table and
2939 the current column, to avoid unnecessary parsing.
2941 HIGHLIGHT means just highlight the range.
2943 When CORNERS-ONLY is set, only return the corners of the range as
2944 a list (line1 column1 line2 column2) where line1 and line2 are
2945 line numbers relative to beginning of table, or TBEG, and column1
2946 and column2 are table column numbers."
2947 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc
)
2948 (replace-regexp-in-string "\\$" "@0$" desc
)
2950 (col (or col
(org-table-current-column)))
2951 (tbeg (or tbeg
(org-table-begin)))
2952 (thisline (count-lines tbeg
(line-beginning-position))))
2953 (unless (string-match org-table-range-regexp desc
)
2954 (user-error "Invalid table range specifier `%s'" desc
))
2955 (let ((rangep (match-end 3))
2956 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2957 (or (save-match-data
2958 (and (org-string-nw-p r
)
2959 (org-table--descriptor-line r thisline
)))
2961 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
2962 (or (save-match-data
2963 (and (org-string-nw-p r
)
2964 (org-table--descriptor-line r thisline
)))
2966 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
2967 (if (or (not c
) (= (string-to-number c
) 0)) col
2968 (+ (string-to-number c
)
2969 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
2970 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
2971 (if (or (not c
) (= (string-to-number c
) 0)) col
2972 (+ (string-to-number c
)
2973 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
2975 (if (and (not corners-only
)
2976 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2979 (forward-line (- r1 thisline
))
2980 (while (not (looking-at org-table-dataline-regexp
))
2982 (prog1 (org-trim (org-table-get-field c1
))
2983 (when highlight
(org-table-highlight-rectangle))))
2984 ;; A range, return a vector. First sort the numbers to get
2985 ;; a regular rectangle.
2986 (let ((first-row (min r1 r2
))
2987 (last-row (max r1 r2
))
2988 (first-column (min c1 c2
))
2989 (last-column (max c1 c2
)))
2990 (if corners-only
(list first-row first-column last-row last-column
)
2991 ;; Copy the range values into a list.
2992 (forward-line (- first-row thisline
))
2993 (while (not (looking-at org-table-dataline-regexp
))
2995 (cl-incf first-row
))
2996 (org-table-goto-column first-column
)
2997 (let ((beg (point)))
2998 (forward-line (- last-row first-row
))
2999 (while (not (looking-at org-table-dataline-regexp
))
3001 (org-table-goto-column last-column
)
3002 (let ((end (point)))
3004 (org-table-highlight-rectangle
3005 beg
(progn (skip-chars-forward "^|\n") (point))))
3006 ;; Return string representation of calc vector.
3009 (org-table-copy-region beg end
))))))))))))
3011 (defun org-table--descriptor-line (desc cline
)
3012 "Return relative line number corresponding to descriptor DESC.
3013 The cursor is currently in relative line number CLINE."
3014 (if (string-match "\\`[0-9]+\\'" desc
)
3015 (aref org-table-dlines
(string-to-number desc
))
3016 (when (or (not (string-match
3017 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3020 (and (not (match-end 3)) (not (match-end 6)))
3021 (and (match-end 3) (match-end 6) (not (match-end 5))))
3022 (user-error "Invalid row descriptor `%s'" desc
))
3023 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3024 (hdir (match-string 2 desc
))
3025 (odir (match-string 5 desc
))
3026 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
3027 (rel (and (match-end 6)
3028 (or (and (match-end 1) (not (match-end 3)))
3030 (when (and hn
(not hdir
))
3033 (when (eq (aref org-table-current-line-types
0) 'hline
) (cl-decf hn
)))
3034 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
3037 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
3040 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
3043 (defun org-table--row-type (type n i backwards relative desc
)
3044 "Return relative line of Nth row with type TYPE.
3045 Search starts from relative line I. When BACKWARDS in non-nil,
3046 look before I. When RELATIVE is non-nil, the reference is
3047 relative. DESC is the original descriptor that started the
3048 search, as a string."
3049 (let ((l (length org-table-current-line-types
)))
3052 (while (and (cl-incf i
(if backwards -
1 1))
3055 (not (eq (aref org-table-current-line-types i
) type
))
3056 ;; We are going to cross a hline. Check if this is
3057 ;; an authorized move.
3060 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
3061 ((eq org-table-relative-ref-may-cross-hline t
))
3062 ((eq org-table-relative-ref-may-cross-hline
'error
)
3063 (user-error "Row descriptor %s crosses hline" desc
))
3064 (t (cl-decf i
(if backwards -
1 1)) ; Step back.
3065 (throw :exit nil
)))))))
3066 (cond ((or (< i
0) (>= i l
))
3067 (user-error "Row descriptor %s leads outside table" desc
))
3068 ;; The last hline doesn't exist. Instead, point to last row
3070 ((= i
(1- l
)) (1- i
))
3073 (defun org-table--error-on-old-row-references (s)
3074 (when (string-match "&[-+0-9I]" s
)
3075 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3077 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3078 "Convert list ELEMENTS to something appropriate to insert into formula.
3079 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3080 NUMBERS indicates that everything should be converted to numbers.
3081 LISPP non-nil means to return something appropriate for a Lisp
3082 list, `literal' is for the format specifier L."
3083 ;; Calc nan (not a number) is used for the conversion of the empty
3084 ;; field to a reference for several reasons: (i) It is accepted in a
3085 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3086 ;; (ii) In a single field (not in range) it can be distinguished
3087 ;; from "(nan)" which is the reference made from a single field
3088 ;; containing "nan".
3089 (if (stringp elements
)
3092 (if (eq lispp
'literal
)
3094 (if (and (eq elements
"") (not keep-empty
))
3097 (if numbers
(string-to-number elements
) elements
))))
3098 (if (string-match "\\S-" elements
)
3100 (when numbers
(setq elements
(number-to-string
3101 (string-to-number elements
))))
3102 (concat "(" elements
")"))
3103 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3108 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3110 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3114 (if (eq lispp
'literal
)
3116 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3118 (concat "[" (mapconcat
3120 (if (string-match "\\S-" x
)
3122 (number-to-string (string-to-number x
))
3124 (if (or (not keep-empty
) numbers
) "0" "nan")))
3128 (defun org-table-message-once-per-second (t1 &rest args
)
3129 "If there has been more than one second since T1, display message.
3130 ARGS are passed as arguments to the `message' function. Returns
3131 current time if a message is printed, otherwise returns T1. If
3132 T1 is nil, always messages."
3133 (let ((curtime (current-time)))
3134 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3135 (progn (apply 'message args
)
3140 (defun org-table-recalculate (&optional all noalign
)
3141 "Recalculate the current table line by applying all stored formulas.
3143 With prefix arg ALL, do this for all lines in the table.
3145 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3146 if ALL is the symbol `iterate',
3147 recompute the table until it no longer changes.
3149 If NOALIGN is not nil, do not re-align the table after the computations
3150 are done. This is typically used internally to save time, if it is
3151 known that the table will be realigned a little later anyway."
3153 (unless (memq this-command org-recalc-commands
)
3154 (push this-command org-recalc-commands
))
3155 (unless (org-at-table-p) (user-error "Not at a table"))
3156 (if (or (eq all
'iterate
) (equal all
'(16)))
3159 (let* ((eqlist (sort (org-table-get-stored-formulas)
3160 (lambda (a b
) (string< (car a
) (car b
)))))
3161 (inhibit-redisplay (not debug-on-error
))
3162 (line-re org-table-dataline-regexp
)
3163 (log-first-time (current-time))
3164 (log-last-time log-first-time
)
3166 beg end eqlcol eqlfield
)
3167 ;; Insert constants in all formulas.
3169 (org-table-save-field
3170 ;; Expand equations, then split the equation list between
3171 ;; column formulas and field formulas.
3173 (let* ((rhs (org-table-formula-substitute-names
3174 (org-table-formula-handle-first/last-rc
(cdr eq
))))
3177 (org-table-formula-handle-first/last-rc
3179 ((string-match "\\`@-?I+" old-lhs
)
3180 (user-error "Can't assign to hline relative reference"))
3181 ((string-match "\\`$[<>]" old-lhs
)
3182 (let ((new (org-table-formula-handle-first/last-rc
3184 (when (assoc new eqlist
)
3185 (user-error "\"%s=\" formula tries to overwrite \
3186 existing formula for column %s"
3191 (if (string-match-p "\\`\\$[0-9]+\\'" lhs
)
3192 (push (cons lhs rhs
) eqlcol
)
3193 (push (cons lhs rhs
) eqlfield
))))
3194 (setq eqlcol
(nreverse eqlcol
))
3195 ;; Expand ranges in lhs of formulas
3196 (setq eqlfield
(org-table-expand-lhs-ranges (nreverse eqlfield
)))
3197 ;; Get the correct line range to process.
3200 (setq end
(copy-marker (org-table-end)))
3201 (goto-char (setq beg org-table-current-begin-pos
))
3203 ((re-search-forward org-table-calculate-mark-regexp end t
)
3204 ;; This is a table with marked lines, compute selected
3206 (setq line-re org-table-recalculate-regexp
))
3207 ;; Move forward to the first non-header line.
3208 ((and (re-search-forward org-table-dataline-regexp end t
)
3209 (re-search-forward org-table-hline-regexp end t
)
3210 (re-search-forward org-table-dataline-regexp end t
))
3211 (setq beg
(match-beginning 0)))
3212 ;; Just leave BEG at the start of the table.
3214 (setq beg
(line-beginning-position)
3215 end
(copy-marker (line-beginning-position 2))))
3217 ;; Mark named fields untouchable. Also check if several
3218 ;; field/range formulas try to set the same field.
3219 (remove-text-properties beg end
'(org-untouchable t
))
3220 (let ((current-line (count-lines org-table-current-begin-pos
3221 (line-beginning-position)))
3223 (dolist (eq eqlfield
)
3224 (let* ((name (car eq
))
3225 (location (assoc name org-table-named-field-locations
))
3226 (eq-line (or (nth 1 location
)
3227 (and (string-match "\\`@\\([0-9]+\\)" name
)
3228 (aref org-table-dlines
3230 (match-string 1 name
))))))
3233 ;; Turn field coordinates associated to NAME
3234 ;; into an absolute reference.
3236 (org-table-line-to-dline eq-line
)
3239 (when (member reference seen-fields
)
3240 (user-error "Several field/range formulas try to set %s"
3242 (push reference seen-fields
)
3243 (when (or all
(eq eq-line current-line
))
3244 (org-table-goto-field name
)
3245 (org-table-put-field-property :org-untouchable t
)))))
3246 ;; Evaluate the column formulas, but skip fields covered by
3249 (while (re-search-forward line-re end t
)
3250 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3251 ;; Unprotected line, recalculate.
3255 (org-table-message-once-per-second
3257 "Re-applying formulas to full table...(line %d)" cnt
)))
3258 (if (markerp org-last-recalc-line
)
3259 (move-marker org-last-recalc-line
(line-beginning-position))
3260 (setq org-last-recalc-line
3261 (copy-marker (line-beginning-position))))
3262 (dolist (entry eqlcol
)
3263 (goto-char org-last-recalc-line
)
3264 (org-table-goto-column
3265 (string-to-number (substring (car entry
) 1)) nil
'force
)
3266 (unless (get-text-property (point) :org-untouchable
)
3267 (org-table-eval-formula
3268 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
3269 ;; Evaluate the field formulas.
3270 (dolist (eq eqlfield
)
3271 (let ((reference (car eq
))
3274 (org-table-message-once-per-second
3275 (and all log-last-time
)
3276 "Re-applying formula to field: %s" (car eq
)))
3277 (org-table-goto-field
3279 ;; Possibly create a new column, as long as
3280 ;; `org-table-formula-create-columns' allows it.
3281 (let ((column-count (progn (end-of-line)
3282 (1- (org-table-current-column)))))
3284 (when (> column
1000)
3285 (user-error "Formula column target too large"))
3286 (and (> column column-count
)
3287 (or (eq org-table-formula-create-columns t
)
3288 (and (eq org-table-formula-create-columns
'warn
)
3290 (org-display-warning
3291 "Out-of-bounds formula added columns")
3293 (and (eq org-table-formula-create-columns
'prompt
)
3295 "Out-of-bounds formula. Add columns? ")))))))
3296 (org-table-eval-formula nil formula t t t t
))))
3297 ;; Clean up markers and internal text property.
3298 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3299 (set-marker end nil
)
3301 (when org-table-may-need-update
(org-table-align))
3303 (org-table-message-once-per-second
3304 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
3305 (org-table-message-once-per-second
3306 (and all log-first-time
) "Re-applying formulas... done")))))
3309 (defun org-table-iterate (&optional arg
)
3310 "Recalculate the table until it does not change anymore.
3311 The maximum number of iterations is 10, but you can choose a different value
3312 with the prefix ARG."
3314 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3316 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3321 (org-table-recalculate 'all
)
3322 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3323 (if (not (string= lasttbl thistbl
))
3324 (setq lasttbl thistbl
)
3326 (message "Convergence after %d iterations" i
)
3327 (message "Table was already stable"))
3329 (user-error "No convergence after %d iterations" i
))))
3332 (defun org-table-recalculate-buffer-tables ()
3333 "Recalculate all tables in the current buffer."
3335 (org-with-wide-buffer
3336 (org-table-map-tables
3338 ;; Reason for separate `org-table-align': When repeating
3339 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3341 (org-table-recalculate t t
)
3346 (defun org-table-iterate-buffer-tables ()
3347 "Iterate all tables in the buffer, to converge inter-table dependencies."
3351 (checksum (md5 (buffer-string)))
3353 (org-with-wide-buffer
3357 (org-table-map-tables (lambda () (org-table-recalculate t t
)) t
)
3358 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3360 (org-table-map-tables #'org-table-align t
)
3361 (message "Convergence after %d iterations" (- imax i
))
3363 (setq checksum c1
)))
3364 (org-table-map-tables #'org-table-align t
)
3365 (user-error "No convergence after %d iterations" imax
)))))
3367 (defun org-table-calc-current-TBLFM (&optional arg
)
3368 "Apply the #+TBLFM in the line at point to the table."
3370 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3371 (let ((formula (buffer-substring
3372 (line-beginning-position)
3373 (line-end-position))))
3375 ;; Insert a temporary formula at right after the table
3376 (goto-char (org-table-TBLFM-begin))
3377 (let ((s (point-marker)))
3378 (insert formula
"\n")
3379 (let ((e (point-marker)))
3380 ;; Recalculate the table.
3381 (beginning-of-line 0) ; move to the inserted line
3382 (skip-chars-backward " \r\n\t")
3384 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3385 ;; Delete the formula inserted temporarily.
3388 (set-marker e nil
)))))))
3390 (defun org-table-TBLFM-begin ()
3391 "Find the beginning of the TBLFM lines and return its position.
3392 Return nil when the beginning of TBLFM line was not found."
3394 (when (progn (forward-line 1)
3395 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3396 (line-beginning-position 2))))
3398 (defun org-table-expand-lhs-ranges (equations)
3399 "Expand list of formulas.
3400 If some of the RHS in the formulas are ranges or a row reference,
3401 expand them to individual field equations for each field. This
3402 function assumes the table is already analyzed (i.e., using
3403 `org-table-analyze')."
3405 (dolist (e equations
(nreverse res
))
3409 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3410 ;; This just refers to one fixed field.
3412 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3413 ;; This just refers to one fixed named field.
3415 ((string-match-p "\\`\\$[0-9]+\\'" lhs
)
3416 ;; Column formulas are treated specially and are not
3419 ((string-match "\\`@[0-9]+\\'" lhs
)
3420 (dotimes (ic org-table-current-ncol
)
3421 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3425 (let* ((range (org-table-get-range
3426 lhs org-table-current-begin-pos
1 nil
'corners
))
3427 (r1 (org-table-line-to-dline (nth 0 range
)))
3429 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3431 (cl-loop for ir from r1 to r2 do
3432 (cl-loop for ic from c1 to c2 do
3433 (push (cons (propertize
3434 (format "@%d$%d" ir ic
) :orig-eqn e
)
3438 (defun org-table-formula-handle-first/last-rc
(s)
3439 "Replace @<, @>, $<, $> with first/last row/column of the table.
3440 So @< and $< will always be replaced with @1 and $1, respectively.
3441 The advantage of these special markers are that structure editing of
3442 the table will not change them, while @1 and $1 will be modified
3443 when a line/row is swapped out of that privileged position. So for
3444 formulas that use a range of rows or columns, it may often be better
3445 to anchor the formula with \"I\" row markers, or to offset from the
3446 borders of the table using the @< @> $< $> makers."
3447 (let (n nmax len char
(start 0))
3448 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3451 (setq start
(match-end 3))
3452 (setq nmax
(if (equal (match-string 1 s
) "@")
3453 (1- (length org-table-dlines
))
3454 org-table-current-ncol
)
3455 len
(- (match-end 2) (match-beginning 2))
3456 char
(string-to-char (match-string 2 s
))
3460 (if (or (< n
1) (> n nmax
))
3461 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3462 (match-string 0 s
) s
))
3463 (setq start
(match-beginning 0))
3464 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3467 (defun org-table-formula-substitute-names (f)
3468 "Replace $const with values in string F."
3470 (pp (/= (string-to-char f
) ?
'))
3471 (duration (string-match-p ";.*[Tt].*\\'" f
))
3472 (new (replace-regexp-in-string ; Check for column names.
3473 org-table-column-name-regexp
3475 (concat "$" (cdr (assoc (match-string 1 m
)
3476 org-table-column-names
))))
3478 ;; Parameters and constants.
3481 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3483 (if (match-end 2) (setq start
(match-end 2))
3485 ;; When a duration is expected, convert value on the fly.
3488 (let ((v (org-table-get-constant (match-string 1 new
))))
3489 (if (and (org-string-nw-p v
) duration
)
3490 (org-table-time-string-to-seconds v
)
3493 (setq new
(replace-match
3494 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3495 (if org-table-formula-debug
(propertize new
:orig-formula f
) new
)))
3497 (defun org-table-get-constant (const)
3498 "Find the value for a parameter or constant in a formula.
3499 Parameters get priority."
3500 (or (cdr (assoc const org-table-local-parameters
))
3501 (cdr (assoc const org-table-formula-constants-local
))
3502 (cdr (assoc const org-table-formula-constants
))
3503 (and (fboundp 'constants-get
) (constants-get const
))
3504 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3505 (org-entry-get nil
(substring const
5) 'inherit
))
3508 (defvar org-table-fedit-map
3509 (let ((map (make-sparse-keymap)))
3510 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3511 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3512 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3513 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3514 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3515 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3516 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3517 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3518 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3519 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3520 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3521 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3522 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3523 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3524 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3525 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3526 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3527 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3528 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3529 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3532 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3534 ["Finish and Install" org-table-fedit-finish t
]
3535 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3536 ["Abort" org-table-fedit-abort t
]
3538 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3539 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3541 "Shift Reference at Point"
3542 ["Up" org-table-fedit-ref-up t
]
3543 ["Down" org-table-fedit-ref-down t
]
3544 ["Left" org-table-fedit-ref-left t
]
3545 ["Right" org-table-fedit-ref-right t
]
3547 "Change Test Row for Column Formulas"
3548 ["Up" org-table-fedit-line-up t
]
3549 ["Down" org-table-fedit-line-down t
]
3551 ["Scroll Table Window" org-table-fedit-scroll t
]
3552 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3553 ["Show Table Grid" org-table-fedit-toggle-coordinates
3554 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3555 org-table-overlay-coordinates
)]
3557 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3558 :style toggle
:selected org-table-buffer-is-an
]))
3561 (defvar org-table--fedit-source nil
3562 "Position of the TBLFM line being edited.")
3565 (defun org-table-edit-formulas ()
3566 "Edit the formulas of the current table in a separate buffer."
3568 (let ((at-tblfm (org-at-TBLFM-p)))
3569 (unless (or at-tblfm
(org-at-table-p))
3570 (user-error "Not at a table"))
3572 ;; Move point within the table before analyzing it.
3573 (when at-tblfm
(re-search-backward "^[ \t]*|"))
3574 (org-table-analyze))
3575 (let ((key (org-table-current-field-formula 'key
'noerror
))
3576 (eql (sort (org-table-get-stored-formulas t
(and at-tblfm
(point)))
3577 #'org-table-formula-less-p
))
3578 (pos (point-marker))
3579 (source (copy-marker (line-beginning-position)))
3581 (wc (current-window-configuration))
3582 (sel-win (selected-window))
3583 (titles '((column .
"# Column Formulas\n")
3584 (field .
"# Field and Range Formulas\n")
3585 (named .
"# Named Field Formulas\n"))))
3586 (org-switch-to-buffer-other-window "*Edit Formulas*")
3588 ;; Keep global-font-lock-mode from turning on font-lock-mode
3589 (let ((font-lock-global-modes '(not fundamental-mode
)))
3591 (setq-local font-lock-global-modes
(list 'not major-mode
))
3592 (setq-local org-pos pos
)
3593 (setq-local org-table--fedit-source source
)
3594 (setq-local org-window-configuration wc
)
3595 (setq-local org-selected-window sel-win
)
3596 (use-local-map org-table-fedit-map
)
3597 (add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3598 (easy-menu-add org-table-fedit-menu
)
3599 (setq startline
(org-current-line))
3602 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry
))
3604 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3606 (title (assq type titles
)))
3608 (unless (bobp) (insert "\n"))
3610 (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3611 (setq titles
(remove title titles
)))
3612 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3614 (if (memq (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3615 (car entry
) " = " (cdr entry
) "\n")))
3616 (remove-text-properties 0 (length s
) '(face nil
) s
)
3618 (when (eq org-table-use-standard-references t
)
3619 (org-table-fedit-toggle-ref-type))
3620 (org-goto-line startline
)
3621 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3622 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3623 See menu for more commands.")))))
3625 (defun org-table-fedit-post-command ()
3626 (when (not (memq this-command
'(lisp-complete-symbol)))
3627 (let ((win (selected-window)))
3629 (ignore-errors (org-table-show-reference))
3630 (select-window win
)))))
3632 (defun org-table-formula-to-user (s)
3633 "Convert a formula from internal to user representation."
3634 (if (eq org-table-use-standard-references t
)
3635 (org-table-convert-refs-to-an s
)
3638 (defun org-table-formula-from-user (s)
3639 "Convert a formula from user to internal representation."
3640 (if org-table-use-standard-references
3641 (org-table-convert-refs-to-rc s
)
3644 (defun org-table-convert-refs-to-rc (s)
3645 "Convert spreadsheet references from A7 to @7$28.
3646 Works for single references, but also for entire formulas and even the
3649 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3652 ;; format match, just advance
3653 (setq start
(match-end 0)))
3654 ((and (> (match-beginning 0) 0)
3655 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3656 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3657 ;; 3.e5 or something like this.
3658 (setq start
(match-end 0)))
3659 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3660 ;; (member (match-string 1 s)
3661 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3663 ;; function name, just advance
3664 (setq start
(match-end 0)))
3666 (setq start
(match-beginning 0)
3668 (if (equal (match-string 2 s
) "&")
3669 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3671 (string-to-number (match-string 2 s
))
3672 (org-letters-to-number (match-string 1 s
))))
3676 (defun org-table-convert-refs-to-an (s)
3677 "Convert spreadsheet references from to @7$28 to AB7.
3678 Works for single references, but also for entire formulas and even the
3680 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3681 (setq s
(replace-match
3683 (org-number-to-letters
3684 (string-to-number (match-string 2 s
)))
3685 (string-to-number (match-string 1 s
)))
3687 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3688 (setq s
(replace-match (concat "\\1"
3689 (org-number-to-letters
3690 (string-to-number (match-string 2 s
))) "&")
3694 (defun org-letters-to-number (s)
3695 "Convert a base 26 number represented by letters into an integer.
3696 For example: AB -> 28."
3699 (while (> (length s
) 0)
3700 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3704 (defun org-number-to-letters (n)
3705 "Convert an integer into a base 26 number represented by letters.
3706 For example: 28 -> AB."
3709 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3713 (defun org-table-time-string-to-seconds (s)
3714 "Convert a time string into numerical duration in seconds.
3715 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3716 If S is a string representing a number, keep this number."
3719 (let (hour minus min sec res
)
3721 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3722 (setq minus
(< 0 (length (match-string 1 s
)))
3723 hour
(string-to-number (match-string 2 s
))
3724 min
(string-to-number (match-string 3 s
))
3725 sec
(string-to-number (match-string 4 s
)))
3727 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3728 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3729 ((and (not (string-match org-ts-regexp-both s
))
3730 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3731 (setq minus
(< 0 (length (match-string 1 s
)))
3732 hour
(string-to-number (match-string 2 s
))
3733 min
(string-to-number (match-string 3 s
)))
3735 (setq res
(- (+ (* hour
3600) (* min
60))))
3736 (setq res
(+ (* hour
3600) (* min
60)))))
3737 (t (setq res
(string-to-number s
))))
3738 (number-to-string res
))))
3740 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3741 "Convert a number of seconds to a time string.
3742 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3743 minutes or seconds."
3744 (let* ((secs0 (abs secs
))
3746 (cond ((eq output-format
'days
)
3747 (format "%.3f" (/ (float secs0
) 86400)))
3748 ((eq output-format
'hours
)
3749 (format "%.2f" (/ (float secs0
) 3600)))
3750 ((eq output-format
'minutes
)
3751 (format "%.1f" (/ (float secs0
) 60)))
3752 ((eq output-format
'seconds
)
3753 (format "%d" secs0
))
3754 (t (format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3755 (if (< secs
0) (concat "-" res
) res
)))
3757 (defun org-table-fedit-convert-buffer (function)
3758 "Convert all references in this buffer, using FUNCTION."
3759 (let ((origin (copy-marker (line-beginning-position))))
3760 (goto-char (point-min))
3762 (insert (funcall function
(buffer-substring (point) (line-end-position))))
3763 (delete-region (point) (line-end-position))
3766 (set-marker origin nil
)))
3768 (defun org-table-fedit-toggle-ref-type ()
3769 "Convert all references in the buffer from B3 to @3$2 and back."
3771 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
3772 (org-table-fedit-convert-buffer
3773 (if org-table-buffer-is-an
3774 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3775 (message "Reference type switched to %s"
3776 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3778 (defun org-table-fedit-ref-up ()
3779 "Shift the reference at point one row/hline up."
3781 (org-table-fedit-shift-reference 'up
))
3782 (defun org-table-fedit-ref-down ()
3783 "Shift the reference at point one row/hline down."
3785 (org-table-fedit-shift-reference 'down
))
3786 (defun org-table-fedit-ref-left ()
3787 "Shift the reference at point one field to the left."
3789 (org-table-fedit-shift-reference 'left
))
3790 (defun org-table-fedit-ref-right ()
3791 "Shift the reference at point one field to the right."
3793 (org-table-fedit-shift-reference 'right
))
3795 (defun org-table-fedit-shift-reference (dir)
3797 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3798 (if (memq dir
'(left right
))
3799 (org-rematch-and-replace 1 (eq dir
'left
))
3800 (user-error "Cannot shift reference in this direction")))
3801 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3802 ;; A B3-like reference
3803 (if (memq dir
'(up down
))
3804 (org-rematch-and-replace 2 (eq dir
'up
))
3805 (org-rematch-and-replace 1 (eq dir
'left
))))
3807 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3808 ;; An internal reference
3809 (if (memq dir
'(up down
))
3810 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3811 (org-rematch-and-replace 5 (eq dir
'left
))))))
3813 (defun org-rematch-and-replace (n &optional decr hline
)
3814 "Re-match the group N, and replace it with the shifted reference."
3815 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3816 (goto-char (match-beginning n
))
3817 (and (looking-at (regexp-quote (match-string n
)))
3818 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3821 (defun org-table-shift-refpart (ref &optional decr hline
)
3822 "Shift a reference part REF.
3823 If DECR is set, decrease the references row/column, else increase.
3824 If HLINE is set, this may be a hline reference, it certainly is not
3825 a translation reference."
3827 (let* ((sign (string-match "^[-+]" ref
)) n
)
3829 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3831 ((and hline
(string-match "^I+" ref
))
3832 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3833 (setq n
(+ n
(if decr -
1 1)))
3834 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3836 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3838 (concat sign
(make-string n ?I
)))
3840 ((string-match "^[0-9]+" ref
)
3841 (setq n
(string-to-number (concat sign ref
)))
3842 (setq n
(+ n
(if decr -
1 1)))
3844 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3845 (number-to-string (max 1 n
))))
3847 ((string-match "^[a-zA-Z]+" ref
)
3848 (org-number-to-letters
3849 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3851 (t (user-error "Cannot shift reference"))))))
3853 (defun org-table-fedit-toggle-coordinates ()
3854 "Toggle the display of coordinates in the referenced table."
3856 (let ((pos (marker-position org-pos
)))
3857 (with-current-buffer (marker-buffer org-pos
)
3860 (org-table-toggle-coordinate-overlays)))))
3862 (defun org-table-fedit-finish (&optional arg
)
3863 "Parse the buffer for formula definitions and install them.
3864 With prefix ARG, apply the new formulas to the table."
3866 (org-table-remove-rectangle-highlight)
3867 (when org-table-use-standard-references
3868 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3869 (setq org-table-buffer-is-an nil
))
3871 (sel-win org-selected-window
)
3872 (source org-table--fedit-source
)
3874 (goto-char (point-min))
3875 (while (re-search-forward
3876 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3878 (let ((var (match-string 1))
3879 (form (org-trim (match-string 3))))
3880 (unless (equal form
"")
3881 (while (string-match "[ \t]*\n[ \t]*" form
)
3882 (setq form
(replace-match " " t t form
)))
3883 (when (assoc var eql
)
3884 (user-error "Double formulas for %s" var
))
3885 (push (cons var form
) eql
))))
3886 (set-window-configuration org-window-configuration
)
3887 (select-window sel-win
)
3889 (org-table-store-formulas eql
)
3890 (set-marker pos nil
)
3891 (set-marker source nil
)
3892 (kill-buffer "*Edit Formulas*")
3894 (org-table-recalculate 'all
)
3895 (message "New formulas installed - press C-u C-c C-c to apply."))))
3897 (defun org-table-fedit-abort ()
3898 "Abort editing formulas, without installing the changes."
3900 (org-table-remove-rectangle-highlight)
3901 (let ((pos org-pos
) (sel-win org-selected-window
))
3902 (set-window-configuration org-window-configuration
)
3903 (select-window sel-win
)
3905 (move-marker pos nil
)
3906 (message "Formula editing aborted without installing changes")))
3908 (defun org-table-fedit-lisp-indent ()
3909 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3911 (let ((pos (point)) beg end ind
)
3912 (beginning-of-line 1)
3914 ((looking-at "[ \t]")
3916 (call-interactively 'lisp-indent-line
))
3917 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3918 ((not (fboundp 'pp-buffer
))
3919 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3920 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3921 (goto-char (- (match-end 0) 2))
3923 (setq ind
(make-string (current-column) ?\
))
3924 (condition-case nil
(forward-sexp 1)
3926 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3929 (narrow-to-region beg end
)
3930 (if (eq last-command this-command
)
3932 (goto-char (point-min))
3933 (setq this-command nil
)
3934 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3935 (replace-match " ")))
3937 (untabify (point-min) (point-max))
3938 (goto-char (1+ (point-min)))
3939 (while (re-search-forward "^." nil t
)
3940 (beginning-of-line 1)
3942 (goto-char (point-max))
3943 (org-delete-backward-char 1)))
3947 (defvar org-show-positions nil
)
3949 (defun org-table-show-reference (&optional local
)
3950 "Show the location/value of the $ expression at point.
3951 When LOCAL is non-nil, show references for the table at point."
3953 (org-table-remove-rectangle-highlight)
3954 (when local
(org-table-analyze))
3956 (let ((pos (if local
(point) org-pos
))
3958 (org-inhibit-highlight-removal t
)
3959 (win (selected-window))
3960 (org-show-positions nil
)
3961 var name e what match dest
)
3963 ((org-in-regexp "^@[0-9]+[ \t=]")
3964 (setq match
(concat (substring (match-string 0) 0 -
1)
3966 (substring (match-string 0) 0 -
1)
3969 ((or (org-in-regexp org-table-range-regexp2
)
3970 (org-in-regexp org-table-translate-regexp
)
3971 (org-in-regexp org-table-range-regexp
))
3974 (org-table-convert-refs-to-rc (match-string 0))))
3976 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3977 ((org-in-regexp "\\$[0-9]+") 'column
)
3979 (t (user-error "No reference at point")))
3980 match
(and what
(or match
(match-string 0))))
3981 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3982 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3983 'secondary-selection
))
3984 (add-hook 'before-change-functions
3985 #'org-table-remove-rectangle-highlight
)
3986 (when (eq what
'name
) (setq var
(substring match
1)))
3987 (when (eq what
'range
)
3988 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3989 (setq match
(org-table-formula-substitute-names match
)))
3993 (re-search-backward "^\\S-" nil t
)
3995 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3996 \\([0-9]+\\|&\\)\\) *=")
3999 (org-table-convert-refs-to-rc (match-string 1))))
4000 (org-table-add-rectangle-overlay
4001 (match-beginning 1) (match-end 1) face2
))))
4002 (if (and (markerp pos
) (marker-buffer pos
))
4003 (if (get-buffer-window (marker-buffer pos
))
4004 (select-window (get-buffer-window (marker-buffer pos
)))
4005 (org-switch-to-buffer-other-window (get-buffer-window
4006 (marker-buffer pos
)))))
4008 (org-table-force-dataline)
4010 (if local org-table-current-begin-pos
(org-table-begin))))
4012 (setq name
(substring dest
1))
4014 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
4015 (org-table-goto-field dest
))
4016 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4018 (org-table-goto-field dest
))
4019 (t (org-table-goto-column (string-to-number name
))))
4020 (move-marker pos
(point))
4021 (org-table-highlight-rectangle nil nil face2
))
4023 ((equal dest match
))
4026 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
4027 ((setq e
(assoc var org-table-named-field-locations
))
4028 (org-table-goto-field var
)
4029 (org-table-highlight-rectangle)
4030 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
4031 ((setq e
(assoc var org-table-column-names
))
4032 (org-table-goto-column (string-to-number (cdr e
)))
4033 (org-table-highlight-rectangle)
4034 (goto-char table-start
)
4035 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
4038 (goto-char (match-beginning 1))
4039 (org-table-highlight-rectangle)
4040 (message "Named column (column %s)" (cdr e
)))
4041 (user-error "Column name not found")))
4044 (org-table-goto-column (string-to-number (substring match
1)))
4045 (org-table-highlight-rectangle)
4046 (message "Column %s" (substring match
1)))
4047 ((setq e
(assoc var org-table-local-parameters
))
4048 (goto-char table-start
)
4049 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
4051 (goto-char (match-beginning 1))
4052 (org-table-highlight-rectangle)
4053 (message "Local parameter."))
4054 (user-error "Parameter not found")))
4055 ((not var
) (user-error "No reference at point"))
4056 ((setq e
(assoc var org-table-formula-constants-local
))
4057 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4059 ((setq e
(assoc var org-table-formula-constants
))
4060 (message "Constant: $%s=%s in `org-table-formula-constants'."
4062 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4063 (message "Constant: $%s=%s, from `constants.el'%s."
4064 var e
(format " (%s units)" constants-unit-system
)))
4065 (t (user-error "Undefined name $%s" var
)))
4067 (when (and org-show-positions
4068 (not (memq this-command
'(org-table-fedit-scroll
4069 org-table-fedit-scroll-down
))))
4070 (push pos org-show-positions
)
4071 (push table-start org-show-positions
)
4072 (let ((min (apply 'min org-show-positions
))
4073 (max (apply 'max org-show-positions
)))
4074 (set-window-start (selected-window) min
)
4076 (or (pos-visible-in-window-p max
)
4077 (set-window-start (selected-window) max
)))))
4078 (select-window win
))))
4080 (defun org-table-force-dataline ()
4081 "Make sure the cursor is in a dataline in a table."
4082 (unless (save-excursion
4083 (beginning-of-line 1)
4084 (looking-at org-table-dataline-regexp
))
4085 (let* ((re org-table-dataline-regexp
)
4086 (p1 (save-excursion (re-search-forward re nil
'move
)))
4087 (p2 (save-excursion (re-search-backward re nil
'move
))))
4089 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4091 ((or p1 p2
) (goto-char (or p1 p2
)))
4092 (t (user-error "No table dataline around here"))))))
4094 (defun org-table-fedit-line-up ()
4095 "Move cursor one line up in the window showing the table."
4097 (org-table-fedit-move 'previous-line
))
4099 (defun org-table-fedit-line-down ()
4100 "Move cursor one line down in the window showing the table."
4102 (org-table-fedit-move 'next-line
))
4104 (defun org-table-fedit-move (command)
4105 "Move the cursor in the window showing the table.
4106 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4107 (let ((org-table-allow-automatic-line-recalculation nil
)
4108 (pos org-pos
) (win (selected-window)) p
)
4109 (select-window (get-buffer-window (marker-buffer org-pos
)))
4111 (call-interactively command
)
4112 (while (and (org-at-table-p)
4113 (org-at-table-hline-p))
4114 (call-interactively command
))
4115 (or (org-at-table-p) (goto-char p
))
4116 (move-marker pos
(point))
4117 (select-window win
)))
4119 (defun org-table-fedit-scroll (N)
4121 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4122 (scroll-other-window N
)))
4124 (defun org-table-fedit-scroll-down (N)
4126 (org-table-fedit-scroll (- N
)))
4128 (defvar org-table-rectangle-overlays nil
)
4130 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4131 "Add a new overlay."
4132 (let ((ov (make-overlay beg end
)))
4133 (overlay-put ov
'face
(or face
'secondary-selection
))
4134 (push ov org-table-rectangle-overlays
)))
4136 (defun org-table-highlight-rectangle (&optional beg end face
)
4137 "Highlight rectangular region in a table.
4138 When buffer positions BEG and END are provided, use them to
4139 delimit the region to highlight. Otherwise, refer to point. Use
4140 FACE, when non-nil, for the highlight."
4141 (let* ((beg (or beg
(point)))
4142 (end (or end
(point)))
4148 (cons (line-beginning-position) (org-table-current-column))))
4152 (cons (line-beginning-position) (org-table-current-column)))))
4153 (when (boundp 'org-show-positions
)
4154 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4155 (goto-char (car start-coordinates
))
4156 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
4157 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
4158 (last-row (car end-coordinates
)))
4159 (while (<= (point) last-row
)
4160 (when (looking-at org-table-dataline-regexp
)
4161 (org-table-goto-column column-start
)
4162 (skip-chars-backward "^|\n")
4164 (org-table-goto-column column-end
)
4165 (skip-chars-forward "^|\n")
4166 (org-table-add-rectangle-overlay p
(point) face
)))
4168 (goto-char (car start-coordinates
)))
4169 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
4171 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
4172 "Remove the rectangle overlays."
4173 (unless org-inhibit-highlight-removal
4174 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4175 (mapc 'delete-overlay org-table-rectangle-overlays
)
4176 (setq org-table-rectangle-overlays nil
)))
4178 (defvar-local org-table-coordinate-overlays nil
4179 "Collects the coordinate grid overlays, so that they can be removed.")
4181 (defun org-table-overlay-coordinates ()
4182 "Add overlays to the table at point, to show row/column coordinates."
4184 (mapc 'delete-overlay org-table-coordinate-overlays
)
4185 (setq org-table-coordinate-overlays nil
)
4187 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4188 (goto-char (org-table-begin))
4189 (while (org-at-table-p)
4190 (setq eol
(point-at-eol))
4191 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4192 (push ov org-table-coordinate-overlays
)
4193 (setq hline
(looking-at org-table-hline-regexp
))
4194 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4195 (format "%4d" (setq id
(1+ id
)))))
4196 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4199 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4200 (setq beg
(1+ (match-beginning 0))
4202 s1
(concat "$" (int-to-string ic
))
4203 s2
(org-number-to-letters ic
)
4204 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4205 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4206 (push ov org-table-coordinate-overlays
)
4207 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4208 (beginning-of-line 2)))))
4211 (defun org-table-toggle-coordinate-overlays ()
4212 "Toggle the display of Row/Column numbers in tables."
4214 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4215 (message "Tables Row/Column numbers display turned %s"
4216 (if org-table-overlay-coordinates
"on" "off"))
4217 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4219 (unless org-table-overlay-coordinates
4220 (mapc 'delete-overlay org-table-coordinate-overlays
)
4221 (setq org-table-coordinate-overlays nil
)))
4224 (defun org-table-toggle-formula-debugger ()
4225 "Toggle the formula debugger in tables."
4227 (setq org-table-formula-debug
(not org-table-formula-debug
))
4228 (message "Formula debugging has been turned %s"
4229 (if org-table-formula-debug
"on" "off")))
4231 ;;; The orgtbl minor mode
4233 ;; Define a minor mode which can be used in other modes in order to
4234 ;; integrate the Org table editor.
4236 ;; This is really a hack, because the Org table editor uses several
4237 ;; keys which normally belong to the major mode, for example the TAB
4238 ;; and RET keys. Here is how it works: The minor mode defines all the
4239 ;; keys necessary to operate the table editor, but wraps the commands
4240 ;; into a function which tests if the cursor is currently inside
4241 ;; a table. If that is the case, the table editor command is
4242 ;; executed. However, when any of those keys is used outside a table,
4243 ;; the function uses `key-binding' to look up if the key has an
4244 ;; associated command in another currently active keymap (minor modes,
4245 ;; major mode, global), and executes that command. There might be
4246 ;; problems if any of the keys used by the table editor is otherwise
4247 ;; used as a prefix key.
4249 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4250 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4251 ;; addresses this by checking explicitly for both bindings.
4253 ;; The optimized version (see variable `orgtbl-optimized') takes over
4254 ;; all keys which are bound to `self-insert-command' in the *global map*.
4255 ;; Some modes bind other commands to simple characters, for example
4256 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4257 ;; active, this binding is ignored inside tables and replaced with a
4258 ;; modified self-insert.
4261 (defvar orgtbl-mode-map
(make-keymap)
4262 "Keymap for `orgtbl-mode'.")
4264 (defvar org-old-auto-fill-inhibit-regexp nil
4265 "Local variable used by `orgtbl-mode'.")
4267 (defconst orgtbl-line-start-regexp
4268 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4269 "Matches a line belonging to an orgtbl.")
4271 (defconst orgtbl-extra-font-lock-keywords
4272 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4273 0 (quote 'org-table
) 'prepend
))
4274 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4276 ;; Install it as a minor mode.
4277 (put 'orgtbl-mode
:included t
)
4278 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4281 (define-minor-mode orgtbl-mode
4282 "The `org-mode' table editor as a minor mode for use in other modes."
4283 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4284 (org-load-modules-maybe)
4286 ((derived-mode-p 'org-mode
)
4287 ;; Exit without error, in case some hook functions calls this
4288 ;; by accident in org-mode.
4289 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4291 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4292 ;; Make sure we are first in minor-mode-map-alist
4293 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4294 ;; FIXME: maybe it should use emulation-mode-map-alists?
4295 (and c
(setq minor-mode-map-alist
4296 (cons c
(delq c minor-mode-map-alist
)))))
4297 (setq-local org-table-may-need-update t
)
4298 (add-hook 'before-change-functions
'org-before-change-function
4300 (setq-local org-old-auto-fill-inhibit-regexp
4301 auto-fill-inhibit-regexp
)
4302 (setq-local auto-fill-inhibit-regexp
4303 (if auto-fill-inhibit-regexp
4304 (concat orgtbl-line-start-regexp
"\\|"
4305 auto-fill-inhibit-regexp
)
4306 orgtbl-line-start-regexp
))
4307 (add-to-invisibility-spec '(org-cwidth))
4308 (when (fboundp 'font-lock-add-keywords
)
4309 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4310 (org-restart-font-lock))
4311 (easy-menu-add orgtbl-mode-menu
))
4313 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4314 (org-table-cleanup-narrow-column-properties)
4315 (org-remove-from-invisibility-spec '(org-cwidth))
4316 (remove-hook 'before-change-functions
'org-before-change-function t
)
4317 (when (fboundp 'font-lock-remove-keywords
)
4318 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4319 (org-restart-font-lock))
4320 (easy-menu-remove orgtbl-mode-menu
)
4321 (force-mode-line-update 'all
))))
4323 (defun org-table-cleanup-narrow-column-properties ()
4324 "Remove all properties related to narrow-column invisibility."
4325 (let ((s (point-min)))
4326 (while (setq s
(text-property-any s
(point-max)
4327 'display org-narrow-column-arrow
))
4328 (remove-text-properties s
(1+ s
) '(display t
)))
4329 (setq s
(point-min))
4330 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4331 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4332 (setq s
(point-min))
4333 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4334 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4336 (defun orgtbl-make-binding (fun n
&rest keys
)
4337 "Create a function for binding in the table minor mode.
4338 FUN is the command to call inside a table. N is used to create a unique
4339 command name. KEYS are keys that should be checked in for a command
4340 to execute outside of tables."
4343 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4345 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4346 "Outside of tables, run the binding of `"
4347 (mapconcat #'key-description keys
"' or `")
4352 (list 'call-interactively
(list 'quote fun
))
4353 (list 'let
'(orgtbl-mode)
4354 (list 'call-interactively
4357 (list 'key-binding k
))
4359 '('orgtbl-error
))))))))
4361 (defun orgtbl-error ()
4362 "Error when there is no default binding for a table key."
4364 (user-error "This key has no function outside tables"))
4366 (defun orgtbl-setup ()
4367 "Setup orgtbl keymaps."
4370 '(([(meta shift left
)] org-table-delete-column
)
4371 ([(meta left
)] org-table-move-column-left
)
4372 ([(meta right
)] org-table-move-column-right
)
4373 ([(meta shift right
)] org-table-insert-column
)
4374 ([(meta shift up
)] org-table-kill-row
)
4375 ([(meta shift down
)] org-table-insert-row
)
4376 ([(meta up
)] org-table-move-row-up
)
4377 ([(meta down
)] org-table-move-row-down
)
4378 ("\C-c\C-w" org-table-cut-region
)
4379 ("\C-c\M-w" org-table-copy-region
)
4380 ("\C-c\C-y" org-table-paste-rectangle
)
4381 ("\C-c\C-w" org-table-wrap-region
)
4382 ("\C-c-" org-table-insert-hline
)
4383 ("\C-c}" org-table-toggle-coordinate-overlays
)
4384 ("\C-c{" org-table-toggle-formula-debugger
)
4385 ("\C-m" org-table-next-row
)
4386 ([(shift return
)] org-table-copy-down
)
4387 ("\C-c?" org-table-field-info
)
4388 ("\C-c " org-table-blank-field
)
4389 ("\C-c+" org-table-sum
)
4390 ("\C-c=" org-table-eval-formula
)
4391 ("\C-c'" org-table-edit-formulas
)
4392 ("\C-c`" org-table-edit-field
)
4393 ("\C-c*" org-table-recalculate
)
4394 ("\C-c^" org-table-sort-lines
)
4395 ("\M-a" org-table-beginning-of-field
)
4396 ("\M-e" org-table-end-of-field
)
4397 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4399 (while (setq elt
(pop bindings
))
4400 (setq nfunc
(1+ nfunc
))
4401 (setq key
(org-key (car elt
))
4403 cmd
(orgtbl-make-binding fun nfunc key
))
4404 (org-defkey orgtbl-mode-map key cmd
))
4406 ;; Special treatment needed for TAB, RET and DEL
4407 (org-defkey orgtbl-mode-map
[(return)]
4408 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4409 (org-defkey orgtbl-mode-map
"\C-m"
4410 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4411 (org-defkey orgtbl-mode-map
[(tab)]
4412 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4413 (org-defkey orgtbl-mode-map
"\C-i"
4414 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4415 (org-defkey orgtbl-mode-map
[(shift tab
)]
4416 (orgtbl-make-binding 'org-table-previous-field
104
4417 [(shift tab
)] [(tab)] "\C-i"))
4418 (org-defkey orgtbl-mode-map
[backspace]
4419 (orgtbl-make-binding 'org-delete-backward-char 109
4420 [backspace] (kbd "DEL")))
4422 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4423 (orgtbl-make-binding 'org-table-previous-field
107
4424 [S-iso-lefttab
] [backtab] [(shift tab)]
4427 (org-defkey orgtbl-mode-map [backtab]
4428 (orgtbl-make-binding 'org-table-previous-field
108
4429 [backtab] [S-iso-lefttab] [(shift tab)]
4432 (org-defkey orgtbl-mode-map "\M-\C-m"
4433 (orgtbl-make-binding 'org-table-wrap-region 105
4434 "\M-\C-m" [(meta return)]))
4435 (org-defkey orgtbl-mode-map [(meta return)]
4436 (orgtbl-make-binding 'org-table-wrap-region 106
4437 [(meta return)] "\M-\C-m"))
4439 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4440 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4442 (when orgtbl-optimized
4443 ;; If the user wants maximum table support, we need to hijack
4444 ;; some standard editing functions
4445 (org-remap orgtbl-mode-map
4446 'self-insert-command 'orgtbl-self-insert-command
4447 'delete-char 'org-delete-char
4448 'delete-backward-char 'org-delete-backward-char)
4449 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4450 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4452 ["Create or convert" org-table-create-or-convert-from-region
4453 :active (not (org-at-table-p)) :keys "C-c |" ]
4455 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4456 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4457 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4458 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4460 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4461 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4462 ["Copy Field from Above"
4463 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4466 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4467 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4468 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4469 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4471 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4472 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4473 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4474 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4475 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4477 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4479 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4480 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4481 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4482 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4485 ["Insert table template" orgtbl-insert-radio-table
4486 (assq major-mode orgtbl-radio-table-templates)]
4487 ["Comment/uncomment table" orgtbl-toggle-comment t])
4489 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4490 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4491 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4492 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4493 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4494 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4495 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4496 ["Sum Column/Rectangle" org-table-sum
4497 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4498 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4500 org-table-toggle-formula-debugger :active (org-at-table-p)
4502 :style toggle :selected org-table-formula-debug]
4503 ["Show Col/Row Numbers"
4504 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4506 :style toggle :selected org-table-overlay-coordinates]
4509 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4510 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4513 (defun orgtbl-ctrl-c-ctrl-c (arg)
4514 "If the cursor is inside a table, realign the table.
4515 If it is a table to be sent away to a receiver, do it.
4516 With prefix arg, also recompute table."
4518 (let ((case-fold-search t) (pos (point)) action)
4520 (beginning-of-line 1)
4522 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4523 ((looking-at "[ \t]*|") pos)
4524 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4528 (org-table-maybe-eval-formula)
4530 (call-interactively 'org-table-recalculate)
4531 (org-table-maybe-recalculate-line))
4532 (call-interactively 'org-table-align)
4533 (when (orgtbl-send-table 'maybe)
4534 (run-hooks 'orgtbl-after-send-table-hook)))
4535 ((eq action 'recalc)
4537 (beginning-of-line 1)
4538 (skip-chars-backward " \r\n\t")
4539 (if (org-at-table-p)
4540 (org-call-with-arg 'org-table-recalculate t))))
4541 (t (let (orgtbl-mode)
4542 (call-interactively (key-binding "\C-c\C-c")))))))
4544 (defun orgtbl-create-or-convert-from-region (_arg)
4545 "Create table or convert region to table, if no conflicting binding.
4546 This installs the table binding `C-c |', but only if there is no
4547 conflicting binding to this key outside orgtbl-mode."
4549 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4551 (call-interactively cmd)
4552 (call-interactively 'org-table-create-or-convert-from-region))))
4554 (defun orgtbl-tab (arg)
4555 "Justification and field motion for `orgtbl-mode'."
4557 (if arg (org-table-edit-field t)
4558 (org-table-justify-field-maybe)
4559 (org-table-next-field)))
4561 (defun orgtbl-ret ()
4562 "Justification and field motion for `orgtbl-mode'."
4566 (org-table-justify-field-maybe)
4567 (org-table-next-row)))
4569 (defun orgtbl-self-insert-command (N)
4570 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4571 If the cursor is in a table looking at whitespace, the whitespace is
4572 overwritten, and the table is not marked as requiring realignment."
4574 (if (and (org-at-table-p)
4576 (and org-table-auto-blank-field
4577 (member last-command
4578 '(orgtbl-hijacker-command-100
4579 orgtbl-hijacker-command-101
4580 orgtbl-hijacker-command-102
4581 orgtbl-hijacker-command-103
4582 orgtbl-hijacker-command-104
4583 orgtbl-hijacker-command-105
4585 (org-table-blank-field))
4588 (looking-at "[^|\n]* \\( \\)|"))
4589 (let (org-table-may-need-update)
4590 (delete-region (match-beginning 1) (match-end 1))
4591 (self-insert-command N))
4592 (setq org-table-may-need-update t)
4595 (cmd (or (key-binding
4596 (or (and (listp function-key-map)
4597 (setq a (assoc last-input-event function-key-map))
4599 (vector last-input-event)))
4600 'self-insert-command)))
4601 (call-interactively cmd)
4602 (if (and org-self-insert-cluster-for-undo
4603 (eq cmd 'self-insert-command))
4604 (if (not (eq last-command 'orgtbl-self-insert-command))
4605 (setq org-self-insert-command-undo-counter 1)
4606 (if (>= org-self-insert-command-undo-counter 20)
4607 (setq org-self-insert-command-undo-counter 1)
4608 (and (> org-self-insert-command-undo-counter 0)
4610 (not (cadr buffer-undo-list)) ; remove nil entry
4611 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4612 (setq org-self-insert-command-undo-counter
4613 (1+ org-self-insert-command-undo-counter))))))))
4616 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4617 "Regular expression matching exponentials as produced by calc.")
4619 (defun orgtbl-gather-send-defs ()
4620 "Gather a plist of :name, :transform, :params for each destination before
4623 (goto-char (org-table-begin))
4625 (beginning-of-line 0)
4626 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4627 (let ((name (org-no-properties (match-string 1)))
4628 (transform (intern (match-string 2)))
4629 (params (if (match-end 3)
4630 (read (concat "(" (match-string 3) ")")))))
4631 (push (list :name name :transform transform :params params)
4633 (beginning-of-line 0)))
4636 (defun orgtbl-send-replace-tbl (name text)
4637 "Find and replace table NAME with TEXT."
4639 (goto-char (point-min))
4640 (let* ((location-flag nil)
4641 (name (regexp-quote name))
4642 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4643 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4644 (while (re-search-forward begin-re nil t)
4645 (unless location-flag (setq location-flag t))
4646 (let ((beg (line-beginning-position 2)))
4647 (unless (re-search-forward end-re nil t)
4648 (user-error "Cannot find end of receiver location at %d" beg))
4650 (delete-region beg (point))
4651 (insert text "\n")))
4652 (unless location-flag
4653 (user-error "No valid receiver location found in the buffer")))))
4656 (defun org-table-to-lisp (&optional txt)
4657 "Convert the table at point to a Lisp structure.
4658 The structure will be a list. Each item is either the symbol `hline'
4659 for a horizontal separator line, or a list of field values as strings.
4660 The table is taken from the parameter TXT, or from the buffer at point."
4661 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4663 (buffer-substring-no-properties (org-table-begin)
4666 (if (string-match org-table-hline-regexp x) 'hline
4667 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4668 (org-split-string txt "[ \t]*\n[ \t]*"))))
4670 (defun orgtbl-send-table (&optional maybe)
4671 "Send a transformed version of table at point to the receiver position.
4672 With argument MAYBE, fail quietly if no transformation is defined
4676 (unless (org-at-table-p) (user-error "Not at a table"))
4677 ;; when non-interactive, we assume align has just happened.
4678 (when (called-interactively-p 'any) (org-table-align))
4679 (let ((dests (orgtbl-gather-send-defs))
4680 (table (org-table-to-lisp
4681 (buffer-substring-no-properties (org-table-begin)
4685 (if maybe (throw 'exit nil)
4686 (user-error "Don't know how to transform this table")))
4687 (dolist (dest dests)
4688 (let ((name (plist-get dest :name))
4689 (transform (plist-get dest :transform))
4690 (params (plist-get dest :params)))
4691 (unless (fboundp transform)
4692 (user-error "No such transformation function %s" transform))
4693 (orgtbl-send-replace-tbl name (funcall transform table params)))
4695 (message "Table converted and installed at %d receiver location%s"
4696 ntbl (if (> ntbl 1) "s" ""))
4697 (and (> ntbl 0) ntbl))))
4699 (defun org-remove-by-index (list indices &optional i0)
4700 "Remove the elements in LIST with indices in INDICES.
4701 First element has index 0, or I0 if given."
4704 (if (integerp indices) (setq indices (list indices)))
4705 (setq i0 (1- (or i0 0)))
4706 (delq :rm (mapcar (lambda (x)
4708 (if (memq i0 indices) :rm x))
4711 (defun orgtbl-toggle-comment ()
4712 "Comment or uncomment the orgtbl at point."
4714 (let* ((case-fold-search t)
4715 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4716 (re2 (concat "^" orgtbl-line-start-regexp))
4717 (commented (save-excursion (beginning-of-line 1)
4718 (cond ((looking-at re1) t)
4719 ((looking-at re2) nil)
4720 (t (user-error "Not at an org table")))))
4721 (re (if commented re1 re2))
4724 (beginning-of-line 1)
4725 (while (looking-at re) (beginning-of-line 0))
4726 (beginning-of-line 2)
4728 (while (looking-at re) (beginning-of-line 2))
4730 (comment-region beg end (if commented '(4) nil))))
4732 (defun orgtbl-insert-radio-table ()
4733 "Insert a radio table template appropriate for this major mode."
4735 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4738 (unless e (user-error "No radio table setup defined for %s" major-mode))
4739 (setq name (read-string "Table name: "))
4740 (while (string-match "%n" txt)
4741 (setq txt (replace-match name t t txt)))
4742 (or (bolp) (insert "\n"))
4748 (defun orgtbl-to-generic (table params)
4749 "Convert the orgtbl-mode TABLE to some other format.
4751 This generic routine can be used for many standard cases.
4753 TABLE is a list, each entry either the symbol `hline' for
4754 a horizontal separator line, or a list of fields for that
4755 line. PARAMS is a property list of parameters that can
4756 influence the conversion.
4758 Valid parameters are:
4762 Export back-end used as a basis to transcode elements of the
4763 table, when no specific parameter applies to it. It is also
4764 used to translate cells contents. You can prevent this by
4765 setting :raw property to a non-nil value.
4769 When non-nil, only convert rows, not the table itself. This is
4770 equivalent to setting to the empty string both :tstart
4771 and :tend, which see.
4775 When set to an integer N, skip the first N lines of the table.
4776 Horizontal separation lines do count for this parameter!
4780 List of columns that should be skipped. If the table has
4781 a column with calculation marks, that column is automatically
4782 discarded beforehand.
4786 String to be inserted on horizontal separation lines. May be
4787 nil to ignore these lines altogether.
4791 Separator between two fields, as a string.
4793 Each in the following group may be either a string or a function
4794 of no arguments returning a string:
4798 Strings to start and end the table. Ignored when :splice is t.
4802 Strings to start and end a new table line.
4806 Strings to start and end the last table line. Default,
4807 respectively, to :lstart and :lend.
4809 Each in the following group may be a string or a function of one
4810 argument (either the cells in the current row, as a list of
4811 strings, or the current cell) returning a string:
4815 Format string for an entire row, with enough %s to capture all
4816 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4820 Format for the entire last line, defaults to :lfmt.
4824 A format to be used to wrap the field, should contain %s for
4825 the original field value. For example, to wrap everything in
4826 dollars, you could use :fmt \"$%s$\". This may also be
4827 a property list with column numbers and format strings, or
4830 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4832 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4834 Same as above, specific for the header lines in the table.
4835 All lines before the first hline are treated as header. If
4836 any of these is not present, the data line value is used.
4838 This may be either a string or a function of two arguments:
4842 Use this format to print numbers with exponential. The format
4843 should have %s twice for inserting mantissa and exponent, for
4844 example \"%s\\\\times10^{%s}\". This may also be a property
4845 list with column numbers and format strings or functions.
4846 :fmt will still be applied after :efmt."
4847 ;; Make sure `org-export-create-backend' is available.
4849 (let* ((backend (plist-get params :backend))
4851 ;; Build a custom back-end according to PARAMS. Before
4852 ;; defining a translator, check if there is anything to do.
4853 ;; When there isn't, let BACKEND handle the element.
4854 (org-export-create-backend
4855 :parent (or backend 'org)
4857 `((table . ,(org-table--to-generic-table params))
4858 (table-row . ,(org-table--to-generic-row params))
4859 (table-cell . ,(org-table--to-generic-cell params))
4860 ;; Macros are not going to be expanded. However, no
4861 ;; regular back-end has a transcoder for them. We
4862 ;; provide one so they are not ignored, but displayed
4864 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4866 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4867 ;; Initialize communication channel in INFO.
4869 (let ((org-inhibit-startup t)) (org-mode))
4870 (let ((standard-output (current-buffer))
4871 (org-element-use-cache nil))
4873 (cond ((eq e 'hline) (princ "|--\n"))
4875 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4877 ;; Add back-end specific filters, but not user-defined ones. In
4878 ;; particular, make sure to call parse-tree filters on the
4881 (let ((org-export-filters-alist nil))
4882 (org-export-install-filters
4884 (org-export-get-environment backend nil params)
4885 `(:back-end ,(org-export-get-backend backend))))))
4887 (org-export-filter-apply-functions
4888 (plist-get info :filter-parse-tree)
4889 (org-element-map (org-element-parse-buffer) 'table
4892 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4893 (user-error "Unknown :backend value"))
4894 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4895 ;; Handle :skip parameter.
4896 (let ((skip (plist-get info :skip)))
4898 (unless (wholenump skip) (user-error "Wrong :skip value"))
4900 (org-element-map data 'table-row
4903 (org-element-extract-element row)
4907 ;; Handle :skipcols parameter.
4908 (let ((skipcols (plist-get info :skipcols)))
4910 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4911 (org-element-map data 'table
4913 (let ((specialp (org-export-table-has-special-column-p table)))
4914 (dolist (row (org-element-contents table))
4915 (when (eq (org-element-property :type row) 'standard)
4917 (dolist (cell (nthcdr (if specialp 1 0)
4918 (org-element-contents row)))
4919 (when (memq c skipcols)
4920 (org-element-extract-element cell))
4921 (cl-incf c))))))))))
4922 ;; Since we are going to export using a low-level mechanism,
4923 ;; ignore special column and special rows manually.
4924 (let ((special? (org-export-table-has-special-column-p data))
4926 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4928 (when (if (eq (org-element-type datum) 'table-row)
4929 (org-export-table-row-is-special-p datum nil)
4930 (org-export-first-sibling-p datum nil))
4931 (push datum ignore))))
4932 (setq info (plist-put info :ignore-list ignore)))
4933 ;; We use a low-level mechanism to export DATA so as to skip all
4934 ;; usual pre-processing and post-processing, i.e., hooks, Babel
4935 ;; code evaluation, include keywords and macro expansion. Only
4936 ;; back-end specific filters are retained.
4937 (let ((output (org-export-data-with-backend data custom-backend info)))
4938 ;; Remove final newline.
4939 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4941 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4942 (cond ((null value) nil)
4943 ((functionp value) `(funcall ',value ,@args))
4945 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4946 (args `(format ,value ,@args))
4948 ((and with-cons (consp value))
4949 `(let ((val (cadr (memq column ',value))))
4950 (cond ((null val) contents)
4951 ((stringp val) (format val ,@args))
4952 ((functionp val) (funcall val ,@args))
4953 (t (user-error "Wrong %s value" ,name)))))
4954 (t (user-error "Wrong %s value" name))))
4956 (defun org-table--to-generic-table (params)
4957 "Return custom table transcoder according to PARAMS.
4958 PARAMS is a plist. See `orgtbl-to-generic' for more
4960 (let ((backend (plist-get params :backend))
4961 (splice (plist-get params :splice))
4962 (tstart (plist-get params :tstart))
4963 (tend (plist-get params :tend)))
4964 `(lambda (table contents info)
4966 ,(and tstart (not splice)
4967 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4968 ,(if (or (not backend) tstart tend splice) 'contents
4969 `(org-export-with-backend ',backend table contents info))
4970 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4972 (defun org-table--to-generic-row (params)
4973 "Return custom table row transcoder according to PARAMS.
4974 PARAMS is a plist. See `orgtbl-to-generic' for more
4976 (let* ((backend (plist-get params :backend))
4977 (lstart (plist-get params :lstart))
4978 (llstart (plist-get params :llstart))
4979 (hlstart (plist-get params :hlstart))
4980 (hllstart (plist-get params :hllstart))
4981 (lend (plist-get params :lend))
4982 (llend (plist-get params :llend))
4983 (hlend (plist-get params :hlend))
4984 (hllend (plist-get params :hllend))
4985 (lfmt (plist-get params :lfmt))
4986 (llfmt (plist-get params :llfmt))
4987 (hlfmt (plist-get params :hlfmt))
4988 (hllfmt (plist-get params :hllfmt)))
4989 `(lambda (row contents info)
4990 (if (eq (org-element-property :type row) 'rule)
4992 ((plist-member params :hline)
4993 (org-table--generic-apply (plist-get params :hline) ":hline"))
4994 (backend `(org-export-with-backend ',backend row nil info)))
4995 (let ((headerp ,(and (or hlfmt hlstart hlend)
4996 '(org-export-table-row-in-header-p row info)))
4998 ,(and (or hllfmt hllstart hllend)
4999 '(org-export-table-row-ends-header-p row info)))
5000 (lastp (not (org-export-get-next-element row info))))
5002 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5003 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5004 ;; `:lstart', `:lend' and their relatives.
5006 '(org-element-map row 'table-cell
5008 ;; Export all cells, without separators.
5010 ;; Use `org-export-data-with-backend'
5011 ;; instead of `org-export-data' to eschew
5012 ;; cached values, which
5013 ;; ignore :orgtbl-ignore-sep parameter.
5014 (org-export-data-with-backend
5016 (plist-get info :back-end)
5017 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5021 `(last-header-p ,(org-table--generic-apply
5022 hllfmt ":hllfmt" nil cells)))
5024 `(headerp ,(org-table--generic-apply
5025 hlfmt ":hlfmt" nil cells)))
5027 `(lastp ,(org-table--generic-apply
5028 llfmt ":llfmt" nil cells)))
5030 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5034 (or hllstart hllend)
5037 ,(org-table--generic-apply hllstart ":hllstart")
5039 ,(org-table--generic-apply hllend ":hllend"))))
5044 ,(org-table--generic-apply hlstart ":hlstart")
5046 ,(org-table--generic-apply hlend ":hlend"))))
5051 ,(org-table--generic-apply llstart ":llstart")
5053 ,(org-table--generic-apply llend ":llend"))))
5058 ,(org-table--generic-apply lstart ":lstart")
5060 ,(org-table--generic-apply lend ":lend")))
5062 `(org-export-with-backend
5063 ',backend row contents info))
5064 (t 'contents)))))))))))))))
5066 (defun org-table--to-generic-cell (params)
5067 "Return custom table cell transcoder according to PARAMS.
5068 PARAMS is a plist. See `orgtbl-to-generic' for more
5070 (let* ((backend (plist-get params :backend))
5071 (efmt (plist-get params :efmt))
5072 (fmt (plist-get params :fmt))
5073 (hfmt (plist-get params :hfmt))
5074 (sep (plist-get params :sep))
5075 (hsep (plist-get params :hsep)))
5076 `(lambda (cell contents info)
5077 ;; Make sure that contents are exported as Org data when :raw
5078 ;; parameter is non-nil.
5079 ,(when (and backend (plist-get params :raw))
5081 ;; Since we don't know what are the pseudo object
5082 ;; types defined in backend, we cannot pass them to
5083 ;; `org-element-interpret-data'. As a consequence,
5084 ;; they will be treated as pseudo elements, and will
5085 ;; have newlines appended instead of spaces.
5086 ;; Therefore, we must make sure :post-blank value is
5087 ;; really turned into spaces.
5088 (replace-regexp-in-string
5091 (org-element-interpret-data
5092 (org-element-contents cell))))))
5094 (let ((headerp ,(and (or hfmt hsep)
5095 '(org-export-table-row-in-header-p
5096 (org-export-get-parent-element cell) info)))
5098 ;; Call costly `org-export-table-cell-address' only if
5099 ;; absolutely necessary, i.e., if one
5100 ;; of :fmt :efmt :hmft has a "plist type" value.
5101 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5102 (list efmt hfmt fmt))
5103 '(1+ (cdr (org-export-table-cell-address cell info))))))
5105 ;; Check if we can apply `:efmt' on CONTENTS.
5107 `(when (string-match orgtbl-exp-regexp contents)
5108 (let ((mantissa (match-string 1 contents))
5109 (exponent (match-string 2 contents)))
5110 (setq contents ,(org-table--generic-apply
5111 efmt ":efmt" t 'mantissa 'exponent)))))
5112 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5114 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5115 hfmt ":hfmt" t 'contents))))
5116 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5117 fmt ":fmt" t 'contents))))))
5118 ;; If a separator is provided, use it instead of BACKEND's.
5119 ;; Separators are ignored when LFMT (or equivalent) is
5123 `(if (or ,(and (not sep) '(not headerp))
5124 (plist-get info :orgtbl-ignore-sep)
5125 (not (org-export-get-next-element cell info)))
5126 ,(if (not backend) 'contents
5127 `(org-export-with-backend ',backend cell contents info))
5129 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5131 (backend `(org-export-with-backend ',backend cell contents info))
5135 (defun orgtbl-to-tsv (table params)
5136 "Convert the orgtbl-mode table to TAB separated material."
5137 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5140 (defun orgtbl-to-csv (table params)
5141 "Convert the orgtbl-mode table to CSV material.
5142 This does take care of the proper quoting of fields with comma or quotes."
5143 (orgtbl-to-generic table
5144 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5148 (defun orgtbl-to-latex (table params)
5149 "Convert the orgtbl-mode TABLE to LaTeX.
5151 TABLE is a list, each entry either the symbol `hline' for
5152 a horizontal separator line, or a list of fields for that line.
5153 PARAMS is a property list of parameters that can influence the
5154 conversion. All parameters from `orgtbl-to-generic' are
5155 supported. It is also possible to use the following ones:
5159 When non-nil, use formal \"booktabs\" style.
5163 Specify environment to use, as a string. If you use
5164 \"longtable\", you may also want to specify :language property,
5165 as a string, to get proper continuation strings."
5170 ;; Provide sane default values.
5171 (list :backend 'latex
5172 :latex-default-table-mode 'table
5173 :latex-tables-centered nil
5174 :latex-tables-booktabs (plist-get params :booktabs)
5175 :latex-table-scientific-notation nil
5176 :latex-default-table-environment
5177 (or (plist-get params :environment) "tabular"))
5181 (defun orgtbl-to-html (table params)
5182 "Convert the orgtbl-mode TABLE to HTML.
5184 TABLE is a list, each entry either the symbol `hline' for
5185 a horizontal separator line, or a list of fields for that line.
5186 PARAMS is a property list of parameters that can influence the
5187 conversion. All parameters from `orgtbl-to-generic' are
5188 supported. It is also possible to use the following one:
5192 Attributes and values, as a plist, which will be used in
5198 ;; Provide sane default values.
5199 (list :backend 'html
5200 :html-table-data-tags '("<td%s>" . "</td>")
5201 :html-table-use-header-tags-for-first-column nil
5202 :html-table-align-individual-fields t
5203 :html-table-row-tags '("<tr>" . "</tr>")
5204 :html-table-attributes
5205 (if (plist-member params :attributes)
5206 (plist-get params :attributes)
5207 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5212 (defun orgtbl-to-texinfo (table params)
5213 "Convert the orgtbl-mode TABLE to Texinfo.
5215 TABLE is a list, each entry either the symbol `hline' for
5216 a horizontal separator line, or a list of fields for that line.
5217 PARAMS is a property list of parameters that can influence the
5218 conversion. All parameters from `orgtbl-to-generic' are
5219 supported. It is also possible to use the following one:
5223 Column widths, as a string. When providing column fractions,
5224 \"@columnfractions\" command can be omitted."
5225 (require 'ox-texinfo)
5230 (list :backend 'texinfo
5231 :texinfo-tables-verbatim nil
5232 :texinfo-table-scientific-notation nil)
5234 (columns (let ((w (plist-get params :columns)))
5236 ((string-match-p "{\\|@columnfractions " w) w)
5237 (t (concat "@columnfractions " w))))))
5238 (if (not columns) output
5239 (replace-regexp-in-string
5240 "@multitable \\(.*\\)" columns output t nil 1))))
5243 (defun orgtbl-to-orgtbl (table params)
5244 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5246 TABLE is a list, each entry either the symbol `hline' for
5247 a horizontal separator line, or a list of fields for that line.
5248 PARAMS is a property list of parameters that can influence the
5249 conversion. All parameters from `orgtbl-to-generic' are
5252 Useful when slicing one table into many. The :hline, :sep,
5253 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5254 be set to provide ORGTBL directives for the generated table."
5256 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5258 (defun orgtbl-to-table.el (table params)
5259 "Convert the orgtbl-mode TABLE into a table.el table.
5260 TABLE is a list, each entry either the symbol `hline' for
5261 a horizontal separator line, or a list of fields for that line.
5262 PARAMS is a property list of parameters that can influence the
5263 conversion. All parameters from `orgtbl-to-generic' are
5266 (insert (orgtbl-to-orgtbl table params))
5268 (replace-regexp-in-string
5270 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5272 (defun orgtbl-to-unicode (table params)
5273 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5275 TABLE is a list, each entry either the symbol `hline' for
5276 a horizontal separator line, or a list of fields for that line.
5277 PARAMS is a property list of parameters that can influence the
5278 conversion. All parameters from `orgtbl-to-generic' are
5279 supported. It is also possible to use the following ones:
5283 When non-nil, use \"ascii-art-to-unicode\" package to translate
5284 the table. You can download it here:
5285 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5289 When non-nil, narrow columns width than provided width cookie,
5290 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5295 (list :backend 'ascii
5296 :ascii-charset 'utf-8
5297 :ascii-table-widen-columns (not (plist-get params :narrow))
5298 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5301 ;; Put the cursor in a column containing numerical values
5304 ;; A new column is added with a bar plot.
5305 ;; When the table is refreshed (C-u C-c *),
5306 ;; the plot is updated to reflect the new values.
5308 (defun orgtbl-ascii-draw (value min max &optional width characters)
5309 "Draw an ascii bar in a table.
5310 VALUE is the value to plot, it determines the width of the bar to draw.
5311 MIN is the value that will be displayed as empty (zero width bar).
5312 MAX is the value that will draw a bar filling all the WIDTH.
5313 WIDTH is the span in characters from MIN to MAX.
5314 CHARACTERS is a string that will compose the bar, with shades of grey
5315 from pure white to pure black. It defaults to a 10 characters string
5316 of regular ascii characters."
5317 (let* ((width (ceiling (or width 12)))
5318 (characters (or characters " .:;c!lhVHW"))
5319 (len (1- (length characters)))
5320 (value (float (if (numberp value)
5321 value (string-to-number value))))
5322 (relative (/ (- value min) (- max min)))
5323 (steps (round (* relative width len))))
5324 (cond ((< steps 0) "too small")
5325 ((> steps (* width len)) "too large")
5326 (t (let* ((int-division (/ steps len))
5327 (remainder (- steps (* int-division len))))
5328 (concat (make-string int-division (elt characters len))
5329 (string (elt characters remainder))))))))
5332 (defun orgtbl-ascii-plot (&optional ask)
5333 "Draw an ASCII bar plot in a column.
5335 With cursor in a column containing numerical values, this function
5336 will draw a plot in a new column.
5338 ASK, if given, is a numeric prefix to override the default 12
5339 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5341 which will prompt for the width."
5343 (let ((col (org-table-current-column))
5344 (min 1e999) ; 1e999 will be converted to infinity
5345 (max -1e999) ; which is the desired result
5346 (table (org-table-to-lisp))
5349 (read-number "Length of column " 12))
5352 ;; Skip any hline a the top of table.
5353 (while (eq (car table) 'hline) (setq table (cdr table)))
5354 ;; Skip table header if any.
5355 (dolist (x (or (cdr (memq 'hline table)) table))
5357 (setq x (nth (1- col) x))
5359 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5361 (setq x (string-to-number x))
5362 (when (> min x) (setq min x))
5363 (when (< max x) (setq max x)))))
5364 (org-table-insert-column)
5365 (org-table-move-column-right)
5366 (org-table-store-formulas
5369 (concat "$" (number-to-string (1+ col)))
5370 (format "'(%s $%s %s %s %s)"
5371 "orgtbl-ascii-draw" col min max length))
5372 (org-table-get-stored-formulas)))
5373 (org-table-recalculate t)))
5375 ;; Example of extension: unicode characters
5376 ;; Here are two examples of different styles.
5378 ;; Unicode block characters are used to give a smooth effect.
5379 ;; See http://en.wikipedia.org/wiki/Block_Elements
5380 ;; Use one of those drawing functions
5381 ;; - orgtbl-ascii-draw (the default ascii)
5382 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5383 ;; - orgtbl-uc-draw-cont (smooth unicode)
5385 ;; This is best viewed with the "DejaVu Sans Mono" font
5386 ;; (use M-x set-default-font).
5388 (defun orgtbl-uc-draw-grid (value min max &optional width)
5389 "Draw a bar in a table using block unicode characters.
5390 It is a variant of orgtbl-ascii-draw with Unicode block
5391 characters, for a smooth display. Bars appear as grids (to the
5392 extent the font allows)."
5393 ;; http://en.wikipedia.org/wiki/Block_Elements
5394 ;; best viewed with the "DejaVu Sans Mono" font.
5395 (orgtbl-ascii-draw value min max width
5396 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5398 (defun orgtbl-uc-draw-cont (value min max &optional width)
5399 "Draw a bar in a table using block unicode characters.
5400 It is a variant of orgtbl-ascii-draw with Unicode block
5401 characters, for a smooth display. Bars are solid (to the extent
5403 (orgtbl-ascii-draw value min max width
5404 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5406 (defun org-table-get-remote-range (name-or-id form)
5407 "Get a field value or a list of values in a range from table at ID.
5409 NAME-OR-ID may be the name of a table in the current file as set
5410 by a \"#+NAME:\" directive. The first table following this line
5411 will then be used. Alternatively, it may be an ID referring to
5412 any entry, also in a different file. In this case, the first
5413 table in that entry will be referenced.
5414 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5415 \"@I$2..@II$2\". All the references must be absolute, not relative.
5417 The return value is either a single string for a single field, or a
5418 list of the fields in the rectangle."
5420 (let ((case-fold-search t) (id-loc nil)
5421 ;; Protect a bunch of variables from being overwritten by
5422 ;; the context of the remote table.
5423 org-table-column-names org-table-column-name-regexp
5424 org-table-local-parameters org-table-named-field-locations
5425 org-table-current-line-types
5426 org-table-current-begin-pos org-table-dlines
5427 org-table-current-ncol
5428 org-table-hlines org-table-last-alignment
5429 org-table-last-column-widths org-table-last-alignment
5430 org-table-last-column-widths
5432 (setq form (org-table-convert-refs-to-rc form))
5433 (org-with-wide-buffer
5434 (goto-char (point-min))
5435 (if (re-search-forward
5436 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5437 (regexp-quote name-or-id) "[ \t]*$")
5439 (setq buffer (current-buffer) loc (match-beginning 0))
5440 (setq id-loc (org-id-find name-or-id 'marker))
5441 (unless (and id-loc (markerp id-loc))
5442 (user-error "Can't find remote table \"%s\"" name-or-id))
5443 (setq buffer (marker-buffer id-loc)
5444 loc (marker-position id-loc))
5445 (move-marker id-loc nil))
5446 (with-current-buffer buffer
5447 (org-with-wide-buffer
5450 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5451 (not (match-beginning 1)))
5452 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5454 (setq form (org-table-formula-substitute-names
5455 (org-table-formula-handle-first/last-rc form)))
5456 (if (and (string-match org-table-range-regexp form)
5457 (> (length (match-string 0 form)) 1))
5458 (org-table-get-range
5459 (match-string 0 form) org-table-current-begin-pos 1)
5462 (defun org-table-remote-reference-indirection (form)
5463 "Return formula with table remote references substituted by indirection.
5464 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5465 This indirection works only with the format @ROW$COLUMN. The
5466 format \"B3\" is not supported because it can not be
5467 distinguished from a plain table name or ID."
5469 ;; Same as in `org-table-eval-formula'.
5470 (concat "\\<remote([ \t]*\\("
5471 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5473 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5474 (replace-regexp-in-string
5478 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5479 (org-table-get-range
5480 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5485 (defmacro org-define-lookup-function (mode)
5486 (let ((mode-str (symbol-name mode))
5487 (first-p (eq mode 'first))
5488 (all-p (eq mode 'all)))
5489 (let ((plural-str (if all-p "s" "")))
5490 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5491 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5492 If R-LIST is nil, return matching element%s of S-LIST.
5493 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5494 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5495 This function is generated by a call to the macro `org-define-lookup-function'."
5496 mode-str plural-str plural-str plural-str)
5497 (let ,(let ((lvars '((p (or predicate 'equal))
5499 (rl (or r-list s-list))
5501 (if first-p (cons '(match-p nil) lvars) lvars))
5502 (while ,(if first-p '(and (not match-p) sl) 'sl)
5503 (when (funcall p val (car sl))
5504 ,(when first-p '(setq match-p t))
5505 (let ((rval (car rl)))
5506 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5507 (setq sl (cdr sl) rl (cdr rl)))
5510 (org-define-lookup-function first)
5511 (org-define-lookup-function last)
5512 (org-define-lookup-function all)
5514 (provide 'org-table)
5517 ;; generated-autoload-file: "org-loaddefs.el"
5520 ;;; org-table.el ends here