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))
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]+\\)|")
1490 (match-beginning 1) (match-end 1)
1491 (match-beginning 2) (match-end 2))))
1493 (set-marker end nil
)
1494 (org-table-goto-column colpos
)
1496 (when (or (not org-table-fix-formulas-confirm
)
1497 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1498 (org-table-fix-formulas
1499 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1500 (cons (number-to-string colpos
) (number-to-string col
))))
1501 (org-table-fix-formulas
1502 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1503 (cons (number-to-string colpos
) (number-to-string col
)))))))
1506 (defun org-table-move-row-down ()
1507 "Move table row down."
1509 (org-table-move-row nil
))
1511 (defun org-table-move-row-up ()
1512 "Move table row up."
1514 (org-table-move-row 'up
))
1517 (defun org-table-move-row (&optional up
)
1518 "Move the current table line down. With arg UP, move it up."
1520 (let* ((col (current-column))
1522 (hline1p (save-excursion (beginning-of-line 1)
1523 (looking-at org-table-hline-regexp
)))
1524 (dline1 (org-table-current-dline))
1525 (dline2 (+ dline1
(if up -
1 1)))
1528 (beginning-of-line tonew
)
1529 (unless (org-at-table-p)
1531 (user-error "Cannot move row further"))
1532 (setq hline2p
(looking-at org-table-hline-regexp
))
1534 (beginning-of-line 1)
1536 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1537 (delete-region (point) (1+ (point-at-eol)))
1538 (beginning-of-line tonew
)
1540 (beginning-of-line 0)
1541 (org-move-to-column col
)
1542 (unless (or hline1p hline2p
1543 (not (or (not org-table-fix-formulas-confirm
)
1544 (funcall org-table-fix-formulas-confirm
1545 "Fix formulas? "))))
1546 (org-table-fix-formulas
1547 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1548 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1551 (defun org-table-insert-row (&optional arg
)
1552 "Insert a new row above the current line into the table.
1553 With prefix ARG, insert below the current line."
1555 (unless (org-at-table-p) (user-error "Not at a table"))
1556 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1557 (new (org-table-clean-line line
)))
1558 ;; Fix the first field if necessary
1559 (if (string-match "^[ \t]*| *[#$] *|" line
)
1560 (setq new
(replace-match (match-string 0 line
) t t new
)))
1561 (beginning-of-line (if arg
2 1))
1562 ;; Buffer may not end of a newline character, so ensure
1563 ;; (beginning-of-line 2) moves point to a new line.
1564 (unless (bolp) (insert "\n"))
1565 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1566 (beginning-of-line 0)
1567 (re-search-forward "| ?" (line-end-position) t
)
1568 (when (or org-table-may-need-update org-table-overlay-coordinates
)
1570 (when (or (not org-table-fix-formulas-confirm
)
1571 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1572 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1575 (defun org-table-insert-hline (&optional above
)
1576 "Insert a horizontal-line below the current line into the table.
1577 With prefix ABOVE, insert above the current line."
1579 (if (not (org-at-table-p))
1580 (user-error "Not at a table"))
1581 (when (eobp) (insert "\n") (backward-char 1))
1582 (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
1584 (let ((line (org-table-clean-line
1585 (buffer-substring (point-at-bol) (point-at-eol))))
1586 (col (current-column)))
1587 (while (string-match "|\\( +\\)|" line
)
1588 (setq line
(replace-match
1589 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1590 ?-
) "|") t t line
)))
1591 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1592 (beginning-of-line (if above
1 2))
1594 (beginning-of-line (if above
1 -
1))
1595 (org-move-to-column col
)
1596 (and org-table-overlay-coordinates
(org-table-align))))
1599 (defun org-table-hline-and-move (&optional same-column
)
1600 "Insert a hline and move to the row below that line."
1602 (let ((col (org-table-current-column)))
1603 (org-table-maybe-eval-formula)
1604 (org-table-maybe-recalculate-line)
1605 (org-table-insert-hline)
1607 (if (looking-at "\n[ \t]*|-")
1608 (progn (insert "\n|") (org-table-align))
1609 (org-table-next-field))
1610 (if same-column
(org-table-goto-column col
))))
1612 (defun org-table-clean-line (s)
1613 "Convert a table line S into a string with only \"|\" and space.
1614 In particular, this does handle wide and invisible characters."
1615 (if (string-match "^[ \t]*|-" s
)
1616 ;; It's a hline, just map the characters
1617 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1618 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1619 (setq s
(replace-match
1620 (concat "|" (make-string (org-string-width (match-string 1 s
))
1626 (defun org-table-kill-row ()
1627 "Delete the current row or horizontal line from the table."
1629 (if (not (org-at-table-p))
1630 (user-error "Not at a table"))
1631 (let ((col (current-column))
1632 (dline (org-table-current-dline)))
1633 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1634 (if (not (org-at-table-p)) (beginning-of-line 0))
1635 (org-move-to-column col
)
1636 (when (or (not org-table-fix-formulas-confirm
)
1637 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1638 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1642 (defun org-table-sort-lines
1643 (&optional with-case sorting-type getkey-func compare-func interactive?
)
1644 "Sort table lines according to the column at point.
1646 The position of point indicates the column to be used for
1647 sorting, and the range of lines is the range between the nearest
1648 horizontal separator lines, or the entire table of no such lines
1649 exist. If point is before the first column, you will be prompted
1650 for the sorting column. If there is an active region, the mark
1651 specifies the first line and the sorting column, while point
1652 should be in the last line to be included into the sorting.
1654 The command then prompts for the sorting type which can be
1655 alphabetically, numerically, or by time (as given in a time stamp
1656 in the field, or as a HH:MM value). Sorting in reverse order is
1659 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1661 If SORTING-TYPE is specified when this function is called from a Lisp
1662 program, no prompting will take place. SORTING-TYPE must be a character,
1663 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1664 sorting should be done in reverse order.
1666 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1667 a function to be called to extract the key. It must return a value
1668 that is compatible with COMPARE-FUNC, the function used to compare
1671 A non-nil value for INTERACTIVE? is used to signal that this
1672 function is being called interactively."
1673 (interactive (list current-prefix-arg nil nil nil t
))
1674 (when (org-region-active-p) (goto-char (region-beginning)))
1675 ;; Point must be either within a field or before a data line.
1677 (skip-chars-backward " \t")
1678 (when (bolp) (search-forward "|" (line-end-position) t
))
1679 (org-table-check-inside-data-field))
1680 ;; Set appropriate case sensitivity and column used for sorting.
1681 (let ((column (let ((c (org-table-current-column)))
1684 (read-number "Use column N for sorting: "))
1688 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1689 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1691 ;; Narrow buffer to appropriate sorting area.
1692 (if (org-region-active-p)
1693 (progn (goto-char (region-beginning))
1696 (save-excursion (goto-char (region-end))
1697 (line-beginning-position 2))))
1698 (let ((start (org-table-begin))
1699 (end (org-table-end)))
1702 (if (re-search-backward org-table-hline-regexp start t
)
1703 (line-beginning-position 2)
1705 (if (save-excursion (re-search-forward org-table-hline-regexp end t
))
1708 ;; Determine arguments for `sort-subr'. Also record original
1709 ;; position. `org-table-save-field' cannot help here since
1710 ;; sorting is too much destructive.
1711 (let* ((sort-fold-case (not with-case
))
1713 (cons (count-lines (point-min) (line-beginning-position))
1715 (extract-key-from-field
1716 ;; Function to be called on the contents of the field
1717 ;; used for sorting in the current row.
1718 (cl-case sorting-type
1719 ((?n ?N
) #'string-to-number
)
1720 ((?a ?A
) #'org-sort-remove-invisible
)
1723 (cond ((string-match org-ts-regexp-both f
)
1725 (org-time-string-to-time (match-string 0 f
))))
1726 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" f
)
1727 (org-duration-to-minutes (match-string 0 f
)))
1732 (org-read-function "Function for extracting keys: "))
1733 (error "Missing key extractor to sort rows")))
1734 (t (user-error "Invalid sorting type `%c'" sorting-type
))))
1736 (cl-case sorting-type
1743 (concat "Fuction for comparing keys "
1744 "(empty for default `sort-subr' predicate): ")
1746 (goto-char (point-min))
1747 (sort-subr (memq sorting-type
'(?A ?N ?T ?F
))
1750 (while (and (not (eobp))
1751 (not (looking-at org-table-dataline-regexp
)))
1755 (funcall extract-key-from-field
1756 (org-trim (org-table-get-field column
))))
1759 ;; Move back to initial field.
1760 (forward-line (car coordinates
))
1761 (move-to-column (cdr coordinates
))))))
1764 (defun org-table-cut-region (beg end
)
1765 "Copy region in table to the clipboard and blank all relevant fields.
1766 If there is no active region, use just the field at point."
1768 (if (org-region-active-p) (region-beginning) (point))
1769 (if (org-region-active-p) (region-end) (point))))
1770 (org-table-copy-region beg end
'cut
))
1773 (defun org-table-copy-region (beg end
&optional cut
)
1774 "Copy rectangular region in table to clipboard.
1775 A special clipboard is used which can only be accessed
1776 with `org-table-paste-rectangle'."
1778 (if (org-region-active-p) (region-beginning) (point))
1779 (if (org-region-active-p) (region-end) (point))
1780 current-prefix-arg
))
1781 (goto-char (min beg end
))
1782 (org-table-check-inside-data-field)
1783 (let ((beg (line-beginning-position))
1784 (c01 (org-table-current-column))
1786 (goto-char (max beg end
))
1787 (org-table-check-inside-data-field)
1788 (let* ((end (copy-marker (line-end-position)))
1789 (c02 (org-table-current-column))
1790 (column-start (min c01 c02
))
1791 (column-end (max c01 c02
))
1792 (column-number (1+ (- column-end column-start
)))
1793 (rpl (and cut
" ")))
1795 (while (< (point) end
)
1796 (unless (org-at-table-hline-p)
1797 ;; Collect every cell between COLUMN-START and COLUMN-END.
1799 (dotimes (c column-number
)
1800 (push (org-table-get-field (+ c column-start
) rpl
) cols
))
1801 (push (nreverse cols
) region
)))
1803 (set-marker end nil
))
1804 (when cut
(org-table-align))
1805 (setq org-table-clip
(nreverse region
))))
1808 (defun org-table-paste-rectangle ()
1809 "Paste a rectangular region into a table.
1810 The upper right corner ends up in the current field. All involved fields
1811 will be overwritten. If the rectangle does not fit into the present table,
1812 the table is enlarged as needed. The process ignores horizontal separator
1815 (unless (consp org-table-clip
)
1816 (user-error "First cut/copy a region to paste!"))
1817 (org-table-check-inside-data-field)
1818 (let* ((column (org-table-current-column))
1819 (org-enable-table-editor t
)
1820 (org-table-automatic-realign nil
))
1821 (org-table-save-field
1822 (dolist (row org-table-clip
)
1823 (while (org-at-table-hline-p) (forward-line))
1824 ;; If we left the table, create a new row.
1825 (when (and (bolp) (not (looking-at "[ \t]*|")))
1827 (org-table-next-field))
1830 (org-table-goto-column c nil
'force
)
1831 (org-table-get-field nil field
)
1837 (defun org-table-convert ()
1838 "Convert from `org-mode' table to table.el and back.
1839 Obviously, this only works within limits. When an Org table is converted
1840 to table.el, all horizontal separator lines get lost, because table.el uses
1841 these as cell boundaries and has no notion of horizontal lines. A table.el
1842 table can be converted to an Org table only if it does not do row or column
1843 spanning. Multiline cells will become multiple cells. Beware, Org mode
1844 does not test if the table can be successfully converted - it blindly
1845 applies a recipe that works for simple tables."
1848 (if (org-at-table.el-p
)
1849 ;; convert to Org table
1850 (let ((beg (copy-marker (org-table-begin t
)))
1851 (end (copy-marker (org-table-end t
))))
1852 (table-unrecognize-region beg end
)
1854 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1857 (if (org-at-table-p)
1858 ;; convert to table.el table
1859 (let ((beg (copy-marker (org-table-begin)))
1860 (end (copy-marker (org-table-end))))
1861 ;; first, get rid of all horizontal lines
1863 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1865 ;; insert a hline before first
1867 (org-table-insert-hline 'above
)
1868 (beginning-of-line -
1)
1869 ;; insert a hline after each line
1870 (while (progn (beginning-of-line 3) (< (point) end
))
1871 (org-table-insert-hline))
1873 (setq end
(move-marker end
(org-table-end)))
1874 ;; replace "+" at beginning and ending of hlines
1875 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1876 (replace-match "\\1+-"))
1878 (while (re-search-forward "-|[ \t]*$" end t
)
1879 (replace-match "-+"))
1882 (defun org-table-transpose-table-at-point ()
1883 "Transpose Org table at point and eliminate hlines.
1891 will be transposed as
1898 Note that horizontal lines disappear."
1900 (let* ((table (delete 'hline
(org-table-to-lisp)))
1901 (dline_old (org-table-current-line))
1902 (col_old (org-table-current-column))
1903 (contents (mapcar (lambda (_)
1909 (setq tp
(cdr tp
))))
1912 (goto-char (org-table-begin))
1913 (re-search-forward "|")
1915 (delete-region (point) (org-table-end))
1918 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1920 (org-table-goto-line col_old
)
1921 (org-table-goto-column dline_old
))
1925 (defun org-table-wrap-region (arg)
1926 "Wrap several fields in a column like a paragraph.
1927 This is useful if you'd like to spread the contents of a field over several
1928 lines, in order to keep the table compact.
1930 If there is an active region, and both point and mark are in the same column,
1931 the text in the column is wrapped to minimum width for the given number of
1932 lines. Generally, this makes the table more compact. A prefix ARG may be
1933 used to change the number of desired lines. For example, \
1934 `C-2 \\[org-table-wrap-region]'
1935 formats the selected text to two lines. If the region was longer than two
1936 lines, the remaining lines remain empty. A negative prefix argument reduces
1937 the current number of lines by that amount. The wrapped text is pasted back
1938 into the table. If you formatted it to more lines than it was before, fields
1939 further down in the table get overwritten - so you might need to make space in
1942 If there is no region, the current field is split at the cursor position and
1943 the text fragment to the right of the cursor is prepended to the field one
1946 If there is no region, but you specify a prefix ARG, the current field gets
1947 blank, and the content is appended to the field above."
1949 (org-table-check-inside-data-field)
1950 (if (org-region-active-p)
1951 ;; There is a region: fill as a paragraph.
1952 (let ((start (region-beginning)))
1953 (org-table-cut-region (region-beginning) (region-end))
1954 (when (> (length (car org-table-clip
)) 1)
1955 (user-error "Region must be limited to single column"))
1956 (let ((nlines (cond ((not arg
) (length org-table-clip
))
1957 ((< arg
1) (+ (length org-table-clip
) arg
))
1959 (setq org-table-clip
1961 (org-wrap (mapconcat #'car org-table-clip
" ")
1965 (org-table-paste-rectangle))
1966 ;; No region, split the current field at point.
1967 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1968 (skip-chars-forward "^\r\n|"))
1970 (arg ; Combine with field above.
1971 (let ((s (org-table-blank-field))
1972 (col (org-table-current-column)))
1974 (while (org-at-table-hline-p) (forward-line -
1))
1975 (org-table-goto-column col
)
1976 (skip-chars-forward "^|")
1977 (skip-chars-backward " ")
1978 (insert " " (org-trim s
))
1980 ((looking-at "\\([^|]+\\)+|") ; Split field.
1981 (let ((s (match-string 1)))
1982 (replace-match " |")
1983 (goto-char (match-beginning 0))
1984 (org-table-next-row)
1985 (insert (org-trim s
) " ")
1987 (t (org-table-next-row)))))
1989 (defvar org-field-marker nil
)
1992 (defun org-table-edit-field (arg)
1993 "Edit table field in a different window.
1994 This is mainly useful for fields that contain hidden parts.
1996 When called with a `\\[universal-argument]' prefix, just make the full field
1997 visible so that it can be edited in place.
1999 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2000 toggle `org-table-follow-field-mode'."
2002 (unless (org-at-table-p) (user-error "Not at a table"))
2005 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2007 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2008 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2009 (remove-text-properties b e
'(org-cwidth t invisible t
2010 display t intangible t
))
2011 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2012 (font-lock-fontify-block))))
2014 (let ((pos (point-marker))
2016 (if (eq org-table-use-standard-references t
)
2017 (concat (org-number-to-letters (org-table-current-column))
2018 (int-to-string (org-table-current-dline)))
2019 (concat "@" (int-to-string (org-table-current-dline))
2020 "$" (int-to-string (org-table-current-column)))))
2021 (field (org-table-get-field))
2022 (cw (current-window-configuration))
2025 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2026 (when (and (local-variable-p 'org-field-marker
)
2027 (markerp org-field-marker
))
2028 (move-marker org-field-marker nil
))
2030 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2031 (let ((org-inhibit-startup t
)) (org-mode))
2033 (setq truncate-lines nil
)
2035 (goto-char (setq p
(point-max)))
2036 (insert (org-trim field
))
2037 (remove-text-properties p
(point-max)
2038 '(invisible t org-cwidth t display t
2041 (setq-local org-finish-function
'org-table-finish-edit-field
)
2042 (setq-local org-window-configuration cw
)
2043 (setq-local org-field-marker pos
)
2044 (message "Edit and finish with C-c C-c")))))
2046 (defun org-table-finish-edit-field ()
2047 "Finish editing a table data field.
2048 Remove all newline characters, insert the result into the table, realign
2049 the table and kill the editing buffer."
2050 (let ((pos org-field-marker
)
2051 (cw org-window-configuration
)
2052 (cb (current-buffer))
2054 (goto-char (point-min))
2055 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2056 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2057 (replace-match " "))
2058 (setq text
(org-trim (buffer-string)))
2059 (set-window-configuration cw
)
2061 (select-window (get-buffer-window (marker-buffer pos
)))
2063 (move-marker pos nil
)
2064 (org-table-check-inside-data-field)
2065 (org-table-get-field nil text
)
2067 (message "New field value inserted")))
2069 (define-minor-mode org-table-follow-field-mode
2070 "Minor mode to make the table field editor window follow the cursor.
2071 When this mode is active, the field editor window will always show the
2072 current field. The mode exits automatically when the cursor leaves the
2073 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2074 nil
" TblFollow" nil
2075 (if org-table-follow-field-mode
2076 (add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2078 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2079 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2080 (win (and buf
(get-buffer-window buf
))))
2081 (when win
(delete-window win
))
2083 (with-current-buffer buf
2084 (move-marker org-field-marker nil
))
2085 (kill-buffer buf
)))))
2087 (defun org-table-follow-fields-with-editor ()
2088 (if (and org-table-exit-follow-field-mode-when-leaving-table
2089 (not (org-at-table-p)))
2090 ;; We have left the table, exit the follow mode
2091 (org-table-follow-field-mode -
1)
2092 (when (org-table-check-inside-data-field 'noerror
)
2093 (let ((win (selected-window)))
2094 (org-table-edit-field nil
)
2095 (org-fit-window-to-buffer)
2096 (select-window win
)))))
2098 (defvar org-timecnt
) ; dynamically scoped parameter
2101 (defun org-table-sum (&optional beg end nlast
)
2102 "Sum numbers in region of current table column.
2103 The result will be displayed in the echo area, and will be available
2104 as kill to be inserted with \\[yank].
2106 If there is an active region, it is interpreted as a rectangle and all
2107 numbers in that rectangle will be summed. If there is no active
2108 region and point is located in a table column, sum all numbers in that
2111 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2112 numbers are assumed to be times as well (in decimal hours) and the
2113 numbers are added as such.
2115 If NLAST is a number, only the NLAST fields will actually be summed."
2118 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2120 ((and beg end
)) ; beg and end given explicitly
2121 ((org-region-active-p)
2122 (setq beg
(region-beginning) end
(region-end)))
2124 (setq col
(org-table-current-column))
2125 (goto-char (org-table-begin))
2126 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2127 (user-error "No table data"))
2128 (org-table-goto-column col
)
2130 (goto-char (org-table-end))
2131 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2132 (user-error "No table data"))
2133 (org-table-goto-column col
)
2134 (setq end
(point))))
2135 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2136 (items1 (cond ((not nlast
) items
)
2137 ((>= nlast
(length items
)) items
)
2138 (t (setq items
(reverse items
))
2139 (setcdr (nthcdr (1- nlast
) items
) nil
)
2141 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2143 (res (apply '+ numbers
))
2144 (sres (if (= org-timecnt
0)
2145 (number-to-string res
)
2146 (setq diff
(* 3600 res
)
2147 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2148 m
(floor (/ diff
60)) diff
(mod diff
60)
2150 (format "%.0f:%02.0f:%02.0f" h m s
))))
2152 (when (called-interactively-p 'interactive
)
2153 (message "%s" (substitute-command-keys
2154 (format "Sum of %d items: %-20s \
2155 \(\\[yank] will insert result into buffer)" (length numbers
) sres
))))
2158 (defun org-table-get-number-for-summing (s)
2160 (if (string-match "^ *|? *" s
)
2161 (setq s
(replace-match "" nil nil s
)))
2162 (if (string-match " *|? *$" s
)
2163 (setq s
(replace-match "" nil nil s
)))
2164 (setq n
(string-to-number s
))
2166 ((and (string-match "0" s
)
2167 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2168 ((string-match "\\`[ \t]+\\'" s
) nil
)
2169 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2170 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2171 (m (string-to-number (or (match-string 2 s
) "0")))
2172 (s (string-to-number (or (match-string 4 s
) "0"))))
2173 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2174 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2178 (defun org-table-current-field-formula (&optional key noerror
)
2179 "Return the formula active for the current field.
2181 Assumes that table is already analyzed. If KEY is given, return
2182 the key to this formula. Otherwise return the formula preceded
2183 with \"=\" or \":=\"."
2184 (let* ((line (count-lines org-table-current-begin-pos
2185 (line-beginning-position)))
2186 (row (org-table-line-to-dline line
)))
2189 (let* ((col (org-table-current-column))
2190 (name (car (rassoc (list line col
)
2191 org-table-named-field-locations
)))
2192 (scol (format "$%d" col
))
2193 (ref (format "@%d$%d" (org-table-current-dline) col
))
2194 (stored-list (org-table-get-stored-formulas noerror
))
2195 (ass (or (assoc name stored-list
)
2196 (assoc ref stored-list
)
2197 (assoc scol stored-list
))))
2198 (cond (key (car ass
))
2199 (ass (concat (if (string-match-p "^[0-9]+$" (car ass
)) "=" ":=")
2202 (t (error "No formula active for the current field")))))
2204 (defun org-table-get-formula (&optional equation named
)
2205 "Read a formula from the minibuffer, offer stored formula as default.
2206 When NAMED is non-nil, look for a named equation."
2207 (let* ((stored-list (org-table-get-stored-formulas))
2208 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2209 (line-beginning-position))
2210 (org-table-current-column))
2211 org-table-named-field-locations
)))
2212 (ref (format "@%d$%d"
2213 (org-table-current-dline)
2214 (org-table-current-column)))
2216 ((not named
) (format "$%d" (org-table-current-column)))
2217 ((and name
(not (string-match "\\`LR[0-9]+\\'" name
))) name
)
2219 (name (or name ref
))
2220 (org-table-may-need-update nil
)
2221 (stored (cdr (assoc scol stored-list
)))
2223 ((and stored equation
(string-match-p "^ *=? *$" equation
))
2227 (t (org-table-formula-from-user
2229 (org-table-formula-to-user
2230 (format "%s formula %s="
2231 (if named
"Field" "Column")
2233 (if stored
(org-table-formula-to-user stored
) "")
2234 'org-table-formula-history
2237 (when (not (string-match "\\S-" eq
))
2239 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2240 (org-table-store-formulas stored-list
)
2241 (user-error "Formula removed"))
2242 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2243 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2244 (if (and name
(not named
))
2245 ;; We set the column equation, delete the named one.
2246 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2249 (setcdr (assoc scol stored-list
) eq
)
2250 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2251 (if (or mustsave
(not (equal stored eq
)))
2252 (org-table-store-formulas stored-list
))
2255 (defun org-table-store-formulas (alist &optional location
)
2256 "Store the list of formulas below the current table.
2257 If optional argument LOCATION is a buffer position, insert it at
2261 (progn (goto-char location
) (beginning-of-line))
2262 (goto-char (org-table-end)))
2263 (let ((case-fold-search t
))
2264 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2266 ;; Don't overwrite TBLFM, we might use text properties to
2268 (goto-char (match-beginning 3))
2269 (delete-region (match-beginning 3) (match-end 0)))
2271 (insert (or (match-string 2) "#+TBLFM:")))
2273 (mapconcat (lambda (x) (concat (car x
) "=" (cdr x
)))
2274 (sort alist
#'org-table-formula-less-p
)
2278 (defsubst org-table-formula-make-cmp-string
(a)
2279 (when (string-match "\\`$[<>]" a
)
2280 (let ((arrow (string-to-char (substring a
1))))
2281 ;; Fake a high number to make sure this is sorted at the end.
2282 (setq a
(org-table-formula-handle-first/last-rc a
))
2283 (setq a
(format "$%d" (+ 10000
2284 (if (= arrow ?
<) -
1000 0)
2285 (string-to-number (substring a
1)))))))
2287 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2291 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2293 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2295 (concat "@@" (match-string 5 a
))))))
2297 (defun org-table-formula-less-p (a b
)
2298 "Compare two formulas for sorting."
2299 (let ((as (org-table-formula-make-cmp-string (car a
)))
2300 (bs (org-table-formula-make-cmp-string (car b
))))
2301 (and as bs
(string< as bs
))))
2304 (defun org-table-get-stored-formulas (&optional noerror location
)
2305 "Return an alist with the stored formulas directly after current table.
2306 By default, only return active formulas, i.e., formulas located
2307 on the first line after the table. However, if optional argument
2308 LOCATION is a buffer position, consider the formulas there."
2311 (progn (goto-char location
) (beginning-of-line))
2312 (goto-char (org-table-end)))
2313 (let ((case-fold-search t
))
2314 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2315 (let ((strings (org-split-string (match-string-no-properties 2)
2318 (dolist (string strings
(nreverse eq-alist
))
2319 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2320 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2323 (let ((m (match-string 1 string
)))
2325 ((not (match-end 2)) m
)
2326 ;; Is it a column reference?
2327 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m
) m
)
2328 ;; Since named columns are not possible in
2329 ;; LHS, assume this is a named field.
2330 (t (match-string 2 string
)))))
2331 (rhs (match-string 3 string
)))
2332 (push (cons lhs rhs
) eq-alist
)
2334 ((not (member lhs seen
)) (push lhs seen
))
2337 "Double definition `%s=' in TBLFM line, please fix by hand"
2343 "Double definition `%s=' in TBLFM line, please fix by hand"
2346 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2347 "Modify the equations after the table structure has been edited.
2348 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2349 For all numbers larger than LIMIT, shift them by DELTA."
2351 (goto-char (org-table-end))
2352 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2353 (let ((msg "The formulas in #+TBLFM have been updated")
2354 (re (concat key
"\\([0-9]+\\)"))
2357 (if (or (equal key
"$") (equal key
"$LR"))
2358 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2359 (regexp-quote key
) remove
)
2360 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2363 (while (re-search-forward re2
(point-at-eol) t
)
2364 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2365 (if (equal (char-before (match-beginning 0)) ?.
)
2367 "Change makes TBLFM term %s invalid, use undo to recover"
2369 (replace-match "")))))
2370 (while (re-search-forward re
(point-at-eol) t
)
2371 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2372 (setq s
(match-string 1) n
(string-to-number s
))
2374 ((setq a
(assoc s replace
))
2375 (replace-match (concat key
(cdr a
)) t t
)
2377 ((and limit
(> n limit
))
2378 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2383 (defun org-table-maybe-eval-formula ()
2384 "Check if the current field starts with \"=\" or \":=\".
2385 If yes, store the formula and apply it."
2386 ;; We already know we are in a table. Get field will only return a formula
2387 ;; when appropriate. It might return a separator line, but no problem.
2388 (when org-table-formula-evaluate-inline
2389 (let* ((field (org-trim (or (org-table-get-field) "")))
2391 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2392 (setq named
(equal (string-to-char field
) ?
:)
2393 eq
(match-string 1 field
))
2394 (org-table-eval-formula (and named
'(4))
2395 (org-table-formula-from-user eq
))))))
2397 (defvar org-recalc-commands nil
2398 "List of commands triggering the recalculation of a line.
2399 Will be filled automatically during use.")
2401 (defvar org-recalc-marks
2402 '((" " .
"Unmarked: no special line, no automatic recalculation")
2403 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2404 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2405 ("!" .
"Column name definition line. Reference in formula as $name.")
2406 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2407 ("_" .
"Names for values in row below this one.")
2408 ("^" .
"Names for values in row above this one.")))
2411 (defun org-table-rotate-recalc-marks (&optional newchar
)
2412 "Rotate the recalculation mark in the first column.
2413 If in any row, the first field is not consistent with a mark,
2414 insert a new column for the markers.
2415 When there is an active region, change all the lines in the region,
2416 after prompting for the marking character.
2417 After each change, a message will be displayed indicating the meaning
2420 (unless (org-at-table-p) (user-error "Not at a table"))
2421 (let* ((region (org-region-active-p))
2423 (save-excursion (goto-char (region-beginning))
2424 (copy-marker (line-beginning-position)))))
2426 (save-excursion (goto-char (region-end))
2427 (copy-marker (line-beginning-position)))))
2428 (l (copy-marker (line-beginning-position)))
2429 (col (org-table-current-column))
2432 (read-char-exclusive
2433 "Change region to what mark? Type # * ! $ or SPC: "))
2437 (goto-char (org-table-begin))
2439 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2440 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2441 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2443 (when l1
(goto-char l1
))
2446 (unless (looking-at org-table-dataline-regexp
)
2447 (user-error "Not at a table data line")))
2448 (when no-special-column
2449 (org-table-goto-column 1)
2450 (org-table-insert-column))
2451 (let ((previous-line-end (line-end-position))
2455 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2457 (t (cadr (member (match-string 1)
2458 (append (mapcar #'car org-recalc-marks
)
2460 ;; Rotate mark in first row.
2461 (org-table-get-field 1 (format " %s " newchar
))
2462 ;; Rotate marks in additional rows if a region is active.
2466 (while (<= (point) l2
)
2467 (when (looking-at org-table-dataline-regexp
)
2468 (org-table-get-field 1 (format " %s " newchar
)))
2470 ;; Only align if rotation actually changed lines' length.
2471 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2473 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2474 (when l1
(set-marker l1 nil
))
2475 (when l2
(set-marker l2 nil
))
2477 (when (called-interactively-p 'interactive
)
2478 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2481 (defun org-table-analyze ()
2482 "Analyze table at point and store results.
2484 This function sets up the following dynamically scoped variables:
2486 `org-table-column-name-regexp',
2487 `org-table-column-names',
2488 `org-table-current-begin-pos',
2489 `org-table-current-line-types',
2490 `org-table-current-ncol',
2493 `org-table-local-parameters',
2494 `org-table-named-field-locations'."
2495 (let ((beg (org-table-begin))
2496 (end (org-table-end)))
2499 ;; Extract column names.
2500 (setq org-table-column-names nil
)
2501 (when (save-excursion
2502 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
2504 (dolist (name (org-split-string (match-string 1) " *| *"))
2506 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
2507 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
2508 (setq org-table-column-names
(nreverse org-table-column-names
))
2509 (setq org-table-column-name-regexp
2510 (format "\\$\\(%s\\)\\>"
2511 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
2512 ;; Extract local parameters.
2513 (setq org-table-local-parameters nil
)
2515 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2516 (dolist (field (org-split-string (match-string 1) " *| *"))
2518 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2519 (push (cons (match-string 1 field
) (match-string 2 field
))
2520 org-table-local-parameters
)))))
2521 ;; Update named fields locations. We minimize `count-lines'
2522 ;; processing by storing last known number of lines in LAST.
2523 (setq org-table-named-field-locations nil
)
2525 (let ((last (cons (point) 0)))
2526 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2527 (let ((c (match-string 1))
2528 (fields (org-split-string (match-string 2) " *| *")))
2530 (forward-line (if (equal c
"_") 1 -
1))
2532 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2533 (org-split-string (match-string 1) " *| *")))
2534 (line (cl-incf (cdr last
) (count-lines (car last
) (point))))
2536 (setcar last
(point)) ; Update last known position.
2537 (while (and fields fields1
)
2538 (let ((field (pop fields
))
2541 (when (and (stringp field
)
2543 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2545 (push (cons field v
) org-table-local-parameters
)
2546 (push (list field line col
)
2547 org-table-named-field-locations
))))))))))
2548 ;; Re-use existing markers when possible.
2549 (if (markerp org-table-current-begin-pos
)
2550 (move-marker org-table-current-begin-pos
(point))
2551 (setq org-table-current-begin-pos
(point-marker)))
2552 ;; Analyze the line types.
2553 (let ((l 0) hlines dlines types
)
2554 (while (looking-at "[ \t]*|\\(-\\)?")
2555 (push (if (match-end 1) 'hline
'dline
) types
)
2556 (if (match-end 1) (push l hlines
) (push l dlines
))
2559 (push 'hline types
) ; Add an imaginary extra hline to the end.
2560 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
2561 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
2562 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
)))))
2563 ;; Get the number of columns from the first data line in table.
2565 (forward-line (aref org-table-dlines
1))
2568 (buffer-substring (line-beginning-position) (line-end-position))
2570 (nfields (length fields
))
2572 (setq org-table-current-ncol nfields
)
2574 (aref org-table-dlines
(1- (length org-table-dlines
)))))
2575 (dotimes (i nfields
)
2576 (let ((column (1+ i
)))
2577 (push (list (format "LR%d" column
) last-dline column
) al
)
2578 (push (cons (format "LR%d" column
) (nth i fields
)) al2
))))
2579 (setq org-table-named-field-locations
2580 (append org-table-named-field-locations al
))
2581 (setq org-table-local-parameters
2582 (append org-table-local-parameters al2
))))))
2584 (defun org-table-goto-field (ref &optional create-column-p
)
2585 "Move point to a specific field in the current table.
2587 REF is either the name of a field its absolute reference, as
2588 a string. No column is created unless CREATE-COLUMN-P is
2589 non-nil. If it is a function, it is called with the column
2590 number as its argument as is used as a predicate to know if the
2591 column can be created.
2593 This function assumes the table is already analyzed (i.e., using
2594 `org-table-analyze')."
2597 ((cdr (assoc ref org-table-named-field-locations
)))
2598 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
2599 (list (condition-case nil
2600 (aref org-table-dlines
2601 (string-to-number (match-string 1 ref
)))
2602 (error (user-error "Invalid row number in %s" ref
)))
2603 (string-to-number (match-string 2 ref
))))
2604 (t (user-error "Unknown field: %s" ref
))))
2605 (line (car coordinates
))
2606 (column (nth 1 coordinates
))
2607 (create-new-column (if (functionp create-column-p
)
2608 (funcall create-column-p column
)
2611 (goto-char org-table-current-begin-pos
)
2613 (org-table-goto-column column nil create-new-column
))))
2616 (defun org-table-maybe-recalculate-line ()
2617 "Recompute the current line if marked for it, and if we haven't just done it."
2619 (and org-table-allow-automatic-line-recalculation
2620 (not (and (memq last-command org-recalc-commands
)
2621 (eq org-last-recalc-line
(line-beginning-position))))
2622 (save-excursion (beginning-of-line 1)
2623 (looking-at org-table-auto-recalculate-regexp
))
2624 (org-table-recalculate) t
))
2626 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2627 (defsubst org-set-calc-mode
(var &optional value
)
2629 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2630 ("R" calc-angle-mode rad
)
2631 ("F" calc-prefer-frac t
)
2632 ("S" calc-symbolic-mode t
)))
2633 value
(nth 2 var
) var
(nth 1 var
)))
2634 (if (memq var org-tbl-calc-modes
)
2635 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2636 (cons var
(cons value org-tbl-calc-modes
)))
2640 (defun org-table-eval-formula (&optional arg equation
2641 suppress-align suppress-const
2642 suppress-store suppress-analysis
)
2643 "Replace the table field value at the cursor by the result of a calculation.
2645 In a table, this command replaces the value in the current field with the
2646 result of a formula. It also installs the formula as the \"current\" column
2647 formula, by storing it in a special line below the table. When called
2648 with a `\\[universal-argument]' prefix the formula is installed as a \
2651 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2652 insert the active equation for the field
2653 back into the current field, so that it can be edited there. This is \
2655 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2656 check the referenced fields.
2658 When called, the command first prompts for a formula, which is read in
2659 the minibuffer. Previously entered formulas are available through the
2660 history list, and the last used formula is offered as a default.
2661 These stored formulas are adapted correctly when moving, inserting, or
2662 deleting columns with the corresponding commands.
2664 The formula can be any algebraic expression understood by the Calc package.
2665 For details, see the Org mode manual.
2667 This function can also be called from Lisp programs and offers
2668 additional arguments: EQUATION can be the formula to apply. If this
2669 argument is given, the user will not be prompted.
2671 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2674 SUPPRESS-CONST suppresses the interpretation of constants in the
2675 formula, assuming that this has been done already outside the
2678 SUPPRESS-STORE means the formula should not be stored, either
2679 because it is already stored, or because it is a modified
2680 equation that should not overwrite the stored one.
2682 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2685 (unless suppress-analysis
2686 (org-table-check-inside-data-field)
2687 (org-table-analyze))
2688 (if (equal arg
'(16))
2689 (let ((eq (org-table-current-field-formula)))
2690 (org-table-get-field nil eq
)
2692 (setq org-table-may-need-update t
))
2694 (ndown (if (integerp arg
) arg
1))
2695 (org-table-automatic-realign nil
)
2696 (case-fold-search nil
)
2698 (formula (if (and equation suppress-store
)
2700 (org-table-get-formula equation
(equal arg
'(4)))))
2701 (n0 (org-table-current-column))
2702 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2703 (numbers nil
) ; was a variable, now fixed default
2705 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2706 duration duration-output-format
)
2707 ;; Parse the format string. Since we have a lot of modes, this is
2708 ;; a lot of work. However, I think calc still uses most of the time.
2709 (if (string-match ";" formula
)
2710 (let ((tmp (org-split-string formula
";")))
2711 (setq formula
(car tmp
)
2712 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2714 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2715 (setq c
(string-to-char (match-string 1 fmt
))
2716 n
(string-to-number (match-string 2 fmt
)))
2718 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2719 (setq org-tbl-calc-modes
2722 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2723 (?s . sci
) (?e . eng
))))
2725 (setq fmt
(replace-match "" t t fmt
)))
2726 (if (string-match "T" fmt
)
2727 (setq duration t numbers t
2728 duration-output-format nil
2729 fmt
(replace-match "" t t fmt
)))
2730 (if (string-match "t" fmt
)
2732 duration-output-format org-table-duration-custom-format
2734 fmt
(replace-match "" t t fmt
)))
2735 (if (string-match "N" fmt
)
2737 fmt
(replace-match "" t t fmt
)))
2738 (if (string-match "L" fmt
)
2740 fmt
(replace-match "" t t fmt
)))
2741 (if (string-match "E" fmt
)
2743 fmt
(replace-match "" t t fmt
)))
2744 (while (string-match "[DRFS]" fmt
)
2745 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2746 (setq fmt
(replace-match "" t t fmt
)))
2747 (unless (string-match "\\S-" fmt
)
2749 (when (and (not suppress-const
) org-table-formula-use-constants
)
2750 (setq formula
(org-table-formula-substitute-names formula
)))
2751 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2752 (setq formula
(org-table-formula-handle-first/last-rc formula
))
2754 (setq fields
(org-split-string
2756 (buffer-substring-no-properties
2757 (line-beginning-position) (line-end-position)))
2759 ;; replace fields with duration values if relevant
2762 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2765 (setq fields
(mapcar
2767 (if (string-match "\\S-" x
)
2768 (number-to-string (string-to-number x
))
2771 (setq ndown
(1- ndown
))
2772 (setq form
(copy-sequence formula
)
2773 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2774 (if (and lispp literal
) (setq lispp
'literal
))
2776 ;; Insert row and column number of formula result field
2777 (while (string-match "[@$]#" form
)
2782 (if (equal (substring form
(match-beginning 0)
2783 (1+ (match-beginning 0)))
2785 (org-table-current-dline)
2786 (org-table-current-column))))
2789 ;; Check for old vertical references
2790 (org-table--error-on-old-row-references form
)
2791 ;; Insert remote references
2792 (setq form
(org-table-remote-reference-indirection form
))
2793 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2797 (org-table-make-reference
2798 (let ((rmtrng (org-table-get-remote-range
2799 (match-string 1 form
) (match-string 2 form
))))
2802 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2803 (org-table-time-string-to-seconds rmtrng
))
2805 keep-empty numbers lispp
))
2807 ;; Insert complex ranges
2808 (while (and (string-match org-table-range-regexp form
)
2809 (> (length (match-string 0 form
)) 1))
2812 (org-table-get-range
2813 (match-string 0 form
) org-table-current-begin-pos n0
)))
2816 (org-table-make-reference
2817 ;; possibly handle durations
2820 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2821 (org-table-time-string-to-seconds formrg
))
2823 keep-empty numbers lispp
)))
2824 (if (not (save-match-data
2825 (string-match (regexp-quote form
) formrpl
)))
2826 (setq form
(replace-match formrpl t t form
))
2827 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2828 ;; Insert simple ranges, i.e. included in the current row.
2829 (while (string-match
2830 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2835 (org-table-make-reference
2837 (+ (if (match-end 2) n0
0)
2838 (string-to-number (match-string 1 form
))
2840 (+ (if (match-end 4) n0
0)
2841 (string-to-number (match-string 3 form
))))
2842 keep-empty numbers lispp
))
2845 ;; Insert the references to fields in same row
2846 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2847 (setq n
(+ (string-to-number (match-string 1 form
))
2848 (if (match-end 2) n0
0))
2849 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2850 formrpl
(save-match-data
2851 (org-table-make-reference
2852 x keep-empty numbers lispp
)))
2855 (string-match (regexp-quote formula
) formrpl
)))
2856 (user-error "Invalid field specifier \"%s\""
2857 (match-string 0 form
)))
2858 (setq form
(replace-match formrpl t t form
)))
2861 (setq ev
(condition-case nil
2862 (eval (eval (read form
)))
2864 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2865 ev
(if duration
(org-table-time-seconds-to-string
2866 (string-to-number ev
)
2867 duration-output-format
) ev
))
2869 ;; Use <...> time-stamps so that Calc can handle them.
2871 (replace-regexp-in-string org-ts-regexp-inactive
"<\\1>" form
))
2872 ;; Internationalize local time-stamps by setting locale to
2875 (replace-regexp-in-string
2878 (let ((system-time-locale "C"))
2880 (org-time-stamp-format
2881 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2882 (apply #'encode-time
2883 (save-match-data (org-parse-time-string ts
))))))
2886 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2888 (calc-eval (cons form org-tbl-calc-modes
)
2889 (when (and (not keep-empty
) numbers
) 'num
)))
2890 ev
(if duration
(org-table-time-seconds-to-string
2891 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2892 (string-to-number (org-table-time-string-to-seconds ev
))
2893 (string-to-number ev
))
2894 duration-output-format
)
2897 (when org-table-formula-debug
2898 (with-output-to-temp-buffer "*Substitution History*"
2899 (princ (format "Substitution history of formula
2903 $1-> %s\n" orig formula form0 form
))
2905 (princ (format " %s^\nError: %s"
2906 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2907 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2909 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2910 (setq bw
(get-buffer-window "*Substitution History*"))
2911 (org-fit-window-to-buffer bw
)
2912 (unless (and (called-interactively-p 'any
) (not ndown
))
2913 (unless (let (inhibit-redisplay)
2914 (y-or-n-p "Debugging Formula. Continue to next? "))
2916 (user-error "Abort"))
2919 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2920 (org-table-justify-field-maybe
2921 (format org-table-formula-field-format
2923 ((not (stringp ev
)) ev
)
2924 (fmt (format fmt
(string-to-number ev
)))
2925 ;; Replace any active time stamp in the result with
2926 ;; an inactive one. Dates in tables are likely
2927 ;; piece of regular data, not meant to appear in the
2929 (t (replace-regexp-in-string org-ts-regexp
"[\\1]" ev
)))))
2930 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2931 (call-interactively 'org-return
)
2933 (and down
(org-table-maybe-recalculate-line))
2934 (or suppress-align
(and org-table-may-need-update
2935 (org-table-align))))))
2937 (defun org-table-put-field-property (prop value
)
2939 (put-text-property (progn (skip-chars-backward "^|") (point))
2940 (progn (skip-chars-forward "^|") (point))
2943 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2944 "Get a calc vector from a column, according to descriptor DESC.
2946 Optional arguments TBEG and COL can give the beginning of the table and
2947 the current column, to avoid unnecessary parsing.
2949 HIGHLIGHT means just highlight the range.
2951 When CORNERS-ONLY is set, only return the corners of the range as
2952 a list (line1 column1 line2 column2) where line1 and line2 are
2953 line numbers relative to beginning of table, or TBEG, and column1
2954 and column2 are table column numbers."
2955 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc
)
2956 (replace-regexp-in-string "\\$" "@0$" desc
)
2958 (col (or col
(org-table-current-column)))
2959 (tbeg (or tbeg
(org-table-begin)))
2960 (thisline (count-lines tbeg
(line-beginning-position))))
2961 (unless (string-match org-table-range-regexp desc
)
2962 (user-error "Invalid table range specifier `%s'" desc
))
2963 (let ((rangep (match-end 3))
2964 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2965 (or (save-match-data
2966 (and (org-string-nw-p r
)
2967 (org-table--descriptor-line r thisline
)))
2969 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
2970 (or (save-match-data
2971 (and (org-string-nw-p r
)
2972 (org-table--descriptor-line r thisline
)))
2974 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
2975 (if (or (not c
) (= (string-to-number c
) 0)) col
2976 (+ (string-to-number c
)
2977 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
2978 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
2979 (if (or (not c
) (= (string-to-number c
) 0)) col
2980 (+ (string-to-number c
)
2981 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
2983 (if (and (not corners-only
)
2984 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2987 (forward-line (- r1 thisline
))
2988 (while (not (looking-at org-table-dataline-regexp
))
2990 (prog1 (org-trim (org-table-get-field c1
))
2991 (when highlight
(org-table-highlight-rectangle))))
2992 ;; A range, return a vector. First sort the numbers to get
2993 ;; a regular rectangle.
2994 (let ((first-row (min r1 r2
))
2995 (last-row (max r1 r2
))
2996 (first-column (min c1 c2
))
2997 (last-column (max c1 c2
)))
2998 (if corners-only
(list first-row first-column last-row last-column
)
2999 ;; Copy the range values into a list.
3000 (forward-line (- first-row thisline
))
3001 (while (not (looking-at org-table-dataline-regexp
))
3003 (cl-incf first-row
))
3004 (org-table-goto-column first-column
)
3005 (let ((beg (point)))
3006 (forward-line (- last-row first-row
))
3007 (while (not (looking-at org-table-dataline-regexp
))
3009 (org-table-goto-column last-column
)
3010 (let ((end (point)))
3012 (org-table-highlight-rectangle
3013 beg
(progn (skip-chars-forward "^|\n") (point))))
3014 ;; Return string representation of calc vector.
3017 (org-table-copy-region beg end
))))))))))))
3019 (defun org-table--descriptor-line (desc cline
)
3020 "Return relative line number corresponding to descriptor DESC.
3021 The cursor is currently in relative line number CLINE."
3022 (if (string-match "\\`[0-9]+\\'" desc
)
3023 (aref org-table-dlines
(string-to-number desc
))
3024 (when (or (not (string-match
3025 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3028 (and (not (match-end 3)) (not (match-end 6)))
3029 (and (match-end 3) (match-end 6) (not (match-end 5))))
3030 (user-error "Invalid row descriptor `%s'" desc
))
3031 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3032 (hdir (match-string 2 desc
))
3033 (odir (match-string 5 desc
))
3034 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
3035 (rel (and (match-end 6)
3036 (or (and (match-end 1) (not (match-end 3)))
3038 (when (and hn
(not hdir
))
3041 (when (eq (aref org-table-current-line-types
0) 'hline
) (cl-decf hn
)))
3042 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
3045 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
3048 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
3051 (defun org-table--row-type (type n i backwards relative desc
)
3052 "Return relative line of Nth row with type TYPE.
3053 Search starts from relative line I. When BACKWARDS in non-nil,
3054 look before I. When RELATIVE is non-nil, the reference is
3055 relative. DESC is the original descriptor that started the
3056 search, as a string."
3057 (let ((l (length org-table-current-line-types
)))
3060 (while (and (cl-incf i
(if backwards -
1 1))
3063 (not (eq (aref org-table-current-line-types i
) type
))
3064 ;; We are going to cross a hline. Check if this is
3065 ;; an authorized move.
3068 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
3069 ((eq org-table-relative-ref-may-cross-hline t
))
3070 ((eq org-table-relative-ref-may-cross-hline
'error
)
3071 (user-error "Row descriptor %s crosses hline" desc
))
3072 (t (cl-decf i
(if backwards -
1 1)) ; Step back.
3073 (throw :exit nil
)))))))
3074 (cond ((or (< i
0) (>= i l
))
3075 (user-error "Row descriptor %s leads outside table" desc
))
3076 ;; The last hline doesn't exist. Instead, point to last row
3078 ((= i
(1- l
)) (1- i
))
3081 (defun org-table--error-on-old-row-references (s)
3082 (when (string-match "&[-+0-9I]" s
)
3083 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3085 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3086 "Convert list ELEMENTS to something appropriate to insert into formula.
3087 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3088 NUMBERS indicates that everything should be converted to numbers.
3089 LISPP non-nil means to return something appropriate for a Lisp
3090 list, `literal' is for the format specifier L."
3091 ;; Calc nan (not a number) is used for the conversion of the empty
3092 ;; field to a reference for several reasons: (i) It is accepted in a
3093 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3094 ;; (ii) In a single field (not in range) it can be distinguished
3095 ;; from "(nan)" which is the reference made from a single field
3096 ;; containing "nan".
3097 (if (stringp elements
)
3100 (if (eq lispp
'literal
)
3102 (if (and (eq elements
"") (not keep-empty
))
3105 (if numbers
(string-to-number elements
) elements
))))
3106 (if (string-match "\\S-" elements
)
3108 (when numbers
(setq elements
(number-to-string
3109 (string-to-number elements
))))
3110 (concat "(" elements
")"))
3111 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3116 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3118 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3122 (if (eq lispp
'literal
)
3124 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3126 (concat "[" (mapconcat
3128 (if (string-match "\\S-" x
)
3130 (number-to-string (string-to-number x
))
3132 (if (or (not keep-empty
) numbers
) "0" "nan")))
3136 (defun org-table-message-once-per-second (t1 &rest args
)
3137 "If there has been more than one second since T1, display message.
3138 ARGS are passed as arguments to the `message' function. Returns
3139 current time if a message is printed, otherwise returns T1. If
3140 T1 is nil, always messages."
3141 (let ((curtime (current-time)))
3142 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3143 (progn (apply 'message args
)
3148 (defun org-table-recalculate (&optional all noalign
)
3149 "Recalculate the current table line by applying all stored formulas.
3151 With prefix arg ALL, do this for all lines in the table.
3153 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3154 if ALL is the symbol `iterate',
3155 recompute the table until it no longer changes.
3157 If NOALIGN is not nil, do not re-align the table after the computations
3158 are done. This is typically used internally to save time, if it is
3159 known that the table will be realigned a little later anyway."
3161 (unless (memq this-command org-recalc-commands
)
3162 (push this-command org-recalc-commands
))
3163 (unless (org-at-table-p) (user-error "Not at a table"))
3164 (if (or (eq all
'iterate
) (equal all
'(16)))
3167 (let* ((eqlist (sort (org-table-get-stored-formulas)
3168 (lambda (a b
) (string< (car a
) (car b
)))))
3169 (inhibit-redisplay (not debug-on-error
))
3170 (line-re org-table-dataline-regexp
)
3171 (log-first-time (current-time))
3172 (log-last-time log-first-time
)
3174 beg end eqlcol eqlfield
)
3175 ;; Insert constants in all formulas.
3177 (org-table-save-field
3178 ;; Expand equations, then split the equation list between
3179 ;; column formulas and field formulas.
3181 (let* ((rhs (org-table-formula-substitute-names
3182 (org-table-formula-handle-first/last-rc
(cdr eq
))))
3185 (org-table-formula-handle-first/last-rc
3187 ((string-match "\\`@-?I+" old-lhs
)
3188 (user-error "Can't assign to hline relative reference"))
3189 ((string-match "\\`$[<>]" old-lhs
)
3190 (let ((new (org-table-formula-handle-first/last-rc
3192 (when (assoc new eqlist
)
3193 (user-error "\"%s=\" formula tries to overwrite \
3194 existing formula for column %s"
3199 (if (string-match-p "\\`\\$[0-9]+\\'" lhs
)
3200 (push (cons lhs rhs
) eqlcol
)
3201 (push (cons lhs rhs
) eqlfield
))))
3202 (setq eqlcol
(nreverse eqlcol
))
3203 ;; Expand ranges in lhs of formulas
3204 (setq eqlfield
(org-table-expand-lhs-ranges (nreverse eqlfield
)))
3205 ;; Get the correct line range to process.
3208 (setq end
(copy-marker (org-table-end)))
3209 (goto-char (setq beg org-table-current-begin-pos
))
3211 ((re-search-forward org-table-calculate-mark-regexp end t
)
3212 ;; This is a table with marked lines, compute selected
3214 (setq line-re org-table-recalculate-regexp
))
3215 ;; Move forward to the first non-header line.
3216 ((and (re-search-forward org-table-dataline-regexp end t
)
3217 (re-search-forward org-table-hline-regexp end t
)
3218 (re-search-forward org-table-dataline-regexp end t
))
3219 (setq beg
(match-beginning 0)))
3220 ;; Just leave BEG at the start of the table.
3222 (setq beg
(line-beginning-position)
3223 end
(copy-marker (line-beginning-position 2))))
3225 ;; Mark named fields untouchable. Also check if several
3226 ;; field/range formulas try to set the same field.
3227 (remove-text-properties beg end
'(org-untouchable t
))
3228 (let ((current-line (count-lines org-table-current-begin-pos
3229 (line-beginning-position)))
3231 (dolist (eq eqlfield
)
3232 (let* ((name (car eq
))
3233 (location (assoc name org-table-named-field-locations
))
3234 (eq-line (or (nth 1 location
)
3235 (and (string-match "\\`@\\([0-9]+\\)" name
)
3236 (aref org-table-dlines
3238 (match-string 1 name
))))))
3241 ;; Turn field coordinates associated to NAME
3242 ;; into an absolute reference.
3244 (org-table-line-to-dline eq-line
)
3247 (when (member reference seen-fields
)
3248 (user-error "Several field/range formulas try to set %s"
3250 (push reference seen-fields
)
3251 (when (or all
(eq eq-line current-line
))
3252 (org-table-goto-field name
)
3253 (org-table-put-field-property :org-untouchable t
)))))
3254 ;; Evaluate the column formulas, but skip fields covered by
3257 (while (re-search-forward line-re end t
)
3258 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3259 ;; Unprotected line, recalculate.
3263 (org-table-message-once-per-second
3265 "Re-applying formulas to full table...(line %d)" cnt
)))
3266 (if (markerp org-last-recalc-line
)
3267 (move-marker org-last-recalc-line
(line-beginning-position))
3268 (setq org-last-recalc-line
3269 (copy-marker (line-beginning-position))))
3270 (dolist (entry eqlcol
)
3271 (goto-char org-last-recalc-line
)
3272 (org-table-goto-column
3273 (string-to-number (substring (car entry
) 1)) nil
'force
)
3274 (unless (get-text-property (point) :org-untouchable
)
3275 (org-table-eval-formula
3276 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
3277 ;; Evaluate the field formulas.
3278 (dolist (eq eqlfield
)
3279 (let ((reference (car eq
))
3282 (org-table-message-once-per-second
3283 (and all log-last-time
)
3284 "Re-applying formula to field: %s" (car eq
)))
3285 (org-table-goto-field
3287 ;; Possibly create a new column, as long as
3288 ;; `org-table-formula-create-columns' allows it.
3289 (let ((column-count (progn (end-of-line)
3290 (1- (org-table-current-column)))))
3292 (when (> column
1000)
3293 (user-error "Formula column target too large"))
3294 (and (> column column-count
)
3295 (or (eq org-table-formula-create-columns t
)
3296 (and (eq org-table-formula-create-columns
'warn
)
3298 (org-display-warning
3299 "Out-of-bounds formula added columns")
3301 (and (eq org-table-formula-create-columns
'prompt
)
3303 "Out-of-bounds formula. Add columns? ")))))))
3304 (org-table-eval-formula nil formula t t t t
))))
3305 ;; Clean up markers and internal text property.
3306 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3307 (set-marker end nil
)
3309 (when org-table-may-need-update
(org-table-align))
3311 (org-table-message-once-per-second
3312 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
3313 (org-table-message-once-per-second
3314 (and all log-first-time
) "Re-applying formulas... done")))))
3317 (defun org-table-iterate (&optional arg
)
3318 "Recalculate the table until it does not change anymore.
3319 The maximum number of iterations is 10, but you can choose a different value
3320 with the prefix ARG."
3322 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3324 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3329 (org-table-recalculate 'all
)
3330 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3331 (if (not (string= lasttbl thistbl
))
3332 (setq lasttbl thistbl
)
3334 (message "Convergence after %d iterations" i
)
3335 (message "Table was already stable"))
3337 (user-error "No convergence after %d iterations" i
))))
3340 (defun org-table-recalculate-buffer-tables ()
3341 "Recalculate all tables in the current buffer."
3343 (org-with-wide-buffer
3344 (org-table-map-tables
3346 ;; Reason for separate `org-table-align': When repeating
3347 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3349 (org-table-recalculate t t
)
3354 (defun org-table-iterate-buffer-tables ()
3355 "Iterate all tables in the buffer, to converge inter-table dependencies."
3359 (checksum (md5 (buffer-string)))
3361 (org-with-wide-buffer
3365 (org-table-map-tables (lambda () (org-table-recalculate t t
)) t
)
3366 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3368 (org-table-map-tables #'org-table-align t
)
3369 (message "Convergence after %d iterations" (- imax i
))
3371 (setq checksum c1
)))
3372 (org-table-map-tables #'org-table-align t
)
3373 (user-error "No convergence after %d iterations" imax
)))))
3375 (defun org-table-calc-current-TBLFM (&optional arg
)
3376 "Apply the #+TBLFM in the line at point to the table."
3378 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3379 (let ((formula (buffer-substring
3380 (line-beginning-position)
3381 (line-end-position))))
3383 ;; Insert a temporary formula at right after the table
3384 (goto-char (org-table-TBLFM-begin))
3385 (let ((s (point-marker)))
3386 (insert formula
"\n")
3387 (let ((e (point-marker)))
3388 ;; Recalculate the table.
3389 (beginning-of-line 0) ; move to the inserted line
3390 (skip-chars-backward " \r\n\t")
3392 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3393 ;; Delete the formula inserted temporarily.
3396 (set-marker e nil
)))))))
3398 (defun org-table-TBLFM-begin ()
3399 "Find the beginning of the TBLFM lines and return its position.
3400 Return nil when the beginning of TBLFM line was not found."
3402 (when (progn (forward-line 1)
3403 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3404 (line-beginning-position 2))))
3406 (defun org-table-expand-lhs-ranges (equations)
3407 "Expand list of formulas.
3408 If some of the RHS in the formulas are ranges or a row reference,
3409 expand them to individual field equations for each field. This
3410 function assumes the table is already analyzed (i.e., using
3411 `org-table-analyze')."
3413 (dolist (e equations
(nreverse res
))
3417 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3418 ;; This just refers to one fixed field.
3420 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3421 ;; This just refers to one fixed named field.
3423 ((string-match-p "\\`\\$[0-9]+\\'" lhs
)
3424 ;; Column formulas are treated specially and are not
3427 ((string-match "\\`@[0-9]+\\'" lhs
)
3428 (dotimes (ic org-table-current-ncol
)
3429 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3433 (let* ((range (org-table-get-range
3434 lhs org-table-current-begin-pos
1 nil
'corners
))
3435 (r1 (org-table-line-to-dline (nth 0 range
)))
3437 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3439 (cl-loop for ir from r1 to r2 do
3440 (cl-loop for ic from c1 to c2 do
3441 (push (cons (propertize
3442 (format "@%d$%d" ir ic
) :orig-eqn e
)
3446 (defun org-table-formula-handle-first/last-rc
(s)
3447 "Replace @<, @>, $<, $> with first/last row/column of the table.
3448 So @< and $< will always be replaced with @1 and $1, respectively.
3449 The advantage of these special markers are that structure editing of
3450 the table will not change them, while @1 and $1 will be modified
3451 when a line/row is swapped out of that privileged position. So for
3452 formulas that use a range of rows or columns, it may often be better
3453 to anchor the formula with \"I\" row markers, or to offset from the
3454 borders of the table using the @< @> $< $> makers."
3455 (let (n nmax len char
(start 0))
3456 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3459 (setq start
(match-end 3))
3460 (setq nmax
(if (equal (match-string 1 s
) "@")
3461 (1- (length org-table-dlines
))
3462 org-table-current-ncol
)
3463 len
(- (match-end 2) (match-beginning 2))
3464 char
(string-to-char (match-string 2 s
))
3468 (if (or (< n
1) (> n nmax
))
3469 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3470 (match-string 0 s
) s
))
3471 (setq start
(match-beginning 0))
3472 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3475 (defun org-table-formula-substitute-names (f)
3476 "Replace $const with values in string F."
3478 (pp (/= (string-to-char f
) ?
'))
3479 (duration (string-match-p ";.*[Tt].*\\'" f
))
3480 (new (replace-regexp-in-string ; Check for column names.
3481 org-table-column-name-regexp
3483 (concat "$" (cdr (assoc (match-string 1 m
)
3484 org-table-column-names
))))
3486 ;; Parameters and constants.
3489 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3491 (if (match-end 2) (setq start
(match-end 2))
3493 ;; When a duration is expected, convert value on the fly.
3496 (let ((v (org-table-get-constant (match-string 1 new
))))
3497 (if (and (org-string-nw-p v
) duration
)
3498 (org-table-time-string-to-seconds v
)
3501 (setq new
(replace-match
3502 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3503 (if org-table-formula-debug
(propertize new
:orig-formula f
) new
)))
3505 (defun org-table-get-constant (const)
3506 "Find the value for a parameter or constant in a formula.
3507 Parameters get priority."
3508 (or (cdr (assoc const org-table-local-parameters
))
3509 (cdr (assoc const org-table-formula-constants-local
))
3510 (cdr (assoc const org-table-formula-constants
))
3511 (and (fboundp 'constants-get
) (constants-get const
))
3512 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3513 (org-entry-get nil
(substring const
5) 'inherit
))
3516 (defvar org-table-fedit-map
3517 (let ((map (make-sparse-keymap)))
3518 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3519 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3520 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3521 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3522 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3523 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3524 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3525 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3526 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3527 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3528 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3529 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3530 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3531 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3532 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3533 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3534 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3535 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3536 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3537 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3540 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3542 ["Finish and Install" org-table-fedit-finish t
]
3543 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3544 ["Abort" org-table-fedit-abort t
]
3546 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3547 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3549 "Shift Reference at Point"
3550 ["Up" org-table-fedit-ref-up t
]
3551 ["Down" org-table-fedit-ref-down t
]
3552 ["Left" org-table-fedit-ref-left t
]
3553 ["Right" org-table-fedit-ref-right t
]
3555 "Change Test Row for Column Formulas"
3556 ["Up" org-table-fedit-line-up t
]
3557 ["Down" org-table-fedit-line-down t
]
3559 ["Scroll Table Window" org-table-fedit-scroll t
]
3560 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3561 ["Show Table Grid" org-table-fedit-toggle-coordinates
3562 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3563 org-table-overlay-coordinates
)]
3565 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3566 :style toggle
:selected org-table-buffer-is-an
]))
3569 (defvar org-table--fedit-source nil
3570 "Position of the TBLFM line being edited.")
3573 (defun org-table-edit-formulas ()
3574 "Edit the formulas of the current table in a separate buffer."
3576 (let ((at-tblfm (org-at-TBLFM-p)))
3577 (unless (or at-tblfm
(org-at-table-p))
3578 (user-error "Not at a table"))
3580 ;; Move point within the table before analyzing it.
3581 (when at-tblfm
(re-search-backward "^[ \t]*|"))
3582 (org-table-analyze))
3583 (let ((key (org-table-current-field-formula 'key
'noerror
))
3584 (eql (sort (org-table-get-stored-formulas t
(and at-tblfm
(point)))
3585 #'org-table-formula-less-p
))
3586 (pos (point-marker))
3587 (source (copy-marker (line-beginning-position)))
3589 (wc (current-window-configuration))
3590 (sel-win (selected-window))
3591 (titles '((column .
"# Column Formulas\n")
3592 (field .
"# Field and Range Formulas\n")
3593 (named .
"# Named Field Formulas\n"))))
3594 (org-switch-to-buffer-other-window "*Edit Formulas*")
3596 ;; Keep global-font-lock-mode from turning on font-lock-mode
3597 (let ((font-lock-global-modes '(not fundamental-mode
)))
3599 (setq-local font-lock-global-modes
(list 'not major-mode
))
3600 (setq-local org-pos pos
)
3601 (setq-local org-table--fedit-source source
)
3602 (setq-local org-window-configuration wc
)
3603 (setq-local org-selected-window sel-win
)
3604 (use-local-map org-table-fedit-map
)
3605 (add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3606 (easy-menu-add org-table-fedit-menu
)
3607 (setq startline
(org-current-line))
3610 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry
))
3612 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3614 (title (assq type titles
)))
3616 (unless (bobp) (insert "\n"))
3618 (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3619 (setq titles
(remove title titles
)))
3620 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3622 (if (memq (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3623 (car entry
) " = " (cdr entry
) "\n")))
3624 (remove-text-properties 0 (length s
) '(face nil
) s
)
3626 (when (eq org-table-use-standard-references t
)
3627 (org-table-fedit-toggle-ref-type))
3628 (org-goto-line startline
)
3629 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3630 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3631 See menu for more commands.")))))
3633 (defun org-table-fedit-post-command ()
3634 (when (not (memq this-command
'(lisp-complete-symbol)))
3635 (let ((win (selected-window)))
3637 (ignore-errors (org-table-show-reference))
3638 (select-window win
)))))
3640 (defun org-table-formula-to-user (s)
3641 "Convert a formula from internal to user representation."
3642 (if (eq org-table-use-standard-references t
)
3643 (org-table-convert-refs-to-an s
)
3646 (defun org-table-formula-from-user (s)
3647 "Convert a formula from user to internal representation."
3648 (if org-table-use-standard-references
3649 (org-table-convert-refs-to-rc s
)
3652 (defun org-table-convert-refs-to-rc (s)
3653 "Convert spreadsheet references from A7 to @7$28.
3654 Works for single references, but also for entire formulas and even the
3657 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3660 ;; format match, just advance
3661 (setq start
(match-end 0)))
3662 ((and (> (match-beginning 0) 0)
3663 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3664 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3665 ;; 3.e5 or something like this.
3666 (setq start
(match-end 0)))
3667 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3668 ;; (member (match-string 1 s)
3669 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3671 ;; function name, just advance
3672 (setq start
(match-end 0)))
3674 (setq start
(match-beginning 0)
3676 (if (equal (match-string 2 s
) "&")
3677 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3679 (string-to-number (match-string 2 s
))
3680 (org-letters-to-number (match-string 1 s
))))
3684 (defun org-table-convert-refs-to-an (s)
3685 "Convert spreadsheet references from to @7$28 to AB7.
3686 Works for single references, but also for entire formulas and even the
3688 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3689 (setq s
(replace-match
3691 (org-number-to-letters
3692 (string-to-number (match-string 2 s
)))
3693 (string-to-number (match-string 1 s
)))
3695 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3696 (setq s
(replace-match (concat "\\1"
3697 (org-number-to-letters
3698 (string-to-number (match-string 2 s
))) "&")
3702 (defun org-letters-to-number (s)
3703 "Convert a base 26 number represented by letters into an integer.
3704 For example: AB -> 28."
3707 (while (> (length s
) 0)
3708 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3712 (defun org-number-to-letters (n)
3713 "Convert an integer into a base 26 number represented by letters.
3714 For example: 28 -> AB."
3717 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3721 (defun org-table-time-string-to-seconds (s)
3722 "Convert a time string into numerical duration in seconds.
3723 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3724 If S is a string representing a number, keep this number."
3727 (let (hour minus min sec res
)
3729 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3730 (setq minus
(< 0 (length (match-string 1 s
)))
3731 hour
(string-to-number (match-string 2 s
))
3732 min
(string-to-number (match-string 3 s
))
3733 sec
(string-to-number (match-string 4 s
)))
3735 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3736 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3737 ((and (not (string-match org-ts-regexp-both s
))
3738 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3739 (setq minus
(< 0 (length (match-string 1 s
)))
3740 hour
(string-to-number (match-string 2 s
))
3741 min
(string-to-number (match-string 3 s
)))
3743 (setq res
(- (+ (* hour
3600) (* min
60))))
3744 (setq res
(+ (* hour
3600) (* min
60)))))
3745 (t (setq res
(string-to-number s
))))
3746 (number-to-string res
))))
3748 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3749 "Convert a number of seconds to a time string.
3750 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3751 minutes or seconds."
3752 (let* ((secs0 (abs secs
))
3754 (cond ((eq output-format
'days
)
3755 (format "%.3f" (/ (float secs0
) 86400)))
3756 ((eq output-format
'hours
)
3757 (format "%.2f" (/ (float secs0
) 3600)))
3758 ((eq output-format
'minutes
)
3759 (format "%.1f" (/ (float secs0
) 60)))
3760 ((eq output-format
'seconds
)
3761 (format "%d" secs0
))
3762 (t (format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3763 (if (< secs
0) (concat "-" res
) res
)))
3765 (defun org-table-fedit-convert-buffer (function)
3766 "Convert all references in this buffer, using FUNCTION."
3767 (let ((origin (copy-marker (line-beginning-position))))
3768 (goto-char (point-min))
3770 (insert (funcall function
(buffer-substring (point) (line-end-position))))
3771 (delete-region (point) (line-end-position))
3774 (set-marker origin nil
)))
3776 (defun org-table-fedit-toggle-ref-type ()
3777 "Convert all references in the buffer from B3 to @3$2 and back."
3779 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
3780 (org-table-fedit-convert-buffer
3781 (if org-table-buffer-is-an
3782 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3783 (message "Reference type switched to %s"
3784 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3786 (defun org-table-fedit-ref-up ()
3787 "Shift the reference at point one row/hline up."
3789 (org-table-fedit-shift-reference 'up
))
3790 (defun org-table-fedit-ref-down ()
3791 "Shift the reference at point one row/hline down."
3793 (org-table-fedit-shift-reference 'down
))
3794 (defun org-table-fedit-ref-left ()
3795 "Shift the reference at point one field to the left."
3797 (org-table-fedit-shift-reference 'left
))
3798 (defun org-table-fedit-ref-right ()
3799 "Shift the reference at point one field to the right."
3801 (org-table-fedit-shift-reference 'right
))
3803 (defun org-table-fedit-shift-reference (dir)
3805 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3806 (if (memq dir
'(left right
))
3807 (org-rematch-and-replace 1 (eq dir
'left
))
3808 (user-error "Cannot shift reference in this direction")))
3809 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3810 ;; A B3-like reference
3811 (if (memq dir
'(up down
))
3812 (org-rematch-and-replace 2 (eq dir
'up
))
3813 (org-rematch-and-replace 1 (eq dir
'left
))))
3815 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3816 ;; An internal reference
3817 (if (memq dir
'(up down
))
3818 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3819 (org-rematch-and-replace 5 (eq dir
'left
))))))
3821 (defun org-rematch-and-replace (n &optional decr hline
)
3822 "Re-match the group N, and replace it with the shifted reference."
3823 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3824 (goto-char (match-beginning n
))
3825 (and (looking-at (regexp-quote (match-string n
)))
3826 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3829 (defun org-table-shift-refpart (ref &optional decr hline
)
3830 "Shift a reference part REF.
3831 If DECR is set, decrease the references row/column, else increase.
3832 If HLINE is set, this may be a hline reference, it certainly is not
3833 a translation reference."
3835 (let* ((sign (string-match "^[-+]" ref
)) n
)
3837 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3839 ((and hline
(string-match "^I+" ref
))
3840 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3841 (setq n
(+ n
(if decr -
1 1)))
3842 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3844 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3846 (concat sign
(make-string n ?I
)))
3848 ((string-match "^[0-9]+" ref
)
3849 (setq n
(string-to-number (concat sign ref
)))
3850 (setq n
(+ n
(if decr -
1 1)))
3852 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3853 (number-to-string (max 1 n
))))
3855 ((string-match "^[a-zA-Z]+" ref
)
3856 (org-number-to-letters
3857 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3859 (t (user-error "Cannot shift reference"))))))
3861 (defun org-table-fedit-toggle-coordinates ()
3862 "Toggle the display of coordinates in the referenced table."
3864 (let ((pos (marker-position org-pos
)))
3865 (with-current-buffer (marker-buffer org-pos
)
3868 (org-table-toggle-coordinate-overlays)))))
3870 (defun org-table-fedit-finish (&optional arg
)
3871 "Parse the buffer for formula definitions and install them.
3872 With prefix ARG, apply the new formulas to the table."
3874 (org-table-remove-rectangle-highlight)
3875 (when org-table-use-standard-references
3876 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3877 (setq org-table-buffer-is-an nil
))
3879 (sel-win org-selected-window
)
3880 (source org-table--fedit-source
)
3882 (goto-char (point-min))
3883 (while (re-search-forward
3884 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3886 (let ((var (match-string 1))
3887 (form (org-trim (match-string 3))))
3888 (unless (equal form
"")
3889 (while (string-match "[ \t]*\n[ \t]*" form
)
3890 (setq form
(replace-match " " t t form
)))
3891 (when (assoc var eql
)
3892 (user-error "Double formulas for %s" var
))
3893 (push (cons var form
) eql
))))
3894 (set-window-configuration org-window-configuration
)
3895 (select-window sel-win
)
3897 (org-table-store-formulas eql
)
3898 (set-marker pos nil
)
3899 (set-marker source nil
)
3900 (kill-buffer "*Edit Formulas*")
3902 (org-table-recalculate 'all
)
3903 (message "New formulas installed - press C-u C-c C-c to apply."))))
3905 (defun org-table-fedit-abort ()
3906 "Abort editing formulas, without installing the changes."
3908 (org-table-remove-rectangle-highlight)
3909 (let ((pos org-pos
) (sel-win org-selected-window
))
3910 (set-window-configuration org-window-configuration
)
3911 (select-window sel-win
)
3913 (move-marker pos nil
)
3914 (message "Formula editing aborted without installing changes")))
3916 (defun org-table-fedit-lisp-indent ()
3917 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3919 (let ((pos (point)) beg end ind
)
3920 (beginning-of-line 1)
3922 ((looking-at "[ \t]")
3924 (call-interactively 'lisp-indent-line
))
3925 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3926 ((not (fboundp 'pp-buffer
))
3927 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3928 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3929 (goto-char (- (match-end 0) 2))
3931 (setq ind
(make-string (current-column) ?\
))
3932 (condition-case nil
(forward-sexp 1)
3934 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3937 (narrow-to-region beg end
)
3938 (if (eq last-command this-command
)
3940 (goto-char (point-min))
3941 (setq this-command nil
)
3942 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3943 (replace-match " ")))
3945 (untabify (point-min) (point-max))
3946 (goto-char (1+ (point-min)))
3947 (while (re-search-forward "^." nil t
)
3948 (beginning-of-line 1)
3950 (goto-char (point-max))
3951 (org-delete-backward-char 1)))
3955 (defvar org-show-positions nil
)
3957 (defun org-table-show-reference (&optional local
)
3958 "Show the location/value of the $ expression at point.
3959 When LOCAL is non-nil, show references for the table at point."
3961 (org-table-remove-rectangle-highlight)
3962 (when local
(org-table-analyze))
3964 (let ((pos (if local
(point) org-pos
))
3966 (org-inhibit-highlight-removal t
)
3967 (win (selected-window))
3968 (org-show-positions nil
)
3969 var name e what match dest
)
3971 ((org-in-regexp "^@[0-9]+[ \t=]")
3972 (setq match
(concat (substring (match-string 0) 0 -
1)
3974 (substring (match-string 0) 0 -
1)
3977 ((or (org-in-regexp org-table-range-regexp2
)
3978 (org-in-regexp org-table-translate-regexp
)
3979 (org-in-regexp org-table-range-regexp
))
3982 (org-table-convert-refs-to-rc (match-string 0))))
3984 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3985 ((org-in-regexp "\\$[0-9]+") 'column
)
3987 (t (user-error "No reference at point")))
3988 match
(and what
(or match
(match-string 0))))
3989 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3990 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3991 'secondary-selection
))
3992 (add-hook 'before-change-functions
3993 #'org-table-remove-rectangle-highlight
)
3994 (when (eq what
'name
) (setq var
(substring match
1)))
3995 (when (eq what
'range
)
3996 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3997 (setq match
(org-table-formula-substitute-names match
)))
4001 (re-search-backward "^\\S-" nil t
)
4003 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4004 \\([0-9]+\\|&\\)\\) *=")
4007 (org-table-convert-refs-to-rc (match-string 1))))
4008 (org-table-add-rectangle-overlay
4009 (match-beginning 1) (match-end 1) face2
))))
4010 (if (and (markerp pos
) (marker-buffer pos
))
4011 (if (get-buffer-window (marker-buffer pos
))
4012 (select-window (get-buffer-window (marker-buffer pos
)))
4013 (org-switch-to-buffer-other-window (get-buffer-window
4014 (marker-buffer pos
)))))
4016 (org-table-force-dataline)
4018 (if local org-table-current-begin-pos
(org-table-begin))))
4020 (setq name
(substring dest
1))
4022 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
4023 (org-table-goto-field dest
))
4024 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4026 (org-table-goto-field dest
))
4027 (t (org-table-goto-column (string-to-number name
))))
4028 (move-marker pos
(point))
4029 (org-table-highlight-rectangle nil nil face2
))
4031 ((equal dest match
))
4034 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
4035 ((setq e
(assoc var org-table-named-field-locations
))
4036 (org-table-goto-field var
)
4037 (org-table-highlight-rectangle)
4038 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
4039 ((setq e
(assoc var org-table-column-names
))
4040 (org-table-goto-column (string-to-number (cdr e
)))
4041 (org-table-highlight-rectangle)
4042 (goto-char table-start
)
4043 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
4046 (goto-char (match-beginning 1))
4047 (org-table-highlight-rectangle)
4048 (message "Named column (column %s)" (cdr e
)))
4049 (user-error "Column name not found")))
4052 (org-table-goto-column (string-to-number (substring match
1)))
4053 (org-table-highlight-rectangle)
4054 (message "Column %s" (substring match
1)))
4055 ((setq e
(assoc var org-table-local-parameters
))
4056 (goto-char table-start
)
4057 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
4059 (goto-char (match-beginning 1))
4060 (org-table-highlight-rectangle)
4061 (message "Local parameter."))
4062 (user-error "Parameter not found")))
4063 ((not var
) (user-error "No reference at point"))
4064 ((setq e
(assoc var org-table-formula-constants-local
))
4065 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4067 ((setq e
(assoc var org-table-formula-constants
))
4068 (message "Constant: $%s=%s in `org-table-formula-constants'."
4070 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4071 (message "Constant: $%s=%s, from `constants.el'%s."
4072 var e
(format " (%s units)" constants-unit-system
)))
4073 (t (user-error "Undefined name $%s" var
)))
4075 (when (and org-show-positions
4076 (not (memq this-command
'(org-table-fedit-scroll
4077 org-table-fedit-scroll-down
))))
4078 (push pos org-show-positions
)
4079 (push table-start org-show-positions
)
4080 (let ((min (apply 'min org-show-positions
))
4081 (max (apply 'max org-show-positions
)))
4082 (set-window-start (selected-window) min
)
4084 (or (pos-visible-in-window-p max
)
4085 (set-window-start (selected-window) max
)))))
4086 (select-window win
))))
4088 (defun org-table-force-dataline ()
4089 "Make sure the cursor is in a dataline in a table."
4090 (unless (save-excursion
4091 (beginning-of-line 1)
4092 (looking-at org-table-dataline-regexp
))
4093 (let* ((re org-table-dataline-regexp
)
4094 (p1 (save-excursion (re-search-forward re nil
'move
)))
4095 (p2 (save-excursion (re-search-backward re nil
'move
))))
4097 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4099 ((or p1 p2
) (goto-char (or p1 p2
)))
4100 (t (user-error "No table dataline around here"))))))
4102 (defun org-table-fedit-line-up ()
4103 "Move cursor one line up in the window showing the table."
4105 (org-table-fedit-move 'previous-line
))
4107 (defun org-table-fedit-line-down ()
4108 "Move cursor one line down in the window showing the table."
4110 (org-table-fedit-move 'next-line
))
4112 (defun org-table-fedit-move (command)
4113 "Move the cursor in the window showing the table.
4114 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4115 (let ((org-table-allow-automatic-line-recalculation nil
)
4116 (pos org-pos
) (win (selected-window)) p
)
4117 (select-window (get-buffer-window (marker-buffer org-pos
)))
4119 (call-interactively command
)
4120 (while (and (org-at-table-p)
4121 (org-at-table-hline-p))
4122 (call-interactively command
))
4123 (or (org-at-table-p) (goto-char p
))
4124 (move-marker pos
(point))
4125 (select-window win
)))
4127 (defun org-table-fedit-scroll (N)
4129 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4130 (scroll-other-window N
)))
4132 (defun org-table-fedit-scroll-down (N)
4134 (org-table-fedit-scroll (- N
)))
4136 (defvar org-table-rectangle-overlays nil
)
4138 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4139 "Add a new overlay."
4140 (let ((ov (make-overlay beg end
)))
4141 (overlay-put ov
'face
(or face
'secondary-selection
))
4142 (push ov org-table-rectangle-overlays
)))
4144 (defun org-table-highlight-rectangle (&optional beg end face
)
4145 "Highlight rectangular region in a table.
4146 When buffer positions BEG and END are provided, use them to
4147 delimit the region to highlight. Otherwise, refer to point. Use
4148 FACE, when non-nil, for the highlight."
4149 (let* ((beg (or beg
(point)))
4150 (end (or end
(point)))
4156 (cons (line-beginning-position) (org-table-current-column))))
4160 (cons (line-beginning-position) (org-table-current-column)))))
4161 (when (boundp 'org-show-positions
)
4162 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4163 (goto-char (car start-coordinates
))
4164 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
4165 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
4166 (last-row (car end-coordinates
)))
4167 (while (<= (point) last-row
)
4168 (when (looking-at org-table-dataline-regexp
)
4169 (org-table-goto-column column-start
)
4170 (skip-chars-backward "^|\n")
4172 (org-table-goto-column column-end
)
4173 (skip-chars-forward "^|\n")
4174 (org-table-add-rectangle-overlay p
(point) face
)))
4176 (goto-char (car start-coordinates
)))
4177 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
4179 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
4180 "Remove the rectangle overlays."
4181 (unless org-inhibit-highlight-removal
4182 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4183 (mapc 'delete-overlay org-table-rectangle-overlays
)
4184 (setq org-table-rectangle-overlays nil
)))
4186 (defvar-local org-table-coordinate-overlays nil
4187 "Collects the coordinate grid overlays, so that they can be removed.")
4189 (defun org-table-overlay-coordinates ()
4190 "Add overlays to the table at point, to show row/column coordinates."
4192 (mapc 'delete-overlay org-table-coordinate-overlays
)
4193 (setq org-table-coordinate-overlays nil
)
4195 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4196 (goto-char (org-table-begin))
4197 (while (org-at-table-p)
4198 (setq eol
(point-at-eol))
4199 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4200 (push ov org-table-coordinate-overlays
)
4201 (setq hline
(looking-at org-table-hline-regexp
))
4202 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4203 (format "%4d" (setq id
(1+ id
)))))
4204 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4207 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4208 (setq beg
(1+ (match-beginning 0))
4210 s1
(concat "$" (int-to-string ic
))
4211 s2
(org-number-to-letters ic
)
4212 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4213 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4214 (push ov org-table-coordinate-overlays
)
4215 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4216 (beginning-of-line 2)))))
4219 (defun org-table-toggle-coordinate-overlays ()
4220 "Toggle the display of Row/Column numbers in tables."
4222 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4223 (message "Tables Row/Column numbers display turned %s"
4224 (if org-table-overlay-coordinates
"on" "off"))
4225 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4227 (unless org-table-overlay-coordinates
4228 (mapc 'delete-overlay org-table-coordinate-overlays
)
4229 (setq org-table-coordinate-overlays nil
)))
4232 (defun org-table-toggle-formula-debugger ()
4233 "Toggle the formula debugger in tables."
4235 (setq org-table-formula-debug
(not org-table-formula-debug
))
4236 (message "Formula debugging has been turned %s"
4237 (if org-table-formula-debug
"on" "off")))
4239 ;;; The orgtbl minor mode
4241 ;; Define a minor mode which can be used in other modes in order to
4242 ;; integrate the Org table editor.
4244 ;; This is really a hack, because the Org table editor uses several
4245 ;; keys which normally belong to the major mode, for example the TAB
4246 ;; and RET keys. Here is how it works: The minor mode defines all the
4247 ;; keys necessary to operate the table editor, but wraps the commands
4248 ;; into a function which tests if the cursor is currently inside
4249 ;; a table. If that is the case, the table editor command is
4250 ;; executed. However, when any of those keys is used outside a table,
4251 ;; the function uses `key-binding' to look up if the key has an
4252 ;; associated command in another currently active keymap (minor modes,
4253 ;; major mode, global), and executes that command. There might be
4254 ;; problems if any of the keys used by the table editor is otherwise
4255 ;; used as a prefix key.
4257 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4258 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4259 ;; addresses this by checking explicitly for both bindings.
4261 ;; The optimized version (see variable `orgtbl-optimized') takes over
4262 ;; all keys which are bound to `self-insert-command' in the *global map*.
4263 ;; Some modes bind other commands to simple characters, for example
4264 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4265 ;; active, this binding is ignored inside tables and replaced with a
4266 ;; modified self-insert.
4269 (defvar orgtbl-mode-map
(make-keymap)
4270 "Keymap for `orgtbl-mode'.")
4272 (defvar org-old-auto-fill-inhibit-regexp nil
4273 "Local variable used by `orgtbl-mode'.")
4275 (defconst orgtbl-line-start-regexp
4276 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4277 "Matches a line belonging to an orgtbl.")
4279 (defconst orgtbl-extra-font-lock-keywords
4280 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4281 0 (quote 'org-table
) 'prepend
))
4282 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4284 ;; Install it as a minor mode.
4285 (put 'orgtbl-mode
:included t
)
4286 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4289 (define-minor-mode orgtbl-mode
4290 "The `org-mode' table editor as a minor mode for use in other modes."
4291 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4292 (org-load-modules-maybe)
4294 ((derived-mode-p 'org-mode
)
4295 ;; Exit without error, in case some hook functions calls this
4296 ;; by accident in org-mode.
4297 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4299 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4300 ;; Make sure we are first in minor-mode-map-alist
4301 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4302 ;; FIXME: maybe it should use emulation-mode-map-alists?
4303 (and c
(setq minor-mode-map-alist
4304 (cons c
(delq c minor-mode-map-alist
)))))
4305 (setq-local org-table-may-need-update t
)
4306 (add-hook 'before-change-functions
'org-before-change-function
4308 (setq-local org-old-auto-fill-inhibit-regexp
4309 auto-fill-inhibit-regexp
)
4310 (setq-local auto-fill-inhibit-regexp
4311 (if auto-fill-inhibit-regexp
4312 (concat orgtbl-line-start-regexp
"\\|"
4313 auto-fill-inhibit-regexp
)
4314 orgtbl-line-start-regexp
))
4315 (add-to-invisibility-spec '(org-cwidth))
4316 (when (fboundp 'font-lock-add-keywords
)
4317 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4318 (org-restart-font-lock))
4319 (easy-menu-add orgtbl-mode-menu
))
4321 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4322 (org-table-cleanup-narrow-column-properties)
4323 (org-remove-from-invisibility-spec '(org-cwidth))
4324 (remove-hook 'before-change-functions
'org-before-change-function t
)
4325 (when (fboundp 'font-lock-remove-keywords
)
4326 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4327 (org-restart-font-lock))
4328 (easy-menu-remove orgtbl-mode-menu
)
4329 (force-mode-line-update 'all
))))
4331 (defun org-table-cleanup-narrow-column-properties ()
4332 "Remove all properties related to narrow-column invisibility."
4333 (let ((s (point-min)))
4334 (while (setq s
(text-property-any s
(point-max)
4335 'display org-narrow-column-arrow
))
4336 (remove-text-properties s
(1+ s
) '(display t
)))
4337 (setq s
(point-min))
4338 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4339 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4340 (setq s
(point-min))
4341 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4342 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4344 (defun orgtbl-make-binding (fun n
&rest keys
)
4345 "Create a function for binding in the table minor mode.
4346 FUN is the command to call inside a table. N is used to create a unique
4347 command name. KEYS are keys that should be checked in for a command
4348 to execute outside of tables."
4351 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4353 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4354 "Outside of tables, run the binding of `"
4355 (mapconcat #'key-description keys
"' or `")
4360 (list 'call-interactively
(list 'quote fun
))
4361 (list 'let
'(orgtbl-mode)
4362 (list 'call-interactively
4365 (list 'key-binding k
))
4367 '('orgtbl-error
))))))))
4369 (defun orgtbl-error ()
4370 "Error when there is no default binding for a table key."
4372 (user-error "This key has no function outside tables"))
4374 (defun orgtbl-setup ()
4375 "Setup orgtbl keymaps."
4378 '(([(meta shift left
)] org-table-delete-column
)
4379 ([(meta left
)] org-table-move-column-left
)
4380 ([(meta right
)] org-table-move-column-right
)
4381 ([(meta shift right
)] org-table-insert-column
)
4382 ([(meta shift up
)] org-table-kill-row
)
4383 ([(meta shift down
)] org-table-insert-row
)
4384 ([(meta up
)] org-table-move-row-up
)
4385 ([(meta down
)] org-table-move-row-down
)
4386 ("\C-c\C-w" org-table-cut-region
)
4387 ("\C-c\M-w" org-table-copy-region
)
4388 ("\C-c\C-y" org-table-paste-rectangle
)
4389 ("\C-c\C-w" org-table-wrap-region
)
4390 ("\C-c-" org-table-insert-hline
)
4391 ("\C-c}" org-table-toggle-coordinate-overlays
)
4392 ("\C-c{" org-table-toggle-formula-debugger
)
4393 ("\C-m" org-table-next-row
)
4394 ([(shift return
)] org-table-copy-down
)
4395 ("\C-c?" org-table-field-info
)
4396 ("\C-c " org-table-blank-field
)
4397 ("\C-c+" org-table-sum
)
4398 ("\C-c=" org-table-eval-formula
)
4399 ("\C-c'" org-table-edit-formulas
)
4400 ("\C-c`" org-table-edit-field
)
4401 ("\C-c*" org-table-recalculate
)
4402 ("\C-c^" org-table-sort-lines
)
4403 ("\M-a" org-table-beginning-of-field
)
4404 ("\M-e" org-table-end-of-field
)
4405 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4407 (while (setq elt
(pop bindings
))
4408 (setq nfunc
(1+ nfunc
))
4409 (setq key
(org-key (car elt
))
4411 cmd
(orgtbl-make-binding fun nfunc key
))
4412 (org-defkey orgtbl-mode-map key cmd
))
4414 ;; Special treatment needed for TAB, RET and DEL
4415 (org-defkey orgtbl-mode-map
[(return)]
4416 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4417 (org-defkey orgtbl-mode-map
"\C-m"
4418 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4419 (org-defkey orgtbl-mode-map
[(tab)]
4420 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4421 (org-defkey orgtbl-mode-map
"\C-i"
4422 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4423 (org-defkey orgtbl-mode-map
[(shift tab
)]
4424 (orgtbl-make-binding 'org-table-previous-field
104
4425 [(shift tab
)] [(tab)] "\C-i"))
4426 (org-defkey orgtbl-mode-map
[backspace]
4427 (orgtbl-make-binding 'org-delete-backward-char 109
4428 [backspace] (kbd "DEL")))
4430 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4431 (orgtbl-make-binding 'org-table-previous-field
107
4432 [S-iso-lefttab
] [backtab] [(shift tab)]
4435 (org-defkey orgtbl-mode-map [backtab]
4436 (orgtbl-make-binding 'org-table-previous-field
108
4437 [backtab] [S-iso-lefttab] [(shift tab)]
4440 (org-defkey orgtbl-mode-map "\M-\C-m"
4441 (orgtbl-make-binding 'org-table-wrap-region 105
4442 "\M-\C-m" [(meta return)]))
4443 (org-defkey orgtbl-mode-map [(meta return)]
4444 (orgtbl-make-binding 'org-table-wrap-region 106
4445 [(meta return)] "\M-\C-m"))
4447 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4448 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4450 (when orgtbl-optimized
4451 ;; If the user wants maximum table support, we need to hijack
4452 ;; some standard editing functions
4453 (org-remap orgtbl-mode-map
4454 'self-insert-command 'orgtbl-self-insert-command
4455 'delete-char 'org-delete-char
4456 'delete-backward-char 'org-delete-backward-char)
4457 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4458 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4460 ["Create or convert" org-table-create-or-convert-from-region
4461 :active (not (org-at-table-p)) :keys "C-c |" ]
4463 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4464 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4465 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4466 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4468 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4469 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4470 ["Copy Field from Above"
4471 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4474 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4475 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4476 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4477 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4479 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4480 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4481 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4482 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4483 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4485 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4487 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4488 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4489 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4490 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4493 ["Insert table template" orgtbl-insert-radio-table
4494 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
4495 ["Comment/uncomment table" orgtbl-toggle-comment t])
4497 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4498 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4499 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4500 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4501 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4502 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4503 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4504 ["Sum Column/Rectangle" org-table-sum
4505 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4506 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4508 org-table-toggle-formula-debugger :active (org-at-table-p)
4510 :style toggle :selected org-table-formula-debug]
4511 ["Show Col/Row Numbers"
4512 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4514 :style toggle :selected org-table-overlay-coordinates]
4517 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4518 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4521 (defun orgtbl-ctrl-c-ctrl-c (arg)
4522 "If the cursor is inside a table, realign the table.
4523 If it is a table to be sent away to a receiver, do it.
4524 With prefix arg, also recompute table."
4526 (let ((case-fold-search t) (pos (point)) action)
4528 (beginning-of-line 1)
4530 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4531 ((looking-at "[ \t]*|") pos)
4532 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4536 (org-table-maybe-eval-formula)
4538 (call-interactively 'org-table-recalculate)
4539 (org-table-maybe-recalculate-line))
4540 (call-interactively 'org-table-align)
4541 (when (orgtbl-send-table 'maybe)
4542 (run-hooks 'orgtbl-after-send-table-hook)))
4543 ((eq action 'recalc)
4545 (beginning-of-line 1)
4546 (skip-chars-backward " \r\n\t")
4547 (if (org-at-table-p)
4548 (org-call-with-arg 'org-table-recalculate t))))
4549 (t (let (orgtbl-mode)
4550 (call-interactively (key-binding "\C-c\C-c")))))))
4552 (defun orgtbl-create-or-convert-from-region (_arg)
4553 "Create table or convert region to table, if no conflicting binding.
4554 This installs the table binding `C-c |', but only if there is no
4555 conflicting binding to this key outside orgtbl-mode."
4557 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4559 (call-interactively cmd)
4560 (call-interactively 'org-table-create-or-convert-from-region))))
4562 (defun orgtbl-tab (arg)
4563 "Justification and field motion for `orgtbl-mode'."
4565 (if arg (org-table-edit-field t)
4566 (org-table-justify-field-maybe)
4567 (org-table-next-field)))
4569 (defun orgtbl-ret ()
4570 "Justification and field motion for `orgtbl-mode'."
4574 (org-table-justify-field-maybe)
4575 (org-table-next-row)))
4577 (defun orgtbl-self-insert-command (N)
4578 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4579 If the cursor is in a table looking at whitespace, the whitespace is
4580 overwritten, and the table is not marked as requiring realignment."
4582 (if (and (org-at-table-p)
4584 (and org-table-auto-blank-field
4585 (member last-command
4586 '(orgtbl-hijacker-command-100
4587 orgtbl-hijacker-command-101
4588 orgtbl-hijacker-command-102
4589 orgtbl-hijacker-command-103
4590 orgtbl-hijacker-command-104
4591 orgtbl-hijacker-command-105
4593 (org-table-blank-field))
4596 (looking-at "[^|\n]* \\( \\)|"))
4597 (let (org-table-may-need-update)
4598 (delete-region (match-beginning 1) (match-end 1))
4599 (self-insert-command N))
4600 (setq org-table-may-need-update t)
4603 (cmd (or (key-binding
4604 (or (and (listp function-key-map)
4605 (setq a (assoc last-input-event function-key-map))
4607 (vector last-input-event)))
4608 'self-insert-command)))
4609 (call-interactively cmd)
4610 (if (and org-self-insert-cluster-for-undo
4611 (eq cmd 'self-insert-command))
4612 (if (not (eq last-command 'orgtbl-self-insert-command))
4613 (setq org-self-insert-command-undo-counter 1)
4614 (if (>= org-self-insert-command-undo-counter 20)
4615 (setq org-self-insert-command-undo-counter 1)
4616 (and (> org-self-insert-command-undo-counter 0)
4618 (not (cadr buffer-undo-list)) ; remove nil entry
4619 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4620 (setq org-self-insert-command-undo-counter
4621 (1+ org-self-insert-command-undo-counter))))))))
4624 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4625 "Regular expression matching exponentials as produced by calc.")
4627 (defun orgtbl-gather-send-defs ()
4628 "Gather a plist of :name, :transform, :params for each destination before
4631 (goto-char (org-table-begin))
4633 (beginning-of-line 0)
4634 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4635 (let ((name (org-no-properties (match-string 1)))
4636 (transform (intern (match-string 2)))
4637 (params (if (match-end 3)
4638 (read (concat "(" (match-string 3) ")")))))
4639 (push (list :name name :transform transform :params params)
4641 (beginning-of-line 0)))
4644 (defun orgtbl-send-replace-tbl (name text)
4645 "Find and replace table NAME with TEXT."
4647 (goto-char (point-min))
4648 (let* ((location-flag nil)
4649 (name (regexp-quote name))
4650 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4651 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4652 (while (re-search-forward begin-re nil t)
4653 (unless location-flag (setq location-flag t))
4654 (let ((beg (line-beginning-position 2)))
4655 (unless (re-search-forward end-re nil t)
4656 (user-error "Cannot find end of receiver location at %d" beg))
4658 (delete-region beg (point))
4659 (insert text "\n")))
4660 (unless location-flag
4661 (user-error "No valid receiver location found in the buffer")))))
4664 (defun org-table-to-lisp (&optional txt)
4665 "Convert the table at point to a Lisp structure.
4666 The structure will be a list. Each item is either the symbol `hline'
4667 for a horizontal separator line, or a list of field values as strings.
4668 The table is taken from the parameter TXT, or from the buffer at point."
4669 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4671 (buffer-substring-no-properties (org-table-begin)
4674 (if (string-match org-table-hline-regexp x) 'hline
4675 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4676 (org-split-string txt "[ \t]*\n[ \t]*"))))
4678 (defun orgtbl-send-table (&optional maybe)
4679 "Send a transformed version of table at point to the receiver position.
4680 With argument MAYBE, fail quietly if no transformation is defined
4684 (unless (org-at-table-p) (user-error "Not at a table"))
4685 ;; when non-interactive, we assume align has just happened.
4686 (when (called-interactively-p 'any) (org-table-align))
4687 (let ((dests (orgtbl-gather-send-defs))
4688 (table (org-table-to-lisp
4689 (buffer-substring-no-properties (org-table-begin)
4693 (if maybe (throw 'exit nil)
4694 (user-error "Don't know how to transform this table")))
4695 (dolist (dest dests)
4696 (let ((name (plist-get dest :name))
4697 (transform (plist-get dest :transform))
4698 (params (plist-get dest :params)))
4699 (unless (fboundp transform)
4700 (user-error "No such transformation function %s" transform))
4701 (orgtbl-send-replace-tbl name (funcall transform table params)))
4703 (message "Table converted and installed at %d receiver location%s"
4704 ntbl (if (> ntbl 1) "s" ""))
4705 (and (> ntbl 0) ntbl))))
4707 (defun org-remove-by-index (list indices &optional i0)
4708 "Remove the elements in LIST with indices in INDICES.
4709 First element has index 0, or I0 if given."
4712 (if (integerp indices) (setq indices (list indices)))
4713 (setq i0 (1- (or i0 0)))
4714 (delq :rm (mapcar (lambda (x)
4716 (if (memq i0 indices) :rm x))
4719 (defun orgtbl-toggle-comment ()
4720 "Comment or uncomment the orgtbl at point."
4722 (let* ((case-fold-search t)
4723 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4724 (re2 (concat "^" orgtbl-line-start-regexp))
4725 (commented (save-excursion (beginning-of-line 1)
4726 (cond ((looking-at re1) t)
4727 ((looking-at re2) nil)
4728 (t (user-error "Not at an org table")))))
4729 (re (if commented re1 re2))
4732 (beginning-of-line 1)
4733 (while (looking-at re) (beginning-of-line 0))
4734 (beginning-of-line 2)
4736 (while (looking-at re) (beginning-of-line 2))
4738 (comment-region beg end (if commented '(4) nil))))
4740 (defun orgtbl-insert-radio-table ()
4741 "Insert a radio table template appropriate for this major mode."
4743 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
4746 (unless e (user-error "No radio table setup defined for %s" major-mode))
4747 (setq name (read-string "Table name: "))
4748 (while (string-match "%n" txt)
4749 (setq txt (replace-match name t t txt)))
4750 (or (bolp) (insert "\n"))
4756 (defun orgtbl-to-generic (table params)
4757 "Convert the orgtbl-mode TABLE to some other format.
4759 This generic routine can be used for many standard cases.
4761 TABLE is a list, each entry either the symbol `hline' for
4762 a horizontal separator line, or a list of fields for that
4763 line. PARAMS is a property list of parameters that can
4764 influence the conversion.
4766 Valid parameters are:
4770 Export back-end used as a basis to transcode elements of the
4771 table, when no specific parameter applies to it. It is also
4772 used to translate cells contents. You can prevent this by
4773 setting :raw property to a non-nil value.
4777 When non-nil, only convert rows, not the table itself. This is
4778 equivalent to setting to the empty string both :tstart
4779 and :tend, which see.
4783 When set to an integer N, skip the first N lines of the table.
4784 Horizontal separation lines do count for this parameter!
4788 List of columns that should be skipped. If the table has
4789 a column with calculation marks, that column is automatically
4790 discarded beforehand.
4794 String to be inserted on horizontal separation lines. May be
4795 nil to ignore these lines altogether.
4799 Separator between two fields, as a string.
4801 Each in the following group may be either a string or a function
4802 of no arguments returning a string:
4806 Strings to start and end the table. Ignored when :splice is t.
4810 Strings to start and end a new table line.
4814 Strings to start and end the last table line. Default,
4815 respectively, to :lstart and :lend.
4817 Each in the following group may be a string or a function of one
4818 argument (either the cells in the current row, as a list of
4819 strings, or the current cell) returning a string:
4823 Format string for an entire row, with enough %s to capture all
4824 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4828 Format for the entire last line, defaults to :lfmt.
4832 A format to be used to wrap the field, should contain %s for
4833 the original field value. For example, to wrap everything in
4834 dollars, you could use :fmt \"$%s$\". This may also be
4835 a property list with column numbers and format strings, or
4838 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4840 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4842 Same as above, specific for the header lines in the table.
4843 All lines before the first hline are treated as header. If
4844 any of these is not present, the data line value is used.
4846 This may be either a string or a function of two arguments:
4850 Use this format to print numbers with exponential. The format
4851 should have %s twice for inserting mantissa and exponent, for
4852 example \"%s\\\\times10^{%s}\". This may also be a property
4853 list with column numbers and format strings or functions.
4854 :fmt will still be applied after :efmt."
4855 ;; Make sure `org-export-create-backend' is available.
4857 (let* ((backend (plist-get params :backend))
4859 ;; Build a custom back-end according to PARAMS. Before
4860 ;; defining a translator, check if there is anything to do.
4861 ;; When there isn't, let BACKEND handle the element.
4862 (org-export-create-backend
4863 :parent (or backend 'org)
4865 `((table . ,(org-table--to-generic-table params))
4866 (table-row . ,(org-table--to-generic-row params))
4867 (table-cell . ,(org-table--to-generic-cell params))
4868 ;; Macros are not going to be expanded. However, no
4869 ;; regular back-end has a transcoder for them. We
4870 ;; provide one so they are not ignored, but displayed
4872 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4874 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4875 ;; Initialize communication channel in INFO.
4877 (let ((org-inhibit-startup t)) (org-mode))
4878 (let ((standard-output (current-buffer))
4879 (org-element-use-cache nil))
4881 (cond ((eq e 'hline) (princ "|--\n"))
4883 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4885 ;; Add back-end specific filters, but not user-defined ones. In
4886 ;; particular, make sure to call parse-tree filters on the
4889 (let ((org-export-filters-alist nil))
4890 (org-export-install-filters
4892 (org-export-get-environment backend nil params)
4893 `(:back-end ,(org-export-get-backend backend))))))
4895 (org-export-filter-apply-functions
4896 (plist-get info :filter-parse-tree)
4897 (org-element-map (org-element-parse-buffer) 'table
4900 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4901 (user-error "Unknown :backend value"))
4902 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4903 ;; Handle :skip parameter.
4904 (let ((skip (plist-get info :skip)))
4906 (unless (wholenump skip) (user-error "Wrong :skip value"))
4908 (org-element-map data 'table-row
4911 (org-element-extract-element row)
4915 ;; Handle :skipcols parameter.
4916 (let ((skipcols (plist-get info :skipcols)))
4918 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4919 (org-element-map data 'table
4921 (let ((specialp (org-export-table-has-special-column-p table)))
4922 (dolist (row (org-element-contents table))
4923 (when (eq (org-element-property :type row) 'standard)
4925 (dolist (cell (nthcdr (if specialp 1 0)
4926 (org-element-contents row)))
4927 (when (memq c skipcols)
4928 (org-element-extract-element cell))
4929 (cl-incf c))))))))))
4930 ;; Since we are going to export using a low-level mechanism,
4931 ;; ignore special column and special rows manually.
4932 (let ((special? (org-export-table-has-special-column-p data))
4934 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4936 (when (if (eq (org-element-type datum) 'table-row)
4937 (org-export-table-row-is-special-p datum nil)
4938 (org-export-first-sibling-p datum nil))
4939 (push datum ignore))))
4940 (setq info (plist-put info :ignore-list ignore)))
4941 ;; We use a low-level mechanism to export DATA so as to skip all
4942 ;; usual pre-processing and post-processing, i.e., hooks, Babel
4943 ;; code evaluation, include keywords and macro expansion. Only
4944 ;; back-end specific filters are retained.
4945 (let ((output (org-export-data-with-backend data custom-backend info)))
4946 ;; Remove final newline.
4947 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4949 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4950 (cond ((null value) nil)
4951 ((functionp value) `(funcall ',value ,@args))
4953 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4954 (args `(format ,value ,@args))
4956 ((and with-cons (consp value))
4957 `(let ((val (cadr (memq column ',value))))
4958 (cond ((null val) contents)
4959 ((stringp val) (format val ,@args))
4960 ((functionp val) (funcall val ,@args))
4961 (t (user-error "Wrong %s value" ,name)))))
4962 (t (user-error "Wrong %s value" name))))
4964 (defun org-table--to-generic-table (params)
4965 "Return custom table transcoder according to PARAMS.
4966 PARAMS is a plist. See `orgtbl-to-generic' for more
4968 (let ((backend (plist-get params :backend))
4969 (splice (plist-get params :splice))
4970 (tstart (plist-get params :tstart))
4971 (tend (plist-get params :tend)))
4972 `(lambda (table contents info)
4974 ,(and tstart (not splice)
4975 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4976 ,(if (or (not backend) tstart tend splice) 'contents
4977 `(org-export-with-backend ',backend table contents info))
4978 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4980 (defun org-table--to-generic-row (params)
4981 "Return custom table row transcoder according to PARAMS.
4982 PARAMS is a plist. See `orgtbl-to-generic' for more
4984 (let* ((backend (plist-get params :backend))
4985 (lstart (plist-get params :lstart))
4986 (llstart (plist-get params :llstart))
4987 (hlstart (plist-get params :hlstart))
4988 (hllstart (plist-get params :hllstart))
4989 (lend (plist-get params :lend))
4990 (llend (plist-get params :llend))
4991 (hlend (plist-get params :hlend))
4992 (hllend (plist-get params :hllend))
4993 (lfmt (plist-get params :lfmt))
4994 (llfmt (plist-get params :llfmt))
4995 (hlfmt (plist-get params :hlfmt))
4996 (hllfmt (plist-get params :hllfmt)))
4997 `(lambda (row contents info)
4998 (if (eq (org-element-property :type row) 'rule)
5000 ((plist-member params :hline)
5001 (org-table--generic-apply (plist-get params :hline) ":hline"))
5002 (backend `(org-export-with-backend ',backend row nil info)))
5003 (let ((headerp ,(and (or hlfmt hlstart hlend)
5004 '(org-export-table-row-in-header-p row info)))
5006 ,(and (or hllfmt hllstart hllend)
5007 '(org-export-table-row-ends-header-p row info)))
5008 (lastp (not (org-export-get-next-element row info))))
5010 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5011 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5012 ;; `:lstart', `:lend' and their relatives.
5014 '(org-element-map row 'table-cell
5016 ;; Export all cells, without separators.
5018 ;; Use `org-export-data-with-backend'
5019 ;; instead of `org-export-data' to eschew
5020 ;; cached values, which
5021 ;; ignore :orgtbl-ignore-sep parameter.
5022 (org-export-data-with-backend
5024 (plist-get info :back-end)
5025 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5029 `(last-header-p ,(org-table--generic-apply
5030 hllfmt ":hllfmt" nil cells)))
5032 `(headerp ,(org-table--generic-apply
5033 hlfmt ":hlfmt" nil cells)))
5035 `(lastp ,(org-table--generic-apply
5036 llfmt ":llfmt" nil cells)))
5038 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5042 (or hllstart hllend)
5045 ,(org-table--generic-apply hllstart ":hllstart")
5047 ,(org-table--generic-apply hllend ":hllend"))))
5052 ,(org-table--generic-apply hlstart ":hlstart")
5054 ,(org-table--generic-apply hlend ":hlend"))))
5059 ,(org-table--generic-apply llstart ":llstart")
5061 ,(org-table--generic-apply llend ":llend"))))
5066 ,(org-table--generic-apply lstart ":lstart")
5068 ,(org-table--generic-apply lend ":lend")))
5070 `(org-export-with-backend
5071 ',backend row contents info))
5072 (t 'contents)))))))))))))))
5074 (defun org-table--to-generic-cell (params)
5075 "Return custom table cell transcoder according to PARAMS.
5076 PARAMS is a plist. See `orgtbl-to-generic' for more
5078 (let* ((backend (plist-get params :backend))
5079 (efmt (plist-get params :efmt))
5080 (fmt (plist-get params :fmt))
5081 (hfmt (plist-get params :hfmt))
5082 (sep (plist-get params :sep))
5083 (hsep (plist-get params :hsep)))
5084 `(lambda (cell contents info)
5085 ;; Make sure that contents are exported as Org data when :raw
5086 ;; parameter is non-nil.
5087 ,(when (and backend (plist-get params :raw))
5089 ;; Since we don't know what are the pseudo object
5090 ;; types defined in backend, we cannot pass them to
5091 ;; `org-element-interpret-data'. As a consequence,
5092 ;; they will be treated as pseudo elements, and will
5093 ;; have newlines appended instead of spaces.
5094 ;; Therefore, we must make sure :post-blank value is
5095 ;; really turned into spaces.
5096 (replace-regexp-in-string
5099 (org-element-interpret-data
5100 (org-element-contents cell))))))
5102 (let ((headerp ,(and (or hfmt hsep)
5103 '(org-export-table-row-in-header-p
5104 (org-export-get-parent-element cell) info)))
5106 ;; Call costly `org-export-table-cell-address' only if
5107 ;; absolutely necessary, i.e., if one
5108 ;; of :fmt :efmt :hmft has a "plist type" value.
5109 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5110 (list efmt hfmt fmt))
5111 '(1+ (cdr (org-export-table-cell-address cell info))))))
5113 ;; Check if we can apply `:efmt' on CONTENTS.
5115 `(when (string-match orgtbl-exp-regexp contents)
5116 (let ((mantissa (match-string 1 contents))
5117 (exponent (match-string 2 contents)))
5118 (setq contents ,(org-table--generic-apply
5119 efmt ":efmt" t 'mantissa 'exponent)))))
5120 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5122 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5123 hfmt ":hfmt" t 'contents))))
5124 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5125 fmt ":fmt" t 'contents))))))
5126 ;; If a separator is provided, use it instead of BACKEND's.
5127 ;; Separators are ignored when LFMT (or equivalent) is
5131 `(if (or ,(and (not sep) '(not headerp))
5132 (plist-get info :orgtbl-ignore-sep)
5133 (not (org-export-get-next-element cell info)))
5134 ,(if (not backend) 'contents
5135 `(org-export-with-backend ',backend cell contents info))
5137 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5139 (backend `(org-export-with-backend ',backend cell contents info))
5143 (defun orgtbl-to-tsv (table params)
5144 "Convert the orgtbl-mode table to TAB separated material."
5145 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5148 (defun orgtbl-to-csv (table params)
5149 "Convert the orgtbl-mode table to CSV material.
5150 This does take care of the proper quoting of fields with comma or quotes."
5151 (orgtbl-to-generic table
5152 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5156 (defun orgtbl-to-latex (table params)
5157 "Convert the orgtbl-mode TABLE to LaTeX.
5159 TABLE is a list, each entry either the symbol `hline' for
5160 a horizontal separator line, or a list of fields for that line.
5161 PARAMS is a property list of parameters that can influence the
5162 conversion. All parameters from `orgtbl-to-generic' are
5163 supported. It is also possible to use the following ones:
5167 When non-nil, use formal \"booktabs\" style.
5171 Specify environment to use, as a string. If you use
5172 \"longtable\", you may also want to specify :language property,
5173 as a string, to get proper continuation strings."
5178 ;; Provide sane default values.
5179 (list :backend 'latex
5180 :latex-default-table-mode 'table
5181 :latex-tables-centered nil
5182 :latex-tables-booktabs (plist-get params :booktabs)
5183 :latex-table-scientific-notation nil
5184 :latex-default-table-environment
5185 (or (plist-get params :environment) "tabular"))
5189 (defun orgtbl-to-html (table params)
5190 "Convert the orgtbl-mode TABLE to HTML.
5192 TABLE is a list, each entry either the symbol `hline' for
5193 a horizontal separator line, or a list of fields for that line.
5194 PARAMS is a property list of parameters that can influence the
5195 conversion. All parameters from `orgtbl-to-generic' are
5196 supported. It is also possible to use the following one:
5200 Attributes and values, as a plist, which will be used in
5206 ;; Provide sane default values.
5207 (list :backend 'html
5208 :html-table-data-tags '("<td%s>" . "</td>")
5209 :html-table-use-header-tags-for-first-column nil
5210 :html-table-align-individual-fields t
5211 :html-table-row-tags '("<tr>" . "</tr>")
5212 :html-table-attributes
5213 (if (plist-member params :attributes)
5214 (plist-get params :attributes)
5215 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5220 (defun orgtbl-to-texinfo (table params)
5221 "Convert the orgtbl-mode TABLE to Texinfo.
5223 TABLE is a list, each entry either the symbol `hline' for
5224 a horizontal separator line, or a list of fields for that line.
5225 PARAMS is a property list of parameters that can influence the
5226 conversion. All parameters from `orgtbl-to-generic' are
5227 supported. It is also possible to use the following one:
5231 Column widths, as a string. When providing column fractions,
5232 \"@columnfractions\" command can be omitted."
5233 (require 'ox-texinfo)
5238 (list :backend 'texinfo
5239 :texinfo-tables-verbatim nil
5240 :texinfo-table-scientific-notation nil)
5242 (columns (let ((w (plist-get params :columns)))
5244 ((string-match-p "{\\|@columnfractions " w) w)
5245 (t (concat "@columnfractions " w))))))
5246 (if (not columns) output
5247 (replace-regexp-in-string
5248 "@multitable \\(.*\\)" columns output t nil 1))))
5251 (defun orgtbl-to-orgtbl (table params)
5252 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5254 TABLE is a list, each entry either the symbol `hline' for
5255 a horizontal separator line, or a list of fields for that line.
5256 PARAMS is a property list of parameters that can influence the
5257 conversion. All parameters from `orgtbl-to-generic' are
5260 Useful when slicing one table into many. The :hline, :sep,
5261 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5262 be set to provide ORGTBL directives for the generated table."
5264 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5266 (defun orgtbl-to-table.el (table params)
5267 "Convert the orgtbl-mode TABLE into a table.el table.
5268 TABLE is a list, each entry either the symbol `hline' for
5269 a horizontal separator line, or a list of fields for that line.
5270 PARAMS is a property list of parameters that can influence the
5271 conversion. All parameters from `orgtbl-to-generic' are
5274 (insert (orgtbl-to-orgtbl table params))
5276 (replace-regexp-in-string
5278 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5280 (defun orgtbl-to-unicode (table params)
5281 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5283 TABLE is a list, each entry either the symbol `hline' for
5284 a horizontal separator line, or a list of fields for that line.
5285 PARAMS is a property list of parameters that can influence the
5286 conversion. All parameters from `orgtbl-to-generic' are
5287 supported. It is also possible to use the following ones:
5291 When non-nil, use \"ascii-art-to-unicode\" package to translate
5292 the table. You can download it here:
5293 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5297 When non-nil, narrow columns width than provided width cookie,
5298 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5303 (list :backend 'ascii
5304 :ascii-charset 'utf-8
5305 :ascii-table-widen-columns (not (plist-get params :narrow))
5306 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5309 ;; Put the cursor in a column containing numerical values
5312 ;; A new column is added with a bar plot.
5313 ;; When the table is refreshed (C-u C-c *),
5314 ;; the plot is updated to reflect the new values.
5316 (defun orgtbl-ascii-draw (value min max &optional width characters)
5317 "Draw an ascii bar in a table.
5318 VALUE is the value to plot, it determines the width of the bar to draw.
5319 MIN is the value that will be displayed as empty (zero width bar).
5320 MAX is the value that will draw a bar filling all the WIDTH.
5321 WIDTH is the span in characters from MIN to MAX.
5322 CHARACTERS is a string that will compose the bar, with shades of grey
5323 from pure white to pure black. It defaults to a 10 characters string
5324 of regular ascii characters."
5325 (let* ((width (ceiling (or width 12)))
5326 (characters (or characters " .:;c!lhVHW"))
5327 (len (1- (length characters)))
5328 (value (float (if (numberp value)
5329 value (string-to-number value))))
5330 (relative (/ (- value min) (- max min)))
5331 (steps (round (* relative width len))))
5332 (cond ((< steps 0) "too small")
5333 ((> steps (* width len)) "too large")
5334 (t (let* ((int-division (/ steps len))
5335 (remainder (- steps (* int-division len))))
5336 (concat (make-string int-division (elt characters len))
5337 (string (elt characters remainder))))))))
5340 (defun orgtbl-ascii-plot (&optional ask)
5341 "Draw an ASCII bar plot in a column.
5343 With cursor in a column containing numerical values, this function
5344 will draw a plot in a new column.
5346 ASK, if given, is a numeric prefix to override the default 12
5347 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5349 which will prompt for the width."
5351 (let ((col (org-table-current-column))
5352 (min 1e999) ; 1e999 will be converted to infinity
5353 (max -1e999) ; which is the desired result
5354 (table (org-table-to-lisp))
5357 (read-number "Length of column " 12))
5360 ;; Skip any hline a the top of table.
5361 (while (eq (car table) 'hline) (setq table (cdr table)))
5362 ;; Skip table header if any.
5363 (dolist (x (or (cdr (memq 'hline table)) table))
5365 (setq x (nth (1- col) x))
5367 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5369 (setq x (string-to-number x))
5370 (when (> min x) (setq min x))
5371 (when (< max x) (setq max x)))))
5372 (org-table-insert-column)
5373 (org-table-move-column-right)
5374 (org-table-store-formulas
5377 (concat "$" (number-to-string (1+ col)))
5378 (format "'(%s $%s %s %s %s)"
5379 "orgtbl-ascii-draw" col min max length))
5380 (org-table-get-stored-formulas)))
5381 (org-table-recalculate t)))
5383 ;; Example of extension: unicode characters
5384 ;; Here are two examples of different styles.
5386 ;; Unicode block characters are used to give a smooth effect.
5387 ;; See http://en.wikipedia.org/wiki/Block_Elements
5388 ;; Use one of those drawing functions
5389 ;; - orgtbl-ascii-draw (the default ascii)
5390 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5391 ;; - orgtbl-uc-draw-cont (smooth unicode)
5393 ;; This is best viewed with the "DejaVu Sans Mono" font
5394 ;; (use M-x set-default-font).
5396 (defun orgtbl-uc-draw-grid (value min max &optional width)
5397 "Draw a bar in a table using block unicode characters.
5398 It is a variant of orgtbl-ascii-draw with Unicode block
5399 characters, for a smooth display. Bars appear as grids (to the
5400 extent the font allows)."
5401 ;; http://en.wikipedia.org/wiki/Block_Elements
5402 ;; best viewed with the "DejaVu Sans Mono" font.
5403 (orgtbl-ascii-draw value min max width
5404 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5406 (defun orgtbl-uc-draw-cont (value min max &optional width)
5407 "Draw a bar in a table using block unicode characters.
5408 It is a variant of orgtbl-ascii-draw with Unicode block
5409 characters, for a smooth display. Bars are solid (to the extent
5411 (orgtbl-ascii-draw value min max width
5412 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5414 (defun org-table-get-remote-range (name-or-id form)
5415 "Get a field value or a list of values in a range from table at ID.
5417 NAME-OR-ID may be the name of a table in the current file as set
5418 by a \"#+NAME:\" directive. The first table following this line
5419 will then be used. Alternatively, it may be an ID referring to
5420 any entry, also in a different file. In this case, the first
5421 table in that entry will be referenced.
5422 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5423 \"@I$2..@II$2\". All the references must be absolute, not relative.
5425 The return value is either a single string for a single field, or a
5426 list of the fields in the rectangle."
5428 (let ((case-fold-search t) (id-loc nil)
5429 ;; Protect a bunch of variables from being overwritten by
5430 ;; the context of the remote table.
5431 org-table-column-names org-table-column-name-regexp
5432 org-table-local-parameters org-table-named-field-locations
5433 org-table-current-line-types
5434 org-table-current-begin-pos org-table-dlines
5435 org-table-current-ncol
5436 org-table-hlines org-table-last-alignment
5437 org-table-last-column-widths org-table-last-alignment
5438 org-table-last-column-widths
5440 (setq form (org-table-convert-refs-to-rc form))
5441 (org-with-wide-buffer
5442 (goto-char (point-min))
5443 (if (re-search-forward
5444 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5445 (regexp-quote name-or-id) "[ \t]*$")
5447 (setq buffer (current-buffer) loc (match-beginning 0))
5448 (setq id-loc (org-id-find name-or-id 'marker))
5449 (unless (and id-loc (markerp id-loc))
5450 (user-error "Can't find remote table \"%s\"" name-or-id))
5451 (setq buffer (marker-buffer id-loc)
5452 loc (marker-position id-loc))
5453 (move-marker id-loc nil))
5454 (with-current-buffer buffer
5455 (org-with-wide-buffer
5458 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5459 (not (match-beginning 1)))
5460 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5462 (setq form (org-table-formula-substitute-names
5463 (org-table-formula-handle-first/last-rc form)))
5464 (if (and (string-match org-table-range-regexp form)
5465 (> (length (match-string 0 form)) 1))
5466 (org-table-get-range
5467 (match-string 0 form) org-table-current-begin-pos 1)
5470 (defun org-table-remote-reference-indirection (form)
5471 "Return formula with table remote references substituted by indirection.
5472 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5473 This indirection works only with the format @ROW$COLUMN. The
5474 format \"B3\" is not supported because it can not be
5475 distinguished from a plain table name or ID."
5477 ;; Same as in `org-table-eval-formula'.
5478 (concat "\\<remote([ \t]*\\("
5479 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5481 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5482 (replace-regexp-in-string
5486 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5487 (org-table-get-range
5488 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5493 (defmacro org-define-lookup-function (mode)
5494 (let ((mode-str (symbol-name mode))
5495 (first-p (eq mode 'first))
5496 (all-p (eq mode 'all)))
5497 (let ((plural-str (if all-p "s" "")))
5498 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5499 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5500 If R-LIST is nil, return matching element%s of S-LIST.
5501 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5502 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5503 This function is generated by a call to the macro `org-define-lookup-function'."
5504 mode-str plural-str plural-str plural-str)
5505 (let ,(let ((lvars '((p (or predicate 'equal))
5507 (rl (or r-list s-list))
5509 (if first-p (cons '(match-p nil) lvars) lvars))
5510 (while ,(if first-p '(and (not match-p) sl) 'sl)
5511 (when (funcall p val (car sl))
5512 ,(when first-p '(setq match-p t))
5513 (let ((rval (car rl)))
5514 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5515 (setq sl (cdr sl) rl (cdr rl)))
5518 (org-define-lookup-function first)
5519 (org-define-lookup-function last)
5520 (org-define-lookup-function all)
5522 (provide 'org-table)
5525 ;; generated-autoload-file: "org-loaddefs.el"
5528 ;;; org-table.el ends here