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 <https://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 t
85 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
87 In the optimized version, the table editor takes over all simple keys that
88 normally just insert a character. In tables, the characters are inserted
89 in a way to minimize disturbing the table structure (i.e. in overwrite mode
90 for empty fields). Outside tables, the correct binding of the keys is
93 Changing this variable requires a restart of Emacs to become
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 :group
'org-table-editing
215 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
216 "Non-nil means automatically exit the follow mode.
217 When nil, the follow mode will stay on and be active in any table
218 the cursor enters. Since the table follow filed mode messes with the
219 window configuration, it is not recommended to set this variable to nil,
220 except maybe locally in a special file that has mostly tables with long
226 (defcustom org-table-fix-formulas-confirm nil
227 "Whether the user should confirm when Org fixes formulas."
228 :group
'org-table-editing
231 (const :tag
"with yes-or-no" yes-or-no-p
)
232 (const :tag
"with y-or-n" y-or-n-p
)
233 (const :tag
"no confirmation" nil
)))
234 (put 'org-table-fix-formulas-confirm
236 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
238 (defcustom org-table-tab-jumps-over-hlines t
239 "Non-nil means tab in the last column of a table with jump over a hline.
240 If a horizontal separator line is following the current line,
241 `org-table-next-field' can either create a new row before that line, or jump
242 over the line. When this option is nil, a new line will be created before
244 :group
'org-table-editing
247 (defgroup org-table-calculation nil
248 "Options concerning tables in Org mode."
249 :tag
"Org Table Calculation"
252 (defcustom org-table-use-standard-references
'from
253 "Non-nil means using table references like B3 instead of @3$2.
256 from accept as input, do not present for editing
257 t accept as input and present for editing"
258 :group
'org-table-calculation
260 (const :tag
"Never, don't even check user input for them" nil
)
261 (const :tag
"Always, both as user input, and when editing" t
)
262 (const :tag
"Convert user input, don't offer during editing" from
)))
264 (defcustom org-table-copy-increment t
265 "Non-nil means increment when copying current field with \
266 `\\[org-table-copy-down]'."
267 :group
'org-table-calculation
269 :package-version
'(Org .
"8.3")
271 (const :tag
"Use the difference between the current and the above fields" t
)
272 (integer :tag
"Use a number" 1)
273 (const :tag
"Don't increment the value when copying a field" nil
)))
275 (defcustom org-calc-default-modes
276 '(calc-internal-prec 12
277 calc-float-format
(float 8)
280 calc-symbolic-mode nil
281 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
282 calc-display-working-message t
284 "List with Calc mode settings for use in `calc-eval' for table formulas.
285 The list must contain alternating symbols (Calc modes variables and values).
286 Don't remove any of the default settings, just change the values. Org mode
287 relies on the variables to be present in the list."
288 :group
'org-table-calculation
291 (defcustom org-table-duration-custom-format
'hours
292 "Format for the output of calc computations like $1+$2;t.
293 The default value is `hours', and will output the results as a
294 number of hours. Other allowed values are `seconds', `minutes' and
295 `days', and the output will be a fraction of seconds, minutes or
296 days. `hh:mm' selects to use hours and minutes, ignoring seconds.
297 The `U' flag in a table formula will select this specific format for
299 :group
'org-table-calculation
301 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
302 (symbol :tag
"Minutes" 'minutes
)
303 (symbol :tag
"Hours " 'hours
)
304 (symbol :tag
"Days " 'days
)
305 (symbol :tag
"HH:MM " 'hh
:mm
)))
307 (defcustom org-table-duration-hour-zero-padding t
308 "Non-nil means hours in table duration computations should be zero-padded.
309 So this is about 08:32:34 versus 8:33:34."
310 :group
'org-table-calculation
312 :package-version
'(Org .
"9.1")
316 (defcustom org-table-formula-field-format
"%s"
317 "Format for fields which contain the result of a formula.
318 For example, using \"~%s~\" will display the result within tilde
319 characters. Beware that modifying the display can prevent the
320 field from being used in another formula."
321 :group
'org-table-settings
325 (defcustom org-table-formula-evaluate-inline t
326 "Non-nil means TAB and RET evaluate a formula in current table field.
327 If the current field starts with an equal sign, it is assumed to be a formula
328 which should be evaluated as described in the manual and in the documentation
329 string of the command `org-table-eval-formula'. This feature requires the
331 When this variable is nil, formula calculation is only available through
332 the command `\\[org-table-eval-formula]'."
333 :group
'org-table-calculation
336 (defcustom org-table-formula-use-constants t
337 "Non-nil means interpret constants in formulas in tables.
338 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
339 by the value given in `org-table-formula-constants', or by a value obtained
340 from the `constants.el' package."
341 :group
'org-table-calculation
344 (defcustom org-table-formula-constants nil
345 "Alist with constant names and values, for use in table formulas.
346 The car of each element is a name of a constant, without the `$' before it.
347 The cdr is the value as a string. For example, if you'd like to use the
348 speed of light in a formula, you would configure
350 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
352 and then use it in an equation like `$1*$c'.
354 Constants can also be defined on a per-file basis using a line like
356 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
357 :group
'org-table-calculation
359 (cons (string :tag
"name")
360 (string :tag
"value"))))
362 (defcustom org-table-allow-automatic-line-recalculation t
363 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
365 Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
366 are pressed in the line."
367 :group
'org-table-calculation
370 (defcustom org-table-relative-ref-may-cross-hline t
371 "Non-nil means relative formula references may cross hlines.
372 Here are the allowed values:
374 nil Relative references may not cross hlines. They will reference the
375 field next to the hline instead. Coming from below, the reference
376 will be to the field below the hline. Coming from above, it will be
378 t Relative references may cross hlines.
379 error An attempt to cross a hline will throw an error.
381 It is probably good to never set this variable to nil, for the sake of
382 portability of tables."
383 :group
'org-table-calculation
385 (const :tag
"Allow to cross" t
)
386 (const :tag
"Stick to hline" nil
)
387 (const :tag
"Error on attempt to cross" error
)))
389 (defcustom org-table-formula-create-columns nil
390 "Non-nil means that evaluation of a field formula can add new
391 columns if an out-of-bounds field is being set."
392 :group
'org-table-calculation
394 :package-version
'(Org .
"8.3")
396 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
397 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
398 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
399 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
401 (defgroup org-table-import-export nil
402 "Options concerning table import and export in Org mode."
403 :tag
"Org Table Import Export"
406 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
407 "Default export parameters for `org-table-export'.
408 These can be overridden for a specific table by setting the
409 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
410 radio tables for the different export transformations and
411 available parameters."
412 :group
'org-table-import-export
415 (defcustom org-table-convert-region-max-lines
999
416 "Max lines that `org-table-convert-region' will attempt to process.
418 The function can be slow on larger regions; this safety feature
419 prevents it from hanging emacs."
420 :group
'org-table-import-export
423 :package-version
'(Org .
"8.3"))
425 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
426 "Regexp matching a line marked for automatic recalculation.")
428 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
429 "Regexp matching a line marked for recalculation.")
431 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
432 "Regexp matching a line marked for calculation.")
434 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
435 "Regexp matching any line outside an Org table.")
437 (defvar org-table-last-highlighted-reference nil
)
439 (defvar org-table-formula-history nil
)
441 (defvar org-table-column-names nil
442 "Alist with column names, derived from the `!' line.
443 This variable is initialized with `org-table-analyze'.")
445 (defvar org-table-column-name-regexp nil
446 "Regular expression matching the current column names.
447 This variable is initialized with `org-table-analyze'.")
449 (defvar org-table-local-parameters nil
450 "Alist with parameter names, derived from the `$' line.
451 This variable is initialized with `org-table-analyze'.")
453 (defvar org-table-named-field-locations nil
454 "Alist with locations of named fields.
455 Associations follow the pattern (NAME LINE COLUMN) where
456 NAME is the name of the field as a string,
457 LINE is the number of lines from the beginning of the table,
458 COLUMN is the column of the field, as an integer.
459 This variable is initialized with `org-table-analyze'.")
461 (defvar org-table-current-line-types nil
462 "Table row types in current table.
463 This variable is initialized with `org-table-analyze'.")
465 (defvar org-table-current-begin-pos nil
466 "Current table begin position, as a marker.
467 This variable is initialized with `org-table-analyze'.")
469 (defvar org-table-current-ncol nil
470 "Number of columns in current table.
471 This variable is initialized with `org-table-analyze'.")
473 (defvar org-table-dlines nil
474 "Vector of data line line numbers in the current table.
475 Line numbers are counted from the beginning of the table. This
476 variable is initialized with `org-table-analyze'.")
478 (defvar org-table-hlines nil
479 "Vector of hline line numbers in the current table.
480 Line numbers are counted from the beginning of the table. This
481 variable is initialized with `org-table-analyze'.")
483 (defconst org-table-range-regexp
484 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
486 "Regular expression for matching ranges in formulas.")
488 (defconst org-table-range-regexp2
490 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
492 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
493 "Match a range for reference display.")
495 (defconst org-table-translate-regexp
496 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
497 "Match a reference that needs translation, for reference display.")
499 (defmacro org-table-save-field
(&rest body
)
500 "Save current field; execute BODY; restore field.
501 Field is restored even in case of abnormal exit."
502 (declare (debug (body)))
503 (org-with-gensyms (line column
)
504 `(let ((,line
(copy-marker (line-beginning-position)))
505 (,column
(org-table-current-column)))
509 (org-table-goto-column ,column
)
510 (set-marker ,line nil
)))))
513 (defun org-table-create-with-table.el
()
514 "Use the table.el package to insert a new table.
515 If there is already a table at point, convert between Org tables
516 and table.el tables."
521 (if (y-or-n-p "Convert table to Org table? ")
522 (org-table-convert)))
524 (when (y-or-n-p "Convert table to table.el table? ")
526 (org-table-convert)))
527 (t (call-interactively 'table-insert
))))
530 (defun org-table-create-or-convert-from-region (arg)
531 "Convert region to table, or create an empty table.
532 If there is an active region, convert it to a table, using the function
533 `org-table-convert-region'. See the documentation of that function
534 to learn how the prefix argument is interpreted to determine the field
536 If there is no such region, create an empty table with `org-table-create'."
538 (if (org-region-active-p)
539 (org-table-convert-region (region-beginning) (region-end) arg
)
540 (org-table-create arg
)))
543 (defun org-table-create (&optional size
)
544 "Query for a size and insert a table skeleton.
545 SIZE is a string Columns x Rows like for example \"3x2\"."
548 (setq size
(read-string
549 (concat "Table size Columns x Rows [e.g. "
550 org-table-default-size
"]: ")
551 "" nil org-table-default-size
)))
554 (indent (make-string (current-column) ?\
))
555 (split (org-split-string size
" *x *"))
556 (rows (string-to-number (nth 1 split
)))
557 (columns (string-to-number (car split
)))
558 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
560 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
561 (point-at-bol) (point)))
562 (beginning-of-line 1)
564 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
565 (dotimes (_ rows
) (insert line
))
568 ;; Insert a hline after the first row.
576 (defun org-table-convert-region (beg0 end0
&optional separator
)
577 "Convert region to a table.
579 The region goes from BEG0 to END0, but these borders will be moved
580 slightly, to make sure a beginning of line in the first line is included.
582 SEPARATOR specifies the field separator in the lines. It can have the
585 (4) Use the comma as a field separator
586 (16) Use a TAB as field separator
587 (64) Prompt for a regular expression as field separator
588 integer When a number, use that many spaces, or a TAB, as field separator
589 regexp When a regular expression, use it to match the separator
590 nil When nil, the command tries to be smart and figure out the
591 separator in the following way:
592 - when each line contains a TAB, assume TAB-separated material
593 - when each line contains a comma, assume CSV material
594 - else, assume one or more SPACE characters as separator."
596 (let* ((beg (min beg0 end0
))
597 (end (max beg0 end0
))
599 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
600 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
601 org-table-convert-region-max-lines
)
602 (if (equal separator
'(64))
603 (setq separator
(read-regexp "Regexp for field separator")))
605 (beginning-of-line 1)
606 (setq beg
(point-marker))
608 (if (bolp) (backward-char 1) (end-of-line 1))
609 (setq end
(point-marker))
610 ;; Get the right field separator
615 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
616 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
619 (if (equal separator
'(4))
620 (while (< (point) end
)
621 ;; parse the csv stuff
623 ((looking-at "^") (insert "| "))
624 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
625 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
626 (replace-match "\\1")
627 (if (looking-at "\"") (insert "\"")))
628 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
629 ((looking-at "[ \t]*,") (replace-match " | "))
630 (t (beginning-of-line 2))))
632 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
633 ((equal separator
'(16)) "^\\|\t")
634 ((integerp separator
)
636 (user-error "Number of spaces in separator must be >= 1")
637 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
639 (format "^ *\\|%s" separator
))
640 (t (error "This should not happen"))))
641 (while (re-search-forward re end t
)
642 (replace-match "| " t t
)))
647 (defun org-table-import (file arg
)
648 "Import FILE as a table.
649 The file is assumed to be tab-separated. Such files can be produced by most
650 spreadsheet and database applications. If no tabs (at least one per line)
651 are found, lines will be split on whitespace into fields."
653 (or (bolp) (newline))
656 (insert-file-contents file
)
657 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
661 (defun org-table-export (&optional file format
)
662 "Export table to a file, with configurable format.
663 Such a file can be imported into usual spreadsheet programs.
665 FILE can be the output file name. If not given, it will be taken
666 from a TABLE_EXPORT_FILE property in the current entry or higher
667 up in the hierarchy, or the user will be prompted for a file
668 name. FORMAT can be an export format, of the same kind as it
669 used when `orgtbl-mode' sends a table in a different format.
671 The command suggests a format depending on TABLE_EXPORT_FORMAT,
672 whether it is set locally or up in the hierarchy, then on the
673 extension of the given file name, and finally on the variable
674 `org-table-export-default-format'."
676 (unless (org-at-table-p) (user-error "No table at point"))
677 (org-table-align) ; Make sure we have everything we need.
678 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
680 (setq file
(read-file-name "Export table to: "))
681 (unless (or (not (file-exists-p file
))
682 (y-or-n-p (format "Overwrite file %s? " file
)))
683 (user-error "File not written")))
684 (when (file-directory-p file
)
685 (user-error "This is a directory path, not a file"))
686 (when (and (buffer-file-name (buffer-base-buffer))
689 (file-truename (buffer-file-name (buffer-base-buffer)))))
690 (user-error "Please specify a file name that is different from current"))
691 (let ((fileext (concat (file-name-extension file
) "$"))
692 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
694 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
695 "orgtbl-to-html" "orgtbl-to-generic"
696 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
697 "orgtbl-to-unicode"))
699 (replace-regexp-in-string
701 (replace-regexp-in-string
706 (and (string-match-p fileext f
) f
))
708 org-table-export-default-format
)
712 "Format: " formats nil nil deffmt-readable
))))
713 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
714 (let ((transform (intern (match-string 1 format
)))
715 (params (and (match-end 2)
716 (read (concat "(" (match-string 2 format
) ")"))))
717 (table (org-table-to-lisp
718 (buffer-substring-no-properties
719 (org-table-begin) (org-table-end)))))
720 (unless (fboundp transform
)
721 (user-error "No such transformation function %s" transform
))
723 (with-current-buffer (find-file-noselect file
)
724 (setq buf
(current-buffer))
727 (insert (funcall transform table params
) "\n")
730 (message "Export done."))
731 (user-error "TABLE_EXPORT_FORMAT invalid")))))
733 (defvar org-table-aligned-begin-marker
(make-marker)
734 "Marker at the beginning of the table last aligned.
735 Used to check if cursor still is in that table, to minimize realignment.")
736 (defvar org-table-aligned-end-marker
(make-marker)
737 "Marker at the end of the table last aligned.
738 Used to check if cursor still is in that table, to minimize realignment.")
739 (defvar org-table-last-alignment nil
740 "List of flags for flushright alignment, from the last re-alignment.
741 This is being used to correctly align a single field after TAB or RET.")
742 (defvar org-table-last-column-widths nil
743 "List of max width of fields in each column.
744 This is being used to correctly align a single field after TAB or RET.")
745 (defvar-local org-table-formula-debug nil
746 "Non-nil means debug table formulas.
747 When nil, simply write \"#ERROR\" in corrupted fields.")
748 (defvar-local org-table-overlay-coordinates nil
749 "Overlay coordinates after each align of a table.")
751 (defvar org-last-recalc-line nil
)
752 (defvar org-table-do-narrow t
) ; for dynamic scoping
753 (defconst org-narrow-column-arrow
"=>"
754 "Used as display property in narrowed table columns.")
757 (defun org-table-align ()
758 "Align the table at point by aligning all vertical bars."
760 (let* ((beg (org-table-begin))
761 (end (copy-marker (org-table-end))))
762 (org-table-save-field
763 ;; Make sure invisible characters in the table are at the right
764 ;; place since column widths take them into account.
765 (font-lock-fontify-region beg end
)
766 (move-marker org-table-aligned-begin-marker beg
)
767 (move-marker org-table-aligned-end-marker end
)
769 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
770 ;; Table's rows. Separators are replaced by nil. Trailing
771 ;; spaces are also removed.
772 (lines (mapcar (lambda (l)
773 (and (not (string-match-p "\\`[ \t]*|-" l
))
774 (let ((l (org-trim l
)))
775 (remove-text-properties
776 0 (length l
) '(display t org-cwidth t
) l
)
778 (org-split-string (buffer-substring beg end
) "\n")))
779 ;; Get the data fields by splitting the lines.
780 (fields (mapcar (lambda (l) (org-split-string l
" *| *"))
782 ;; Compute number of fields in the longest line. If the
783 ;; table contains no field, create a default table.
784 (maxfields (if fields
(apply #'max
(mapcar #'length fields
))
785 (kill-region beg end
)
786 (org-table-create org-table-default-size
)
787 (user-error "Empty table - created default table")))
788 ;; A list of empty strings to fill any short rows on output.
789 (emptycells (make-list maxfields
""))
791 ;; Check for special formatting.
792 (dotimes (i maxfields
)
793 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) fields
))
795 ;; Look for an explicit width or alignment.
796 (when (save-excursion
797 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t
)
798 (and org-table-do-narrow
800 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t
))))
802 (dolist (cell column
)
803 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell
)
804 (when (match-end 1) (setq falign
(match-string 1 cell
)))
805 (when (and org-table-do-narrow
(match-end 2))
806 (setq fmax
(string-to-number (match-string 2 cell
))))
807 (when (or falign fmax
) (throw :exit nil
)))))
808 ;; Find fields that are wider than FMAX, and shorten them.
811 (when (> (string-width x
) fmax
)
815 "Clipped table field, use `\\[org-table-edit-field]' to \
816 edit. Full value is:\n"
817 (substring-no-properties x
)))
820 (or (string-match org-bracket-link-regexp x
)
825 "Cannot narrow field starting with wide link \"%s\""
827 (if (= (org-string-width x
) l
) (setq f2 f1
)
829 (while (< (org-string-width (substring x
0 f2
)) f1
)
831 (add-text-properties f2 l
(list 'org-cwidth t
) x
)
833 (if (>= (string-width (substring x
(1- f2
) f2
)) 2) (1- f2
)
836 (list 'display org-narrow-column-arrow
)
838 ;; Get the maximum width for each column
839 (push (or fmax
(apply #'max
1 (mapcar #'org-string-width column
)))
841 ;; Get the fraction of numbers among non-empty cells to
842 ;; decide about alignment of the column.
843 (if falign
(push (equal (downcase falign
) "r") typenums
)
850 (if (string-match-p org-table-number-regexp x
)
854 (push (>= frac org-table-number-fraction
) typenums
)))))
855 (setq lengths
(nreverse lengths
))
856 (setq typenums
(nreverse typenums
))
857 ;; Store alignment of this table, for later editing of single
859 (setq org-table-last-alignment typenums
)
860 (setq org-table-last-column-widths lengths
)
861 ;; With invisible characters, `format' does not get the field
862 ;; width right So we need to make these fields wide by hand.
863 ;; Invisible characters may be introduced by fontified links,
864 ;; emphasis, macros or sub/superscripts.
865 (when (or (text-property-any beg end
'invisible
'org-link
)
866 (text-property-any beg end
'invisible t
))
867 (dotimes (i maxfields
)
868 (let ((len (nth i lengths
)))
869 (dotimes (j (length fields
))
870 (let* ((c (nthcdr i
(nth j fields
)))
874 (let ((l (length cell
)))
875 (or (text-property-any 0 l
'invisible
'org-link cell
)
876 (text-property-any beg end
'invisible t
)))
877 (< (org-string-width cell
) len
))
878 (let ((s (make-string (- len
(org-string-width cell
)) ?\s
)))
879 (setcar c
(if (nth i typenums
) (concat s cell
)
880 (concat cell s
))))))))))
882 ;; Compute the formats needed for output of the table.
883 (let ((hfmt (concat indent
"|"))
884 (rfmt (concat indent
"|"))
887 (dolist (l lengths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
888 (let ((ty (if (pop typenums
) "" "-"))) ; Flush numbers right.
889 (setq rfmt
(concat rfmt
(format rfmt1 ty l
)))
890 (setq hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
))))))
891 ;; Replace modified lines only. Check not only contents, but
892 ;; also columns' width.
895 (if l
(apply #'format rfmt
(append (pop fields
) emptycells
))
897 (previous (buffer-substring (point) (line-end-position))))
898 (if (and (equal previous line
)
902 (setq a
(next-single-property-change
903 a
'org-cwidth previous
))
904 (setq b
(next-single-property-change
905 b
'org-cwidth line
)))
910 (delete-region (point) (line-beginning-position 2))))))
911 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
912 (goto-char org-table-aligned-begin-marker
)
913 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
915 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
916 (setq org-table-may-need-update nil
)))))
919 (defun org-table-begin (&optional table-type
)
920 "Find the beginning of the table and return its position.
921 With a non-nil optional argument TABLE-TYPE, return the beginning
922 of a table.el-type table. This function assumes point is on
925 (org-element-property :post-affiliated
(org-element-at-point)))
927 (and (re-search-backward org-table-border-regexp nil t
)
928 (line-beginning-position 2))))
932 (defun org-table-end (&optional table-type
)
933 "Find the end of the table and return its position.
934 With a non-nil optional argument TABLE-TYPE, return the end of
935 a table.el-type table. This function assumes point is on
939 (goto-char (org-element-property :end
(org-element-at-point)))
940 (skip-chars-backward " \t\n")
941 (line-beginning-position 2))
942 ((re-search-forward org-table-border-regexp nil t
)
944 ;; When the line right after the table is the last line in
945 ;; the buffer with trailing spaces but no final newline
946 ;; character, be sure to catch the correct ending at its
947 ;; beginning. In any other case, ending is expected to be
949 (t (goto-char (point-max))
950 (skip-chars-backward " \t")
951 (if (bolp) (point) (line-end-position))))))
954 (defun org-table-justify-field-maybe (&optional new
)
955 "Justify the current field, text to left, number to right.
956 Optional argument NEW may specify text to replace the current field content."
958 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
959 ((org-at-table-hline-p))
961 (or (not (eq (marker-buffer org-table-aligned-begin-marker
)
963 (< (point) org-table-aligned-begin-marker
)
964 (>= (point) org-table-aligned-end-marker
)))
965 ;; This is not the same table, force a full re-align.
966 (setq org-table-may-need-update t
))
968 ;; Realign the current field, based on previous full realign.
970 (col (org-table-current-column)))
972 (skip-chars-backward "^|")
973 (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
974 (setq org-table-may-need-update t
)
975 (let* ((numbers?
(nth (1- col
) org-table-last-alignment
))
976 (cell (match-string 0))
977 (field (match-string 1))
978 (len (max 1 (- (org-string-width cell
) 3)))
979 (properly-closed?
(/= (match-beginning 2) (match-end 2)))
980 (fmt (format (if numbers?
" %%%ds %s" " %%-%ds %s")
982 (if properly-closed?
"|"
983 (setq org-table-may-need-update t
)
986 (cond ((not new
) (format fmt field
))
987 ((<= (org-string-width new
) len
) (format fmt new
))
989 (setq org-table-may-need-update t
)
990 (format " %s |" new
)))))
991 (unless (equal new-cell cell
)
992 (let (org-table-may-need-update)
993 (replace-match new-cell t t
)))
994 (goto-char pos
))))))))
997 (defun org-table-next-field ()
998 "Go to the next field in the current table, creating new lines as needed.
999 Before doing so, re-align the table if necessary."
1001 (org-table-maybe-eval-formula)
1002 (org-table-maybe-recalculate-line)
1003 (if (and org-table-automatic-realign
1004 org-table-may-need-update
)
1006 (let ((end (org-table-end)))
1007 (if (org-at-table-hline-p)
1011 (re-search-forward "|" end
)
1012 (if (looking-at "[ \t]*$")
1013 (re-search-forward "|" end
))
1014 (if (and (looking-at "-")
1015 org-table-tab-jumps-over-hlines
1016 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1017 (goto-char (match-beginning 1)))
1018 (if (looking-at "-")
1020 (beginning-of-line 0)
1021 (org-table-insert-row 'below
))
1022 (if (looking-at " ") (forward-char 1))))
1024 (org-table-insert-row 'below
)))))
1027 (defun org-table-previous-field ()
1028 "Go to the previous field in the table.
1029 Before doing so, re-align the table if necessary."
1031 (org-table-justify-field-maybe)
1032 (org-table-maybe-recalculate-line)
1033 (when (and org-table-automatic-realign
1034 org-table-may-need-update
)
1036 (when (org-at-table-hline-p)
1038 (let ((start (org-table-begin))
1042 (search-backward "|" start nil
2)
1043 (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)")
1044 (search-backward "|" start
)))
1047 (user-error "Cannot move to previous table field"))))
1048 (when (looking-at "| ?")
1049 (goto-char (match-end 0))))
1051 (defun org-table-beginning-of-field (&optional n
)
1052 "Move to the beginning of the current table field.
1053 If already at or before the beginning, move to the beginning of the
1055 With numeric argument N, move N-1 fields backward first."
1057 (let ((pos (point)))
1060 (org-table-previous-field))
1061 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1062 (user-error "No more table fields before the current")
1063 (goto-char (match-end 0))
1064 (and (looking-at " ") (forward-char 1)))
1065 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1067 (defun org-table-end-of-field (&optional n
)
1068 "Move to the end of the current table field.
1069 If already at or after the end, move to the end of the next table field.
1070 With numeric argument N, move N-1 fields forward first."
1072 (let ((pos (point)))
1075 (org-table-next-field))
1076 (when (re-search-forward "|" (point-at-eol 1) t
)
1078 (skip-chars-backward " ")
1079 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1081 (if (<= (point) pos
) (org-table-end-of-field 2))))
1084 (defun org-table-next-row ()
1085 "Go to the next row (same column) in the current table.
1086 Before doing so, re-align the table if necessary."
1088 (org-table-maybe-eval-formula)
1089 (org-table-maybe-recalculate-line)
1090 (if (and org-table-automatic-realign
1091 org-table-may-need-update
)
1093 (let ((col (org-table-current-column)))
1094 (beginning-of-line 2)
1095 (when (or (not (org-at-table-p))
1096 (org-at-table-hline-p))
1097 (beginning-of-line 0)
1098 (org-table-insert-row 'below
))
1099 (org-table-goto-column col
)
1100 (skip-chars-backward "^|\n\r")
1101 (when (looking-at " ") (forward-char))))
1104 (defun org-table-copy-down (n)
1105 "Copy the value of the current field one row below.
1107 If the field at the cursor is empty, copy the content of the
1108 nearest non-empty field above. With argument N, use the Nth
1111 If the current field is not empty, it is copied down to the next
1112 row, and the cursor is moved with it. Therefore, repeating this
1113 command causes the column to be filled row-by-row.
1115 If the variable `org-table-copy-increment' is non-nil and the
1116 field is an integer or a timestamp, it will be incremented while
1117 copying. By default, increment by the difference between the
1118 value in the current field and the one in the field above. To
1119 increment using a fixed integer, set `org-table-copy-increment'
1120 to a number. In the case of a timestamp, increment by days."
1122 (let* ((colpos (org-table-current-column))
1123 (col (current-column))
1124 (field (save-excursion (org-table-get-field)))
1125 (field-up (or (save-excursion
1126 (org-table-get (1- (org-table-current-line))
1127 (org-table-current-column))) ""))
1128 (non-empty (string-match "[^ \t]" field
))
1129 (non-empty-up (string-match "[^ \t]" field-up
))
1130 (beg (org-table-begin))
1133 (org-table-check-inside-data-field)
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))))))
1148 (while (progn (beginning-of-line 1)
1149 (re-search-backward org-table-dataline-regexp
1151 (org-table-goto-column colpos t
)
1152 (if (and (looking-at
1153 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1154 (<= (setq n
(1- n
)) 0))
1155 (throw 'exit
(match-string 1))))))
1156 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1157 ;; Above field was not empty, go down to the next row
1158 (setq txt
(org-trim field
))
1159 (org-table-next-row)
1160 (org-table-blank-field))
1161 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1163 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1164 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1165 (string-match org-ts-regexp3 txt
))
1166 (- (org-time-string-to-absolute txt
)
1167 (org-time-string-to-absolute txt-up
)))
1168 ((string-match org-ts-regexp3 txt
) 1)
1169 ((string-match "\\([-+]\\)?[0-9]+\\(?:\.[0-9]+\\)?" txt-up
)
1170 (- (string-to-number txt
)
1171 (string-to-number (match-string 0 txt-up
))))
1175 (user-error "No non-empty field found")
1176 (if (and org-table-copy-increment
1177 (not (equal orig-n
0))
1178 (string-match-p "^[-+^/*0-9eE.]+$" txt
)
1179 (< (string-to-number txt
) 100000000))
1180 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1182 (org-move-to-column col
)
1183 (if (and org-table-copy-increment
(org-at-timestamp-p 'lax
))
1184 (org-timestamp-up-day inc
)
1185 (org-table-maybe-recalculate-line))
1187 (org-move-to-column col
))))
1189 (defun org-table-check-inside-data-field (&optional noerror
)
1190 "Is point inside a table data field?
1191 I.e. not on a hline or before the first or after the last column?
1192 This actually throws an error, so it aborts the current command."
1193 (cond ((and (org-at-table-p)
1194 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1195 (not (org-at-table-hline-p))
1196 (not (looking-at "[ \t]*$"))))
1198 (t (user-error "Not in table data field"))))
1200 (defvar org-table-clip nil
1201 "Clipboard for table regions.")
1203 (defun org-table-get (line column
)
1204 "Get the field in table line LINE, column COLUMN.
1205 If LINE is larger than the number of data lines in the table, the function
1206 returns nil. However, if COLUMN is too large, we will simply return an
1208 If LINE is nil, use the current line.
1209 If COLUMN is nil, use the current column."
1210 (setq column
(or column
(org-table-current-column)))
1212 (and (or (not line
) (org-table-goto-line line
))
1213 (org-trim (org-table-get-field column
)))))
1215 (defun org-table-put (line column value
&optional align
)
1216 "Put VALUE into line LINE, column COLUMN.
1217 When ALIGN is set, also realign the table."
1218 (setq column
(or column
(org-table-current-column)))
1219 (prog1 (save-excursion
1220 (and (or (not line
) (org-table-goto-line line
))
1221 (progn (org-table-goto-column column nil
'force
) t
)
1222 (org-table-get-field column value
)))
1223 (and align
(org-table-align))))
1225 (defun org-table-current-line ()
1226 "Return the index of the current data line."
1227 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1229 (goto-char (org-table-begin))
1230 (while (and (re-search-forward org-table-dataline-regexp end t
)
1232 (< (point-at-eol) pos
))))
1235 (defun org-table-goto-line (N)
1236 "Go to the Nth data line in the current table.
1237 Return t when the line exists, nil if it does not exist."
1238 (goto-char (org-table-begin))
1239 (let ((end (org-table-end)) (cnt 0))
1240 (while (and (re-search-forward org-table-dataline-regexp end t
)
1241 (< (setq cnt
(1+ cnt
)) N
)))
1245 (defun org-table-blank-field ()
1246 "Blank the current table field or active region."
1248 (org-table-check-inside-data-field)
1249 (if (and (called-interactively-p 'any
) (org-region-active-p))
1250 (let (org-table-clip)
1251 (org-table-cut-region (region-beginning) (region-end)))
1252 (skip-chars-backward "^|")
1254 (if (looking-at "|[^|\n]+")
1255 (let* ((pos (match-beginning 0))
1256 (match (match-string 0))
1257 (len (org-string-width match
)))
1258 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1259 (goto-char (+ 2 pos
))
1260 (substring match
1)))))
1262 (defun org-table-get-field (&optional n replace
)
1263 "Return the value of the field in column N of current row.
1264 N defaults to current column. If REPLACE is a string, replace
1265 field with this value. The return value is always the old
1267 (when n
(org-table-goto-column n
))
1268 (skip-chars-backward "^|\n")
1269 (if (or (bolp) (looking-at-p "[ \t]*$"))
1270 ;; Before first column or after last one.
1272 (looking-at "[^|\r\n]*")
1273 (let* ((pos (match-beginning 0))
1274 (val (buffer-substring pos
(match-end 0))))
1276 (replace-match (if (equal replace
"") " " replace
) t t
))
1277 (goto-char (min (line-end-position) (1+ pos
)))
1281 (defun org-table-field-info (_arg)
1282 "Show info about the current field, and highlight any reference at point."
1284 (unless (org-at-table-p) (user-error "Not at a table"))
1287 (let* ((pos (point))
1288 (col (org-table-current-column))
1289 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1290 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1291 (line-beginning-position))
1293 org-table-named-field-locations
)))
1294 (eql (org-table-expand-lhs-ranges
1297 (cons (org-table-formula-handle-first/last-rc
(car e
))
1299 (org-table-get-stored-formulas))))
1300 (dline (org-table-current-dline))
1301 (ref (format "@%d$%d" dline col
))
1302 (ref1 (org-table-convert-refs-to-an ref
))
1303 ;; Prioritize field formulas over column formulas.
1304 (fequation (or (assoc name eql
) (assoc ref eql
)))
1305 (cequation (assoc (format "$%d" col
) eql
))
1306 (eqn (or fequation cequation
)))
1307 (let ((p (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))))
1308 (when p
(setq eqn p
)))
1310 (ignore-errors (org-table-show-reference 'local
))
1311 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1313 (if cname
(concat " or $" cname
) "")
1315 (if name
(concat " or $" name
) "")
1316 ;; FIXME: formula info not correct if special table line
1318 (concat ", formula: "
1319 (org-table-formula-to-user
1321 (if (or (string-prefix-p "$" (car eqn
))
1322 (string-prefix-p "@" (car eqn
)))
1325 (car eqn
) "=" (cdr eqn
))))
1328 (defun org-table-current-column ()
1329 "Find out which column we are in."
1332 (let ((column 0) (pos (point)))
1334 (while (search-forward "|" pos t
) (cl-incf column
))
1337 (defun org-table-current-dline ()
1338 "Find out what table data line we are in.
1339 Only data lines count for this."
1342 (pos (line-beginning-position)))
1343 (goto-char (org-table-begin))
1344 (while (<= (point) pos
)
1345 (when (looking-at org-table-dataline-regexp
) (cl-incf c
))
1350 (defun org-table-goto-column (n &optional on-delim force
)
1351 "Move the cursor to the Nth column in the current table line.
1352 With optional argument ON-DELIM, stop with point before the left delimiter
1354 If there are less than N fields, just go to after the last delimiter.
1355 However, when FORCE is non-nil, create new columns if necessary."
1357 (beginning-of-line 1)
1359 (while (and (> (setq n
(1- n
)) -
1)
1360 (or (search-forward "|" (point-at-eol) t
)
1362 (progn (end-of-line 1)
1363 (skip-chars-backward "^|")
1366 (when (and force
(not (looking-at ".*|")))
1367 (save-excursion (end-of-line 1) (insert " | ")))
1370 (if (looking-at " ") (forward-char 1)))))
1373 (defun org-table-insert-column ()
1374 "Insert a new column into the table."
1376 (unless (org-at-table-p) (user-error "Not at a table"))
1377 (org-table-find-dataline)
1378 (let* ((col (max 1 (org-table-current-column)))
1379 (beg (org-table-begin))
1380 (end (copy-marker (org-table-end))))
1381 (org-table-save-field
1383 (while (< (point) end
)
1384 (unless (org-at-table-hline-p)
1385 (org-table-goto-column col t
)
1388 (set-marker end nil
)
1390 (when (or (not org-table-fix-formulas-confirm
)
1391 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1392 (org-table-fix-formulas "$" nil
(1- col
) 1)
1393 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1395 (defun org-table-find-dataline ()
1396 "Find a data line in the current table, which is needed for column commands."
1397 (if (and (org-at-table-p)
1398 (not (org-at-table-hline-p)))
1400 (let ((col (current-column))
1401 (end (org-table-end)))
1402 (org-move-to-column col
)
1403 (while (and (< (point) end
)
1404 (or (not (= (current-column) col
))
1405 (org-at-table-hline-p)))
1406 (beginning-of-line 2)
1407 (org-move-to-column col
))
1408 (if (and (org-at-table-p)
1409 (not (org-at-table-hline-p)))
1412 "Please position cursor in a data line for column operations")))))
1414 (defun org-table-line-to-dline (line &optional above
)
1415 "Turn a buffer line number into a data line number.
1417 If there is no data line in this line, return nil.
1419 If there is no matching dline (most likely the reference was
1420 a hline), the first dline below it is used. When ABOVE is
1421 non-nil, the one above is used."
1423 (max (1- (length org-table-dlines
))))
1424 (cond ((or (> (aref org-table-dlines min
) line
)
1425 (< (aref org-table-dlines max
) line
))
1427 ((= (aref org-table-dlines max
) line
) max
)
1429 (while (> (- max min
) 1)
1430 (let* ((mean (/ (+ max min
) 2))
1431 (v (aref org-table-dlines mean
)))
1432 (cond ((= v line
) (throw 'exit mean
))
1433 ((> v line
) (setq max mean
))
1434 (t (setq min mean
)))))
1435 (if above min max
))))))
1438 (defun org-table-delete-column ()
1439 "Delete a column from the table."
1441 (unless (org-at-table-p) (user-error "Not at a table"))
1442 (org-table-find-dataline)
1443 (org-table-check-inside-data-field)
1444 (let ((col (org-table-current-column))
1445 (beg (org-table-begin))
1446 (end (copy-marker (org-table-end))))
1447 (org-table-save-field
1449 (while (< (point) end
)
1450 (if (org-at-table-hline-p)
1452 (org-table-goto-column col t
)
1453 (and (looking-at "|[^|\n]+|")
1454 (replace-match "|")))
1456 (set-marker end nil
)
1457 (org-table-goto-column (max 1 (1- col
)))
1459 (when (or (not org-table-fix-formulas-confirm
)
1460 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1461 (org-table-fix-formulas
1462 "$" (list (cons (number-to-string col
) "INVALID")) col -
1 col
)
1463 (org-table-fix-formulas
1464 "$LR" (list (cons (number-to-string col
) "INVALID")) col -
1 col
))))
1467 (defun org-table-move-column-right ()
1468 "Move column to the right."
1470 (org-table-move-column nil
))
1472 (defun org-table-move-column-left ()
1473 "Move column to the left."
1475 (org-table-move-column 'left
))
1478 (defun org-table-move-column (&optional left
)
1479 "Move the current column to the right. With arg LEFT, move to the left."
1481 (unless (org-at-table-p) (user-error "Not at a table"))
1482 (org-table-find-dataline)
1483 (org-table-check-inside-data-field)
1484 (let* ((col (org-table-current-column))
1485 (col1 (if left
(1- col
) col
))
1486 (colpos (if left
(1- col
) (1+ col
)))
1487 (beg (org-table-begin))
1488 (end (copy-marker (org-table-end))))
1489 (when (and left
(= col
1))
1490 (user-error "Cannot move column further left"))
1491 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1492 (user-error "Cannot move column further right"))
1493 (org-table-save-field
1495 (while (< (point) end
)
1496 (unless (org-at-table-hline-p)
1497 (org-table-goto-column col1 t
)
1498 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1500 (match-beginning 1) (match-end 1)
1501 (match-beginning 2) (match-end 2))))
1503 (set-marker end nil
)
1504 (org-table-goto-column colpos
)
1506 (when (or (not org-table-fix-formulas-confirm
)
1507 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1508 (org-table-fix-formulas
1509 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1510 (cons (number-to-string colpos
) (number-to-string col
))))
1511 (org-table-fix-formulas
1512 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1513 (cons (number-to-string colpos
) (number-to-string col
)))))))
1516 (defun org-table-move-row-down ()
1517 "Move table row down."
1519 (org-table-move-row nil
))
1521 (defun org-table-move-row-up ()
1522 "Move table row up."
1524 (org-table-move-row 'up
))
1527 (defun org-table-move-row (&optional up
)
1528 "Move the current table line down. With arg UP, move it up."
1530 (let* ((col (current-column))
1532 (hline1p (save-excursion (beginning-of-line 1)
1533 (looking-at org-table-hline-regexp
)))
1534 (dline1 (org-table-current-dline))
1535 (dline2 (+ dline1
(if up -
1 1)))
1538 (when (and up
(= (point-min) (line-beginning-position)))
1539 (user-error "Cannot move row further"))
1540 (beginning-of-line tonew
)
1541 (when (or (and (not up
) (eobp)) (not (org-at-table-p)))
1543 (user-error "Cannot move row further"))
1544 (setq hline2p
(looking-at org-table-hline-regexp
))
1546 (let ((row (delete-and-extract-region (line-beginning-position)
1547 (line-beginning-position 2))))
1548 (beginning-of-line tonew
)
1549 (unless (bolp) (insert "\n")) ;at eob without a newline
1551 (unless (bolp) (insert "\n")) ;missing final newline in ROW
1552 (beginning-of-line 0)
1553 (org-move-to-column col
)
1554 (unless (or hline1p hline2p
1555 (not (or (not org-table-fix-formulas-confirm
)
1556 (funcall org-table-fix-formulas-confirm
1557 "Fix formulas? "))))
1558 (org-table-fix-formulas
1560 (cons (number-to-string dline1
) (number-to-string dline2
))
1561 (cons (number-to-string dline2
) (number-to-string dline1
))))))))
1564 (defun org-table-insert-row (&optional arg
)
1565 "Insert a new row above the current line into the table.
1566 With prefix ARG, insert below the current line."
1568 (unless (org-at-table-p) (user-error "Not at a table"))
1569 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1570 (new (org-table-clean-line line
)))
1571 ;; Fix the first field if necessary
1572 (if (string-match "^[ \t]*| *[#$] *|" line
)
1573 (setq new
(replace-match (match-string 0 line
) t t new
)))
1574 (beginning-of-line (if arg
2 1))
1575 ;; Buffer may not end of a newline character, so ensure
1576 ;; (beginning-of-line 2) moves point to a new line.
1577 (unless (bolp) (insert "\n"))
1578 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1579 (beginning-of-line 0)
1580 (re-search-forward "| ?" (line-end-position) t
)
1581 (when (or org-table-may-need-update org-table-overlay-coordinates
)
1583 (when (or (not org-table-fix-formulas-confirm
)
1584 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1585 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1588 (defun org-table-insert-hline (&optional above
)
1589 "Insert a horizontal-line below the current line into the table.
1590 With prefix ABOVE, insert above the current line."
1592 (if (not (org-at-table-p))
1593 (user-error "Not at a table"))
1594 (when (eobp) (insert "\n") (backward-char 1))
1595 (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
1597 (let ((line (org-table-clean-line
1598 (buffer-substring (point-at-bol) (point-at-eol))))
1599 (col (current-column)))
1600 (while (string-match "|\\( +\\)|" line
)
1601 (setq line
(replace-match
1602 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1603 ?-
) "|") t t line
)))
1604 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1605 (beginning-of-line (if above
1 2))
1607 (beginning-of-line (if above
1 -
1))
1608 (org-move-to-column col
)
1609 (and org-table-overlay-coordinates
(org-table-align))))
1612 (defun org-table-hline-and-move (&optional same-column
)
1613 "Insert a hline and move to the row below that line."
1615 (let ((col (org-table-current-column)))
1616 (org-table-maybe-eval-formula)
1617 (org-table-maybe-recalculate-line)
1618 (org-table-insert-hline)
1620 (if (looking-at "\n[ \t]*|-")
1621 (progn (insert "\n|") (org-table-align))
1622 (org-table-next-field))
1623 (if same-column
(org-table-goto-column col
))))
1625 (defun org-table-clean-line (s)
1626 "Convert a table line S into a string with only \"|\" and space.
1627 In particular, this does handle wide and invisible characters."
1628 (if (string-match "^[ \t]*|-" s
)
1629 ;; It's a hline, just map the characters
1630 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1631 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1632 (setq s
(replace-match
1633 (concat "|" (make-string (org-string-width (match-string 1 s
))
1639 (defun org-table-kill-row ()
1640 "Delete the current row or horizontal line from the table."
1642 (if (not (org-at-table-p))
1643 (user-error "Not at a table"))
1644 (let ((col (current-column))
1645 (dline (and (not (org-match-line org-table-hline-regexp
))
1646 (org-table-current-dline))))
1647 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1648 (if (not (org-at-table-p)) (beginning-of-line 0))
1649 (org-move-to-column col
)
1651 (or (not org-table-fix-formulas-confirm
)
1652 (funcall org-table-fix-formulas-confirm
"Fix formulas? ")))
1653 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1657 (defun org-table-sort-lines
1658 (&optional with-case sorting-type getkey-func compare-func interactive?
)
1659 "Sort table lines according to the column at point.
1661 The position of point indicates the column to be used for
1662 sorting, and the range of lines is the range between the nearest
1663 horizontal separator lines, or the entire table of no such lines
1664 exist. If point is before the first column, you will be prompted
1665 for the sorting column. If there is an active region, the mark
1666 specifies the first line and the sorting column, while point
1667 should be in the last line to be included into the sorting.
1669 The command then prompts for the sorting type which can be
1670 alphabetically, numerically, or by time (as given in a time stamp
1671 in the field, or as a HH:MM value). Sorting in reverse order is
1674 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1676 If SORTING-TYPE is specified when this function is called from a Lisp
1677 program, no prompting will take place. SORTING-TYPE must be a character,
1678 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1679 sorting should be done in reverse order.
1681 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1682 a function to be called to extract the key. It must return a value
1683 that is compatible with COMPARE-FUNC, the function used to compare
1686 A non-nil value for INTERACTIVE? is used to signal that this
1687 function is being called interactively."
1688 (interactive (list current-prefix-arg nil nil nil t
))
1689 (when (org-region-active-p) (goto-char (region-beginning)))
1690 ;; Point must be either within a field or before a data line.
1692 (skip-chars-backward " \t")
1693 (when (bolp) (search-forward "|" (line-end-position) t
))
1694 (org-table-check-inside-data-field))
1695 ;; Set appropriate case sensitivity and column used for sorting.
1696 (let ((column (let ((c (org-table-current-column)))
1699 (read-number "Use column N for sorting: "))
1703 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1704 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1706 ;; Narrow buffer to appropriate sorting area.
1707 (if (org-region-active-p)
1708 (progn (goto-char (region-beginning))
1711 (save-excursion (goto-char (region-end))
1712 (line-beginning-position 2))))
1713 (let ((start (org-table-begin))
1714 (end (org-table-end)))
1717 (if (re-search-backward org-table-hline-regexp start t
)
1718 (line-beginning-position 2)
1720 (if (save-excursion (re-search-forward org-table-hline-regexp end t
))
1723 ;; Determine arguments for `sort-subr'. Also record original
1724 ;; position. `org-table-save-field' cannot help here since
1725 ;; sorting is too much destructive.
1726 (let* ((sort-fold-case (not with-case
))
1728 (cons (count-lines (point-min) (line-beginning-position))
1730 (extract-key-from-field
1731 ;; Function to be called on the contents of the field
1732 ;; used for sorting in the current row.
1733 (cl-case sorting-type
1734 ((?n ?N
) #'string-to-number
)
1735 ((?a ?A
) #'org-sort-remove-invisible
)
1738 (cond ((string-match org-ts-regexp-both f
)
1740 (org-time-string-to-time (match-string 0 f
))))
1741 ((org-duration-p f
) (org-duration-to-minutes f
))
1742 ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f
)
1743 (org-duration-to-minutes (match-string 0 f
)))
1748 (org-read-function "Function for extracting keys: "))
1749 (error "Missing key extractor to sort rows")))
1750 (t (user-error "Invalid sorting type `%c'" sorting-type
))))
1752 (cl-case sorting-type
1759 (concat "Function for comparing keys "
1760 "(empty for default `sort-subr' predicate): ")
1762 (goto-char (point-min))
1763 (sort-subr (memq sorting-type
'(?A ?N ?T ?F
))
1766 (while (and (not (eobp))
1767 (not (looking-at org-table-dataline-regexp
)))
1771 (funcall extract-key-from-field
1772 (org-trim (org-table-get-field column
))))
1775 ;; Move back to initial field.
1776 (forward-line (car coordinates
))
1777 (move-to-column (cdr coordinates
))))))
1780 (defun org-table-cut-region (beg end
)
1781 "Copy region in table to the clipboard and blank all relevant fields.
1782 If there is no active region, use just the field at point."
1784 (if (org-region-active-p) (region-beginning) (point))
1785 (if (org-region-active-p) (region-end) (point))))
1786 (org-table-copy-region beg end
'cut
))
1789 (defun org-table-copy-region (beg end
&optional cut
)
1790 "Copy rectangular region in table to clipboard.
1791 A special clipboard is used which can only be accessed
1792 with `org-table-paste-rectangle'."
1794 (if (org-region-active-p) (region-beginning) (point))
1795 (if (org-region-active-p) (region-end) (point))
1796 current-prefix-arg
))
1797 (goto-char (min beg end
))
1798 (org-table-check-inside-data-field)
1799 (let ((beg (line-beginning-position))
1800 (c01 (org-table-current-column))
1802 (goto-char (max beg end
))
1803 (org-table-check-inside-data-field)
1804 (let* ((end (copy-marker (line-end-position)))
1805 (c02 (org-table-current-column))
1806 (column-start (min c01 c02
))
1807 (column-end (max c01 c02
))
1808 (column-number (1+ (- column-end column-start
)))
1809 (rpl (and cut
" ")))
1811 (while (< (point) end
)
1812 (unless (org-at-table-hline-p)
1813 ;; Collect every cell between COLUMN-START and COLUMN-END.
1815 (dotimes (c column-number
)
1816 (push (org-table-get-field (+ c column-start
) rpl
) cols
))
1817 (push (nreverse cols
) region
)))
1819 (set-marker end nil
))
1820 (when cut
(org-table-align))
1821 (setq org-table-clip
(nreverse region
))))
1824 (defun org-table-paste-rectangle ()
1825 "Paste a rectangular region into a table.
1826 The upper right corner ends up in the current field. All involved fields
1827 will be overwritten. If the rectangle does not fit into the present table,
1828 the table is enlarged as needed. The process ignores horizontal separator
1831 (unless (consp org-table-clip
)
1832 (user-error "First cut/copy a region to paste!"))
1833 (org-table-check-inside-data-field)
1834 (let* ((column (org-table-current-column))
1835 (org-table-automatic-realign nil
))
1836 (org-table-save-field
1837 (dolist (row org-table-clip
)
1838 (while (org-at-table-hline-p) (forward-line))
1839 ;; If we left the table, create a new row.
1840 (when (and (bolp) (not (looking-at "[ \t]*|")))
1842 (org-table-next-field))
1845 (org-table-goto-column c nil
'force
)
1846 (org-table-get-field nil field
)
1852 (defun org-table-convert ()
1853 "Convert from `org-mode' table to table.el and back.
1854 Obviously, this only works within limits. When an Org table is converted
1855 to table.el, all horizontal separator lines get lost, because table.el uses
1856 these as cell boundaries and has no notion of horizontal lines. A table.el
1857 table can be converted to an Org table only if it does not do row or column
1858 spanning. Multiline cells will become multiple cells. Beware, Org mode
1859 does not test if the table can be successfully converted - it blindly
1860 applies a recipe that works for simple tables."
1863 (if (org-at-table.el-p
)
1864 ;; convert to Org table
1865 (let ((beg (copy-marker (org-table-begin t
)))
1866 (end (copy-marker (org-table-end t
))))
1867 (table-unrecognize-region beg end
)
1869 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1872 (if (org-at-table-p)
1873 ;; convert to table.el table
1874 (let ((beg (copy-marker (org-table-begin)))
1875 (end (copy-marker (org-table-end))))
1876 ;; first, get rid of all horizontal lines
1878 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1880 ;; insert a hline before first
1882 (org-table-insert-hline 'above
)
1883 (beginning-of-line -
1)
1884 ;; insert a hline after each line
1885 (while (progn (beginning-of-line 3) (< (point) end
))
1886 (org-table-insert-hline))
1888 (setq end
(move-marker end
(org-table-end)))
1889 ;; replace "+" at beginning and ending of hlines
1890 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1891 (replace-match "\\1+-"))
1893 (while (re-search-forward "-|[ \t]*$" end t
)
1894 (replace-match "-+"))
1897 (defun org-table-transpose-table-at-point ()
1898 "Transpose Org table at point and eliminate hlines.
1906 will be transposed as
1913 Note that horizontal lines disappear."
1915 (let* ((table (delete 'hline
(org-table-to-lisp)))
1916 (dline_old (org-table-current-line))
1917 (col_old (org-table-current-column))
1918 (contents (mapcar (lambda (_)
1924 (setq tp
(cdr tp
))))
1927 (goto-char (org-table-begin))
1928 (re-search-forward "|")
1930 (delete-region (point) (org-table-end))
1933 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1935 (org-table-goto-line col_old
)
1936 (org-table-goto-column dline_old
))
1940 (defun org-table-wrap-region (arg)
1941 "Wrap several fields in a column like a paragraph.
1942 This is useful if you'd like to spread the contents of a field over several
1943 lines, in order to keep the table compact.
1945 If there is an active region, and both point and mark are in the same column,
1946 the text in the column is wrapped to minimum width for the given number of
1947 lines. Generally, this makes the table more compact. A prefix ARG may be
1948 used to change the number of desired lines. For example, \
1949 `C-2 \\[org-table-wrap-region]'
1950 formats the selected text to two lines. If the region was longer than two
1951 lines, the remaining lines remain empty. A negative prefix argument reduces
1952 the current number of lines by that amount. The wrapped text is pasted back
1953 into the table. If you formatted it to more lines than it was before, fields
1954 further down in the table get overwritten - so you might need to make space in
1957 If there is no region, the current field is split at the cursor position and
1958 the text fragment to the right of the cursor is prepended to the field one
1961 If there is no region, but you specify a prefix ARG, the current field gets
1962 blank, and the content is appended to the field above."
1964 (org-table-check-inside-data-field)
1965 (if (org-region-active-p)
1966 ;; There is a region: fill as a paragraph.
1967 (let ((start (region-beginning)))
1968 (org-table-cut-region (region-beginning) (region-end))
1969 (when (> (length (car org-table-clip
)) 1)
1970 (user-error "Region must be limited to single column"))
1971 (let ((nlines (cond ((not arg
) (length org-table-clip
))
1972 ((< arg
1) (+ (length org-table-clip
) arg
))
1974 (setq org-table-clip
1976 (org-wrap (mapconcat #'car org-table-clip
" ")
1980 (org-table-paste-rectangle))
1981 ;; No region, split the current field at point.
1982 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1983 (skip-chars-forward "^\r\n|"))
1985 (arg ; Combine with field above.
1986 (let ((s (org-table-blank-field))
1987 (col (org-table-current-column)))
1989 (while (org-at-table-hline-p) (forward-line -
1))
1990 (org-table-goto-column col
)
1991 (skip-chars-forward "^|")
1992 (skip-chars-backward " ")
1993 (insert " " (org-trim s
))
1995 ((looking-at "\\([^|]+\\)+|") ; Split field.
1996 (let ((s (match-string 1)))
1997 (replace-match " |")
1998 (goto-char (match-beginning 0))
1999 (org-table-next-row)
2000 (insert (org-trim s
) " ")
2002 (t (org-table-next-row)))))
2004 (defvar org-field-marker nil
)
2007 (defun org-table-edit-field (arg)
2008 "Edit table field in a different window.
2009 This is mainly useful for fields that contain hidden parts.
2011 When called with a `\\[universal-argument]' prefix, just make the full field
2012 visible so that it can be edited in place.
2014 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2015 toggle `org-table-follow-field-mode'."
2017 (unless (org-at-table-p) (user-error "Not at a table"))
2020 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2022 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2023 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2024 (remove-text-properties b e
'(org-cwidth t invisible t
2025 display t intangible t
))
2026 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2027 (font-lock-fontify-block))))
2029 (let ((pos (point-marker))
2031 (if (eq org-table-use-standard-references t
)
2032 (concat (org-number-to-letters (org-table-current-column))
2033 (int-to-string (org-table-current-dline)))
2034 (concat "@" (int-to-string (org-table-current-dline))
2035 "$" (int-to-string (org-table-current-column)))))
2036 (field (org-table-get-field))
2037 (cw (current-window-configuration))
2040 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2041 (when (and (local-variable-p 'org-field-marker
)
2042 (markerp org-field-marker
))
2043 (move-marker org-field-marker nil
))
2045 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2046 (let ((org-inhibit-startup t
)) (org-mode))
2048 (setq truncate-lines nil
)
2050 (goto-char (setq p
(point-max)))
2051 (insert (org-trim field
))
2052 (remove-text-properties p
(point-max)
2053 '(invisible t org-cwidth t display t
2056 (setq-local org-finish-function
'org-table-finish-edit-field
)
2057 (setq-local org-window-configuration cw
)
2058 (setq-local org-field-marker pos
)
2059 (message "Edit and finish with C-c C-c")))))
2061 (defun org-table-finish-edit-field ()
2062 "Finish editing a table data field.
2063 Remove all newline characters, insert the result into the table, realign
2064 the table and kill the editing buffer."
2065 (let ((pos org-field-marker
)
2066 (cw org-window-configuration
)
2067 (cb (current-buffer))
2069 (goto-char (point-min))
2070 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2071 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2072 (replace-match " "))
2073 (setq text
(org-trim (buffer-string)))
2074 (set-window-configuration cw
)
2076 (select-window (get-buffer-window (marker-buffer pos
)))
2078 (move-marker pos nil
)
2079 (org-table-check-inside-data-field)
2080 (org-table-get-field nil text
)
2082 (message "New field value inserted")))
2084 (define-minor-mode org-table-follow-field-mode
2085 "Minor mode to make the table field editor window follow the cursor.
2086 When this mode is active, the field editor window will always show the
2087 current field. The mode exits automatically when the cursor leaves the
2088 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2089 nil
" TblFollow" nil
2090 (if org-table-follow-field-mode
2091 (add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2093 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2094 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2095 (win (and buf
(get-buffer-window buf
))))
2096 (when win
(delete-window win
))
2098 (with-current-buffer buf
2099 (move-marker org-field-marker nil
))
2100 (kill-buffer buf
)))))
2102 (defun org-table-follow-fields-with-editor ()
2103 (if (and org-table-exit-follow-field-mode-when-leaving-table
2104 (not (org-at-table-p)))
2105 ;; We have left the table, exit the follow mode
2106 (org-table-follow-field-mode -
1)
2107 (when (org-table-check-inside-data-field 'noerror
)
2108 (let ((win (selected-window)))
2109 (org-table-edit-field nil
)
2110 (org-fit-window-to-buffer)
2111 (select-window win
)))))
2113 (defvar org-timecnt
) ; dynamically scoped parameter
2116 (defun org-table-sum (&optional beg end nlast
)
2117 "Sum numbers in region of current table column.
2118 The result will be displayed in the echo area, and will be available
2119 as kill to be inserted with \\[yank].
2121 If there is an active region, it is interpreted as a rectangle and all
2122 numbers in that rectangle will be summed. If there is no active
2123 region and point is located in a table column, sum all numbers in that
2126 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2127 numbers are assumed to be times as well (in decimal hours) and the
2128 numbers are added as such.
2130 If NLAST is a number, only the NLAST fields will actually be summed."
2133 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2135 ((and beg end
)) ; beg and end given explicitly
2136 ((org-region-active-p)
2137 (setq beg
(region-beginning) end
(region-end)))
2139 (setq col
(org-table-current-column))
2140 (goto-char (org-table-begin))
2141 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2142 (user-error "No table data"))
2143 (org-table-goto-column col
)
2145 (goto-char (org-table-end))
2146 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2147 (user-error "No table data"))
2148 (org-table-goto-column col
)
2149 (setq end
(point))))
2150 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2151 (items1 (cond ((not nlast
) items
)
2152 ((>= nlast
(length items
)) items
)
2153 (t (setq items
(reverse items
))
2154 (setcdr (nthcdr (1- nlast
) items
) nil
)
2156 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2158 (res (apply '+ numbers
))
2159 (sres (if (= org-timecnt
0)
2160 (number-to-string res
)
2161 (setq diff
(* 3600 res
)
2162 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2163 m
(floor (/ diff
60)) diff
(mod diff
60)
2165 (format "%.0f:%02.0f:%02.0f" h m s
))))
2167 (when (called-interactively-p 'interactive
)
2168 (message "%s" (substitute-command-keys
2169 (format "Sum of %d items: %-20s \
2170 \(\\[yank] will insert result into buffer)" (length numbers
) sres
))))
2173 (defun org-table-get-number-for-summing (s)
2175 (if (string-match "^ *|? *" s
)
2176 (setq s
(replace-match "" nil nil s
)))
2177 (if (string-match " *|? *$" s
)
2178 (setq s
(replace-match "" nil nil s
)))
2179 (setq n
(string-to-number s
))
2181 ((and (string-match "0" s
)
2182 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2183 ((string-match "\\`[ \t]+\\'" s
) nil
)
2184 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2185 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2186 (m (string-to-number (or (match-string 2 s
) "0")))
2187 (s (string-to-number (or (match-string 4 s
) "0"))))
2188 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2189 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2193 (defun org-table-current-field-formula (&optional key noerror
)
2194 "Return the formula active for the current field.
2196 Assumes that table is already analyzed. If KEY is given, return
2197 the key to this formula. Otherwise return the formula preceded
2198 with \"=\" or \":=\"."
2199 (let* ((line (count-lines org-table-current-begin-pos
2200 (line-beginning-position)))
2201 (row (org-table-line-to-dline line
)))
2204 (let* ((col (org-table-current-column))
2205 (name (car (rassoc (list line col
)
2206 org-table-named-field-locations
)))
2207 (scol (format "$%d" col
))
2208 (ref (format "@%d$%d" (org-table-current-dline) col
))
2209 (stored-list (org-table-get-stored-formulas noerror
))
2210 (ass (or (assoc name stored-list
)
2211 (assoc ref stored-list
)
2212 (assoc scol stored-list
))))
2213 (cond (key (car ass
))
2214 (ass (concat (if (string-match-p "^[0-9]+$" (car ass
)) "=" ":=")
2217 (t (error "No formula active for the current field")))))
2219 (defun org-table-get-formula (&optional equation named
)
2220 "Read a formula from the minibuffer, offer stored formula as default.
2221 When NAMED is non-nil, look for a named equation."
2222 (let* ((stored-list (org-table-get-stored-formulas))
2223 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2224 (line-beginning-position))
2225 (org-table-current-column))
2226 org-table-named-field-locations
)))
2227 (ref (format "@%d$%d"
2228 (org-table-current-dline)
2229 (org-table-current-column)))
2231 ((not named
) (format "$%d" (org-table-current-column)))
2232 ((and name
(not (string-match "\\`LR[0-9]+\\'" name
))) name
)
2234 (name (or name ref
))
2235 (org-table-may-need-update nil
)
2236 (stored (cdr (assoc scol stored-list
)))
2238 ((and stored equation
(string-match-p "^ *=? *$" equation
))
2242 (t (org-table-formula-from-user
2244 (org-table-formula-to-user
2245 (format "%s formula %s="
2246 (if named
"Field" "Column")
2248 (if stored
(org-table-formula-to-user stored
) "")
2249 'org-table-formula-history
2252 (when (not (string-match "\\S-" eq
))
2254 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2255 (org-table-store-formulas stored-list
)
2256 (user-error "Formula removed"))
2257 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2258 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2259 (if (and name
(not named
))
2260 ;; We set the column equation, delete the named one.
2261 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2264 (setcdr (assoc scol stored-list
) eq
)
2265 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2266 (if (or mustsave
(not (equal stored eq
)))
2267 (org-table-store-formulas stored-list
))
2270 (defun org-table-store-formulas (alist &optional location
)
2271 "Store the list of formulas below the current table.
2272 If optional argument LOCATION is a buffer position, insert it at
2276 (progn (goto-char location
) (beginning-of-line))
2277 (goto-char (org-table-end)))
2278 (let ((case-fold-search t
))
2279 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2281 ;; Don't overwrite TBLFM, we might use text properties to
2283 (goto-char (match-beginning 3))
2284 (delete-region (match-beginning 3) (match-end 0)))
2286 (insert (or (match-string 2) "#+TBLFM:")))
2288 (mapconcat (lambda (x) (concat (car x
) "=" (cdr x
)))
2289 (sort alist
#'org-table-formula-less-p
)
2293 (defsubst org-table-formula-make-cmp-string
(a)
2294 (when (string-match "\\`$[<>]" a
)
2295 (let ((arrow (string-to-char (substring a
1))))
2296 ;; Fake a high number to make sure this is sorted at the end.
2297 (setq a
(org-table-formula-handle-first/last-rc a
))
2298 (setq a
(format "$%d" (+ 10000
2299 (if (= arrow ?
<) -
1000 0)
2300 (string-to-number (substring a
1)))))))
2302 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2306 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2308 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2310 (concat "@@" (match-string 5 a
))))))
2312 (defun org-table-formula-less-p (a b
)
2313 "Compare two formulas for sorting."
2314 (let ((as (org-table-formula-make-cmp-string (car a
)))
2315 (bs (org-table-formula-make-cmp-string (car b
))))
2316 (and as bs
(string< as bs
))))
2319 (defun org-table-get-stored-formulas (&optional noerror location
)
2320 "Return an alist with the stored formulas directly after current table.
2321 By default, only return active formulas, i.e., formulas located
2322 on the first line after the table. However, if optional argument
2323 LOCATION is a buffer position, consider the formulas there."
2326 (progn (goto-char location
) (beginning-of-line))
2327 (goto-char (org-table-end)))
2328 (let ((case-fold-search t
))
2329 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2330 (let ((strings (org-split-string (match-string-no-properties 2)
2333 (dolist (string strings
(nreverse eq-alist
))
2334 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2335 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2338 (let ((m (match-string 1 string
)))
2340 ((not (match-end 2)) m
)
2341 ;; Is it a column reference?
2342 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m
) m
)
2343 ;; Since named columns are not possible in
2344 ;; LHS, assume this is a named field.
2345 (t (match-string 2 string
)))))
2346 (rhs (match-string 3 string
)))
2347 (push (cons lhs rhs
) eq-alist
)
2349 ((not (member lhs seen
)) (push lhs seen
))
2352 "Double definition `%s=' in TBLFM line, please fix by hand"
2358 "Double definition `%s=' in TBLFM line, please fix by hand"
2361 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2362 "Modify the equations after the table structure has been edited.
2363 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2364 For all numbers larger than LIMIT, shift them by DELTA."
2366 (goto-char (org-table-end))
2367 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2368 (let ((msg "The formulas in #+TBLFM have been updated")
2369 (re (concat key
"\\([0-9]+\\)"))
2372 (if (or (equal key
"$") (equal key
"$LR"))
2373 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2374 (regexp-quote key
) remove
)
2375 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2378 (while (re-search-forward re2
(point-at-eol) t
)
2379 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2380 (if (equal (char-before (match-beginning 0)) ?.
)
2382 "Change makes TBLFM term %s invalid, use undo to recover"
2384 (replace-match "")))))
2385 (while (re-search-forward re
(point-at-eol) t
)
2386 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2387 (setq s
(match-string 1) n
(string-to-number s
))
2389 ((setq a
(assoc s replace
))
2390 (replace-match (concat key
(cdr a
)) t t
)
2392 ((and limit
(> n limit
))
2393 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2398 (defun org-table-maybe-eval-formula ()
2399 "Check if the current field starts with \"=\" or \":=\".
2400 If yes, store the formula and apply it."
2401 ;; We already know we are in a table. Get field will only return a formula
2402 ;; when appropriate. It might return a separator line, but no problem.
2403 (when org-table-formula-evaluate-inline
2404 (let* ((field (org-trim (or (org-table-get-field) "")))
2406 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2407 (setq named
(equal (string-to-char field
) ?
:)
2408 eq
(match-string 1 field
))
2409 (org-table-eval-formula (and named
'(4))
2410 (org-table-formula-from-user eq
))))))
2412 (defvar org-recalc-commands nil
2413 "List of commands triggering the recalculation of a line.
2414 Will be filled automatically during use.")
2416 (defvar org-recalc-marks
2417 '((" " .
"Unmarked: no special line, no automatic recalculation")
2418 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2419 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2420 ("!" .
"Column name definition line. Reference in formula as $name.")
2421 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2422 ("_" .
"Names for values in row below this one.")
2423 ("^" .
"Names for values in row above this one.")))
2426 (defun org-table-rotate-recalc-marks (&optional newchar
)
2427 "Rotate the recalculation mark in the first column.
2428 If in any row, the first field is not consistent with a mark,
2429 insert a new column for the markers.
2430 When there is an active region, change all the lines in the region,
2431 after prompting for the marking character.
2432 After each change, a message will be displayed indicating the meaning
2435 (unless (org-at-table-p) (user-error "Not at a table"))
2436 (let* ((region (org-region-active-p))
2438 (save-excursion (goto-char (region-beginning))
2439 (copy-marker (line-beginning-position)))))
2441 (save-excursion (goto-char (region-end))
2442 (copy-marker (line-beginning-position)))))
2443 (l (copy-marker (line-beginning-position)))
2444 (col (org-table-current-column))
2447 (read-char-exclusive
2448 "Change region to what mark? Type # * ! $ or SPC: "))
2452 (goto-char (org-table-begin))
2454 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2455 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2456 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2458 (when l1
(goto-char l1
))
2461 (unless (looking-at org-table-dataline-regexp
)
2462 (user-error "Not at a table data line")))
2463 (when no-special-column
2464 (org-table-goto-column 1)
2465 (org-table-insert-column))
2466 (let ((previous-line-end (line-end-position))
2470 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2472 (t (cadr (member (match-string 1)
2473 (append (mapcar #'car org-recalc-marks
)
2475 ;; Rotate mark in first row.
2476 (org-table-get-field 1 (format " %s " newchar
))
2477 ;; Rotate marks in additional rows if a region is active.
2481 (while (<= (point) l2
)
2482 (when (looking-at org-table-dataline-regexp
)
2483 (org-table-get-field 1 (format " %s " newchar
)))
2485 ;; Only align if rotation actually changed lines' length.
2486 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2488 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2489 (when l1
(set-marker l1 nil
))
2490 (when l2
(set-marker l2 nil
))
2492 (when (called-interactively-p 'interactive
)
2493 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2496 (defun org-table-analyze ()
2497 "Analyze table at point and store results.
2499 This function sets up the following dynamically scoped variables:
2501 `org-table-column-name-regexp',
2502 `org-table-column-names',
2503 `org-table-current-begin-pos',
2504 `org-table-current-line-types',
2505 `org-table-current-ncol',
2508 `org-table-local-parameters',
2509 `org-table-named-field-locations'."
2510 (let ((beg (org-table-begin))
2511 (end (org-table-end)))
2514 ;; Extract column names.
2515 (setq org-table-column-names nil
)
2516 (when (save-excursion
2517 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
2519 (dolist (name (org-split-string (match-string 1) " *| *"))
2521 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
2522 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
2523 (setq org-table-column-names
(nreverse org-table-column-names
))
2524 (setq org-table-column-name-regexp
2525 (format "\\$\\(%s\\)\\>"
2526 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
2527 ;; Extract local parameters.
2528 (setq org-table-local-parameters nil
)
2530 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2531 (dolist (field (org-split-string (match-string 1) " *| *"))
2533 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2534 (push (cons (match-string 1 field
) (match-string 2 field
))
2535 org-table-local-parameters
)))))
2536 ;; Update named fields locations. We minimize `count-lines'
2537 ;; processing by storing last known number of lines in LAST.
2538 (setq org-table-named-field-locations nil
)
2540 (let ((last (cons (point) 0)))
2541 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2542 (let ((c (match-string 1))
2543 (fields (org-split-string (match-string 2) " *| *")))
2545 (forward-line (if (equal c
"_") 1 -
1))
2547 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2548 (org-split-string (match-string 1) " *| *")))
2549 (line (cl-incf (cdr last
) (count-lines (car last
) (point))))
2551 (setcar last
(point)) ; Update last known position.
2552 (while (and fields fields1
)
2553 (let ((field (pop fields
))
2556 (when (and (stringp field
)
2558 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2560 (push (cons field v
) org-table-local-parameters
)
2561 (push (list field line col
)
2562 org-table-named-field-locations
))))))))))
2563 ;; Re-use existing markers when possible.
2564 (if (markerp org-table-current-begin-pos
)
2565 (move-marker org-table-current-begin-pos
(point))
2566 (setq org-table-current-begin-pos
(point-marker)))
2567 ;; Analyze the line types.
2568 (let ((l 0) hlines dlines types
)
2569 (while (looking-at "[ \t]*|\\(-\\)?")
2570 (push (if (match-end 1) 'hline
'dline
) types
)
2571 (if (match-end 1) (push l hlines
) (push l dlines
))
2574 (push 'hline types
) ; Add an imaginary extra hline to the end.
2575 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
2576 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
2577 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
)))))
2578 ;; Get the number of columns from the first data line in table.
2580 (forward-line (aref org-table-dlines
1))
2583 (buffer-substring (line-beginning-position) (line-end-position))
2585 (nfields (length fields
))
2587 (setq org-table-current-ncol nfields
)
2589 (aref org-table-dlines
(1- (length org-table-dlines
)))))
2590 (dotimes (i nfields
)
2591 (let ((column (1+ i
)))
2592 (push (list (format "LR%d" column
) last-dline column
) al
)
2593 (push (cons (format "LR%d" column
) (nth i fields
)) al2
))))
2594 (setq org-table-named-field-locations
2595 (append org-table-named-field-locations al
))
2596 (setq org-table-local-parameters
2597 (append org-table-local-parameters al2
))))))
2599 (defun org-table-goto-field (ref &optional create-column-p
)
2600 "Move point to a specific field in the current table.
2602 REF is either the name of a field its absolute reference, as
2603 a string. No column is created unless CREATE-COLUMN-P is
2604 non-nil. If it is a function, it is called with the column
2605 number as its argument as is used as a predicate to know if the
2606 column can be created.
2608 This function assumes the table is already analyzed (i.e., using
2609 `org-table-analyze')."
2612 ((cdr (assoc ref org-table-named-field-locations
)))
2613 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
2614 (list (condition-case nil
2615 (aref org-table-dlines
2616 (string-to-number (match-string 1 ref
)))
2617 (error (user-error "Invalid row number in %s" ref
)))
2618 (string-to-number (match-string 2 ref
))))
2619 (t (user-error "Unknown field: %s" ref
))))
2620 (line (car coordinates
))
2621 (column (nth 1 coordinates
))
2622 (create-new-column (if (functionp create-column-p
)
2623 (funcall create-column-p column
)
2626 (goto-char org-table-current-begin-pos
)
2628 (org-table-goto-column column nil create-new-column
))))
2631 (defun org-table-maybe-recalculate-line ()
2632 "Recompute the current line if marked for it, and if we haven't just done it."
2634 (and org-table-allow-automatic-line-recalculation
2635 (not (and (memq last-command org-recalc-commands
)
2636 (eq org-last-recalc-line
(line-beginning-position))))
2637 (save-excursion (beginning-of-line 1)
2638 (looking-at org-table-auto-recalculate-regexp
))
2639 (org-table-recalculate) t
))
2641 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2642 (defsubst org-set-calc-mode
(var &optional value
)
2644 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2645 ("R" calc-angle-mode rad
)
2646 ("F" calc-prefer-frac t
)
2647 ("S" calc-symbolic-mode t
)))
2648 value
(nth 2 var
) var
(nth 1 var
)))
2649 (if (memq var org-tbl-calc-modes
)
2650 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2651 (cons var
(cons value org-tbl-calc-modes
)))
2655 (defun org-table-eval-formula (&optional arg equation
2656 suppress-align suppress-const
2657 suppress-store suppress-analysis
)
2658 "Replace the table field value at the cursor by the result of a calculation.
2660 In a table, this command replaces the value in the current field with the
2661 result of a formula. It also installs the formula as the \"current\" column
2662 formula, by storing it in a special line below the table. When called
2663 with a `\\[universal-argument]' prefix the formula is installed as a \
2666 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2667 insert the active equation for the field
2668 back into the current field, so that it can be edited there. This is \
2670 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2671 check the referenced fields.
2673 When called, the command first prompts for a formula, which is read in
2674 the minibuffer. Previously entered formulas are available through the
2675 history list, and the last used formula is offered as a default.
2676 These stored formulas are adapted correctly when moving, inserting, or
2677 deleting columns with the corresponding commands.
2679 The formula can be any algebraic expression understood by the Calc package.
2680 For details, see the Org mode manual.
2682 This function can also be called from Lisp programs and offers
2683 additional arguments: EQUATION can be the formula to apply. If this
2684 argument is given, the user will not be prompted.
2686 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2689 SUPPRESS-CONST suppresses the interpretation of constants in the
2690 formula, assuming that this has been done already outside the
2693 SUPPRESS-STORE means the formula should not be stored, either
2694 because it is already stored, or because it is a modified
2695 equation that should not overwrite the stored one.
2697 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2700 (unless suppress-analysis
2701 (org-table-check-inside-data-field)
2702 (org-table-analyze))
2703 (if (equal arg
'(16))
2704 (let ((eq (org-table-current-field-formula)))
2705 (org-table-get-field nil eq
)
2707 (setq org-table-may-need-update t
))
2709 (ndown (if (integerp arg
) arg
1))
2710 (org-table-automatic-realign nil
)
2711 (case-fold-search nil
)
2713 (formula (if (and equation suppress-store
)
2715 (org-table-get-formula equation
(equal arg
'(4)))))
2716 (n0 (org-table-current-column))
2717 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2718 (numbers nil
) ; was a variable, now fixed default
2720 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2721 duration duration-output-format
)
2722 ;; Parse the format string. Since we have a lot of modes, this is
2723 ;; a lot of work. However, I think calc still uses most of the time.
2724 (if (string-match ";" formula
)
2725 (let ((tmp (org-split-string formula
";")))
2726 (setq formula
(car tmp
)
2727 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2729 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2730 (setq c
(string-to-char (match-string 1 fmt
))
2731 n
(string-to-number (match-string 2 fmt
)))
2733 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2734 (setq org-tbl-calc-modes
2737 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2738 (?s . sci
) (?e . eng
))))
2740 (setq fmt
(replace-match "" t t fmt
)))
2741 (if (string-match "[tTU]" fmt
)
2742 (let ((ff (match-string 0 fmt
)))
2743 (setq duration t numbers t
2744 duration-output-format
2745 (cond ((equal ff
"T") nil
)
2746 ((equal ff
"t") org-table-duration-custom-format
)
2747 ((equal ff
"U") 'hh
:mm
))
2748 fmt
(replace-match "" t t fmt
))))
2749 (if (string-match "N" fmt
)
2751 fmt
(replace-match "" t t fmt
)))
2752 (if (string-match "L" fmt
)
2754 fmt
(replace-match "" t t fmt
)))
2755 (if (string-match "E" fmt
)
2757 fmt
(replace-match "" t t fmt
)))
2758 (while (string-match "[DRFS]" fmt
)
2759 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2760 (setq fmt
(replace-match "" t t fmt
)))
2761 (unless (string-match "\\S-" fmt
)
2763 (when (and (not suppress-const
) org-table-formula-use-constants
)
2764 (setq formula
(org-table-formula-substitute-names formula
)))
2765 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2766 (setq formula
(org-table-formula-handle-first/last-rc formula
))
2768 (setq fields
(org-split-string
2770 (buffer-substring-no-properties
2771 (line-beginning-position) (line-end-position)))
2773 ;; replace fields with duration values if relevant
2776 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2779 (setq fields
(mapcar
2781 (if (string-match "\\S-" x
)
2782 (number-to-string (string-to-number x
))
2785 (setq ndown
(1- ndown
))
2786 (setq form
(copy-sequence formula
)
2787 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2788 (if (and lispp literal
) (setq lispp
'literal
))
2790 ;; Insert row and column number of formula result field
2791 (while (string-match "[@$]#" form
)
2796 (if (equal (substring form
(match-beginning 0)
2797 (1+ (match-beginning 0)))
2799 (org-table-current-dline)
2800 (org-table-current-column))))
2803 ;; Check for old vertical references
2804 (org-table--error-on-old-row-references form
)
2805 ;; Insert remote references
2806 (setq form
(org-table-remote-reference-indirection form
))
2807 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2811 (org-table-make-reference
2812 (let ((rmtrng (org-table-get-remote-range
2813 (match-string 1 form
) (match-string 2 form
))))
2816 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2817 (org-table-time-string-to-seconds rmtrng
))
2819 keep-empty numbers lispp
))
2821 ;; Insert complex ranges
2822 (while (and (string-match org-table-range-regexp form
)
2823 (> (length (match-string 0 form
)) 1))
2826 (org-table-get-range
2827 (match-string 0 form
) org-table-current-begin-pos n0
)))
2830 (org-table-make-reference
2831 ;; possibly handle durations
2834 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2835 (org-table-time-string-to-seconds formrg
))
2837 keep-empty numbers lispp
)))
2838 (if (not (save-match-data
2839 (string-match (regexp-quote form
) formrpl
)))
2840 (setq form
(replace-match formrpl t t form
))
2841 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2842 ;; Insert simple ranges, i.e. included in the current row.
2843 (while (string-match
2844 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2849 (org-table-make-reference
2851 (+ (if (match-end 2) n0
0)
2852 (string-to-number (match-string 1 form
))
2854 (+ (if (match-end 4) n0
0)
2855 (string-to-number (match-string 3 form
))))
2856 keep-empty numbers lispp
))
2859 ;; Insert the references to fields in same row
2860 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2861 (setq n
(+ (string-to-number (match-string 1 form
))
2862 (if (match-end 2) n0
0))
2863 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2864 formrpl
(save-match-data
2865 (org-table-make-reference
2866 x keep-empty numbers lispp
)))
2869 (string-match (regexp-quote formula
) formrpl
)))
2870 (user-error "Invalid field specifier \"%s\""
2871 (match-string 0 form
)))
2872 (setq form
(replace-match formrpl t t form
)))
2875 (setq ev
(condition-case nil
2876 (eval (eval (read form
)))
2878 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2879 ev
(if duration
(org-table-time-seconds-to-string
2880 (string-to-number ev
)
2881 duration-output-format
) ev
))
2883 ;; Use <...> time-stamps so that Calc can handle them.
2885 (replace-regexp-in-string org-ts-regexp-inactive
"<\\1>" form
))
2886 ;; Internationalize local time-stamps by setting locale to
2889 (replace-regexp-in-string
2892 (let ((system-time-locale "C"))
2894 (org-time-stamp-format
2895 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2896 (apply #'encode-time
2897 (save-match-data (org-parse-time-string ts
))))))
2900 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2902 (calc-eval (cons form org-tbl-calc-modes
)
2903 (when (and (not keep-empty
) numbers
) 'num
)))
2904 ev
(if duration
(org-table-time-seconds-to-string
2905 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2906 (string-to-number (org-table-time-string-to-seconds ev
))
2907 (string-to-number ev
))
2908 duration-output-format
)
2911 (when org-table-formula-debug
2912 (with-output-to-temp-buffer "*Substitution History*"
2913 (princ (format "Substitution history of formula
2917 $1-> %s\n" orig formula form0 form
))
2919 (princ (format " %s^\nError: %s"
2920 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2921 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2923 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2924 (setq bw
(get-buffer-window "*Substitution History*"))
2925 (org-fit-window-to-buffer bw
)
2926 (unless (and (called-interactively-p 'any
) (not ndown
))
2927 (unless (let (inhibit-redisplay)
2928 (y-or-n-p "Debugging Formula. Continue to next? "))
2930 (user-error "Abort"))
2933 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2934 (org-table-justify-field-maybe
2935 (format org-table-formula-field-format
2937 ((not (stringp ev
)) ev
)
2938 (fmt (format fmt
(string-to-number ev
)))
2939 ;; Replace any active time stamp in the result with
2940 ;; an inactive one. Dates in tables are likely
2941 ;; piece of regular data, not meant to appear in the
2943 (t (replace-regexp-in-string org-ts-regexp
"[\\1]" ev
)))))
2944 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2945 (call-interactively 'org-return
)
2947 (and down
(org-table-maybe-recalculate-line))
2948 (or suppress-align
(and org-table-may-need-update
2949 (org-table-align))))))
2951 (defun org-table-put-field-property (prop value
)
2953 (put-text-property (progn (skip-chars-backward "^|") (point))
2954 (progn (skip-chars-forward "^|") (point))
2957 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2958 "Get a calc vector from a column, according to descriptor DESC.
2960 Optional arguments TBEG and COL can give the beginning of the table and
2961 the current column, to avoid unnecessary parsing.
2963 HIGHLIGHT means just highlight the range.
2965 When CORNERS-ONLY is set, only return the corners of the range as
2966 a list (line1 column1 line2 column2) where line1 and line2 are
2967 line numbers relative to beginning of table, or TBEG, and column1
2968 and column2 are table column numbers."
2969 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc
)
2970 (replace-regexp-in-string "\\$" "@0$" desc
)
2972 (col (or col
(org-table-current-column)))
2973 (tbeg (or tbeg
(org-table-begin)))
2974 (thisline (count-lines tbeg
(line-beginning-position))))
2975 (unless (string-match org-table-range-regexp desc
)
2976 (user-error "Invalid table range specifier `%s'" desc
))
2977 (let ((rangep (match-end 3))
2978 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2979 (or (save-match-data
2980 (and (org-string-nw-p r
)
2981 (org-table--descriptor-line r thisline
)))
2983 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
2984 (or (save-match-data
2985 (and (org-string-nw-p r
)
2986 (org-table--descriptor-line r thisline
)))
2988 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
2989 (if (or (not c
) (= (string-to-number c
) 0)) col
2990 (+ (string-to-number c
)
2991 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
2992 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
2993 (if (or (not c
) (= (string-to-number c
) 0)) col
2994 (+ (string-to-number c
)
2995 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
2997 (if (and (not corners-only
)
2998 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
3001 (forward-line (- r1 thisline
))
3002 (while (not (looking-at org-table-dataline-regexp
))
3004 (prog1 (org-trim (org-table-get-field c1
))
3005 (when highlight
(org-table-highlight-rectangle))))
3006 ;; A range, return a vector. First sort the numbers to get
3007 ;; a regular rectangle.
3008 (let ((first-row (min r1 r2
))
3009 (last-row (max r1 r2
))
3010 (first-column (min c1 c2
))
3011 (last-column (max c1 c2
)))
3012 (if corners-only
(list first-row first-column last-row last-column
)
3013 ;; Copy the range values into a list.
3014 (forward-line (- first-row thisline
))
3015 (while (not (looking-at org-table-dataline-regexp
))
3017 (cl-incf first-row
))
3018 (org-table-goto-column first-column
)
3019 (let ((beg (point)))
3020 (forward-line (- last-row first-row
))
3021 (while (not (looking-at org-table-dataline-regexp
))
3023 (org-table-goto-column last-column
)
3024 (let ((end (point)))
3026 (org-table-highlight-rectangle
3027 beg
(progn (skip-chars-forward "^|\n") (point))))
3028 ;; Return string representation of calc vector.
3031 (org-table-copy-region beg end
))))))))))))
3033 (defun org-table--descriptor-line (desc cline
)
3034 "Return relative line number corresponding to descriptor DESC.
3035 The cursor is currently in relative line number CLINE."
3036 (if (string-match "\\`[0-9]+\\'" desc
)
3037 (aref org-table-dlines
(string-to-number desc
))
3038 (when (or (not (string-match
3039 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3042 (and (not (match-end 3)) (not (match-end 6)))
3043 (and (match-end 3) (match-end 6) (not (match-end 5))))
3044 (user-error "Invalid row descriptor `%s'" desc
))
3045 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3046 (hdir (match-string 2 desc
))
3047 (odir (match-string 5 desc
))
3048 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
3049 (rel (and (match-end 6)
3050 (or (and (match-end 1) (not (match-end 3)))
3052 (when (and hn
(not hdir
))
3055 (when (eq (aref org-table-current-line-types
0) 'hline
) (cl-decf hn
)))
3056 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
3059 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
3062 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
3065 (defun org-table--row-type (type n i backwards relative desc
)
3066 "Return relative line of Nth row with type TYPE.
3067 Search starts from relative line I. When BACKWARDS in non-nil,
3068 look before I. When RELATIVE is non-nil, the reference is
3069 relative. DESC is the original descriptor that started the
3070 search, as a string."
3071 (let ((l (length org-table-current-line-types
)))
3074 (while (and (cl-incf i
(if backwards -
1 1))
3077 (not (eq (aref org-table-current-line-types i
) type
))
3078 ;; We are going to cross a hline. Check if this is
3079 ;; an authorized move.
3082 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
3083 ((eq org-table-relative-ref-may-cross-hline t
))
3084 ((eq org-table-relative-ref-may-cross-hline
'error
)
3085 (user-error "Row descriptor %s crosses hline" desc
))
3086 (t (cl-decf i
(if backwards -
1 1)) ; Step back.
3087 (throw :exit nil
)))))))
3088 (cond ((or (< i
0) (>= i l
))
3089 (user-error "Row descriptor %s leads outside table" desc
))
3090 ;; The last hline doesn't exist. Instead, point to last row
3092 ((= i
(1- l
)) (1- i
))
3095 (defun org-table--error-on-old-row-references (s)
3096 (when (string-match "&[-+0-9I]" s
)
3097 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3099 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3100 "Convert list ELEMENTS to something appropriate to insert into formula.
3101 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3102 NUMBERS indicates that everything should be converted to numbers.
3103 LISPP non-nil means to return something appropriate for a Lisp
3104 list, `literal' is for the format specifier L."
3105 ;; Calc nan (not a number) is used for the conversion of the empty
3106 ;; field to a reference for several reasons: (i) It is accepted in a
3107 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3108 ;; (ii) In a single field (not in range) it can be distinguished
3109 ;; from "(nan)" which is the reference made from a single field
3110 ;; containing "nan".
3111 (if (stringp elements
)
3114 (if (eq lispp
'literal
)
3116 (if (and (eq elements
"") (not keep-empty
))
3119 (if numbers
(string-to-number elements
) elements
))))
3120 (if (string-match "\\S-" elements
)
3122 (when numbers
(setq elements
(number-to-string
3123 (string-to-number elements
))))
3124 (concat "(" elements
")"))
3125 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3130 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3132 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3136 (if (eq lispp
'literal
)
3138 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3140 (concat "[" (mapconcat
3142 (if (string-match "\\S-" x
)
3144 (number-to-string (string-to-number x
))
3146 (if (or (not keep-empty
) numbers
) "0" "nan")))
3150 (defun org-table-message-once-per-second (t1 &rest args
)
3151 "If there has been more than one second since T1, display message.
3152 ARGS are passed as arguments to the `message' function. Returns
3153 current time if a message is printed, otherwise returns T1. If
3154 T1 is nil, always messages."
3155 (let ((curtime (current-time)))
3156 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3157 (progn (apply 'message args
)
3162 (defun org-table-recalculate (&optional all noalign
)
3163 "Recalculate the current table line by applying all stored formulas.
3165 With prefix arg ALL, do this for all lines in the table.
3167 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3168 if ALL is the symbol `iterate',
3169 recompute the table until it no longer changes.
3171 If NOALIGN is not nil, do not re-align the table after the computations
3172 are done. This is typically used internally to save time, if it is
3173 known that the table will be realigned a little later anyway."
3175 (unless (memq this-command org-recalc-commands
)
3176 (push this-command org-recalc-commands
))
3177 (unless (org-at-table-p) (user-error "Not at a table"))
3178 (if (or (eq all
'iterate
) (equal all
'(16)))
3181 (let* ((eqlist (sort (org-table-get-stored-formulas)
3182 (lambda (a b
) (string< (car a
) (car b
)))))
3183 (inhibit-redisplay (not debug-on-error
))
3184 (line-re org-table-dataline-regexp
)
3185 (log-first-time (current-time))
3186 (log-last-time log-first-time
)
3188 beg end eqlcol eqlfield
)
3189 ;; Insert constants in all formulas.
3191 (org-table-save-field
3192 ;; Expand equations, then split the equation list between
3193 ;; column formulas and field formulas.
3195 (let* ((rhs (org-table-formula-substitute-names
3196 (org-table-formula-handle-first/last-rc
(cdr eq
))))
3199 (org-table-formula-handle-first/last-rc
3201 ((string-match "\\`@-?I+" old-lhs
)
3202 (user-error "Can't assign to hline relative reference"))
3203 ((string-match "\\`$[<>]" old-lhs
)
3204 (let ((new (org-table-formula-handle-first/last-rc
3206 (when (assoc new eqlist
)
3207 (user-error "\"%s=\" formula tries to overwrite \
3208 existing formula for column %s"
3213 (if (string-match-p "\\`\\$[0-9]+\\'" lhs
)
3214 (push (cons lhs rhs
) eqlcol
)
3215 (push (cons lhs rhs
) eqlfield
))))
3216 (setq eqlcol
(nreverse eqlcol
))
3217 ;; Expand ranges in lhs of formulas
3218 (setq eqlfield
(org-table-expand-lhs-ranges (nreverse eqlfield
)))
3219 ;; Get the correct line range to process.
3222 (setq end
(copy-marker (org-table-end)))
3223 (goto-char (setq beg org-table-current-begin-pos
))
3225 ((re-search-forward org-table-calculate-mark-regexp end t
)
3226 ;; This is a table with marked lines, compute selected
3228 (setq line-re org-table-recalculate-regexp
))
3229 ;; Move forward to the first non-header line.
3230 ((and (re-search-forward org-table-dataline-regexp end t
)
3231 (re-search-forward org-table-hline-regexp end t
)
3232 (re-search-forward org-table-dataline-regexp end t
))
3233 (setq beg
(match-beginning 0)))
3234 ;; Just leave BEG at the start of the table.
3236 (setq beg
(line-beginning-position)
3237 end
(copy-marker (line-beginning-position 2))))
3239 ;; Mark named fields untouchable. Also check if several
3240 ;; field/range formulas try to set the same field.
3241 (remove-text-properties beg end
'(:org-untouchable t
))
3242 (let ((current-line (count-lines org-table-current-begin-pos
3243 (line-beginning-position)))
3245 (dolist (eq eqlfield
)
3246 (let* ((name (car eq
))
3247 (location (assoc name org-table-named-field-locations
))
3248 (eq-line (or (nth 1 location
)
3249 (and (string-match "\\`@\\([0-9]+\\)" name
)
3250 (aref org-table-dlines
3252 (match-string 1 name
))))))
3255 ;; Turn field coordinates associated to NAME
3256 ;; into an absolute reference.
3258 (org-table-line-to-dline eq-line
)
3261 (when (member reference seen-fields
)
3262 (user-error "Several field/range formulas try to set %s"
3264 (push reference seen-fields
)
3265 (when (or all
(eq eq-line current-line
))
3266 (org-table-goto-field name
)
3267 (org-table-put-field-property :org-untouchable t
)))))
3268 ;; Evaluate the column formulas, but skip fields covered by
3271 (while (re-search-forward line-re end t
)
3272 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3273 ;; Unprotected line, recalculate.
3277 (org-table-message-once-per-second
3279 "Re-applying formulas to full table...(line %d)" cnt
)))
3280 (if (markerp org-last-recalc-line
)
3281 (move-marker org-last-recalc-line
(line-beginning-position))
3282 (setq org-last-recalc-line
3283 (copy-marker (line-beginning-position))))
3284 (dolist (entry eqlcol
)
3285 (goto-char org-last-recalc-line
)
3286 (org-table-goto-column
3287 (string-to-number (substring (car entry
) 1)) nil
'force
)
3288 (unless (get-text-property (point) :org-untouchable
)
3289 (org-table-eval-formula
3290 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
3291 ;; Evaluate the field formulas.
3292 (dolist (eq eqlfield
)
3293 (let ((reference (car eq
))
3296 (org-table-message-once-per-second
3297 (and all log-last-time
)
3298 "Re-applying formula to field: %s" (car eq
)))
3299 (org-table-goto-field
3301 ;; Possibly create a new column, as long as
3302 ;; `org-table-formula-create-columns' allows it.
3303 (let ((column-count (progn (end-of-line)
3304 (1- (org-table-current-column)))))
3306 (when (> column
1000)
3307 (user-error "Formula column target too large"))
3308 (and (> column column-count
)
3309 (or (eq org-table-formula-create-columns t
)
3310 (and (eq org-table-formula-create-columns
'warn
)
3312 (org-display-warning
3313 "Out-of-bounds formula added columns")
3315 (and (eq org-table-formula-create-columns
'prompt
)
3317 "Out-of-bounds formula. Add columns? ")))))))
3318 (org-table-eval-formula nil formula t t t t
))))
3319 ;; Clean up markers and internal text property.
3320 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3321 (set-marker end nil
)
3323 (when org-table-may-need-update
(org-table-align))
3325 (org-table-message-once-per-second
3326 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
3327 (org-table-message-once-per-second
3328 (and all log-first-time
) "Re-applying formulas... done")))))
3331 (defun org-table-iterate (&optional arg
)
3332 "Recalculate the table until it does not change anymore.
3333 The maximum number of iterations is 10, but you can choose a different value
3334 with the prefix ARG."
3336 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3338 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3343 (org-table-recalculate 'all
)
3344 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3345 (if (not (string= lasttbl thistbl
))
3346 (setq lasttbl thistbl
)
3348 (message "Convergence after %d iterations" i
)
3349 (message "Table was already stable"))
3351 (user-error "No convergence after %d iterations" i
))))
3354 (defun org-table-recalculate-buffer-tables ()
3355 "Recalculate all tables in the current buffer."
3357 (org-with-wide-buffer
3358 (org-table-map-tables
3360 ;; Reason for separate `org-table-align': When repeating
3361 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3363 (org-table-recalculate t t
)
3368 (defun org-table-iterate-buffer-tables ()
3369 "Iterate all tables in the buffer, to converge inter-table dependencies."
3373 (checksum (md5 (buffer-string)))
3375 (org-with-wide-buffer
3379 (org-table-map-tables (lambda () (org-table-recalculate t t
)) t
)
3380 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3382 (org-table-map-tables #'org-table-align t
)
3383 (message "Convergence after %d iterations" (- imax i
))
3385 (setq checksum c1
)))
3386 (org-table-map-tables #'org-table-align t
)
3387 (user-error "No convergence after %d iterations" imax
)))))
3389 (defun org-table-calc-current-TBLFM (&optional arg
)
3390 "Apply the #+TBLFM in the line at point to the table."
3392 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3393 (let ((formula (buffer-substring
3394 (line-beginning-position)
3395 (line-end-position))))
3397 ;; Insert a temporary formula at right after the table
3398 (goto-char (org-table-TBLFM-begin))
3399 (let ((s (point-marker)))
3400 (insert formula
"\n")
3401 (let ((e (point-marker)))
3402 ;; Recalculate the table.
3403 (beginning-of-line 0) ; move to the inserted line
3404 (skip-chars-backward " \r\n\t")
3406 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3407 ;; Delete the formula inserted temporarily.
3410 (set-marker e nil
)))))))
3412 (defun org-table-TBLFM-begin ()
3413 "Find the beginning of the TBLFM lines and return its position.
3414 Return nil when the beginning of TBLFM line was not found."
3416 (when (progn (forward-line 1)
3417 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3418 (line-beginning-position 2))))
3420 (defun org-table-expand-lhs-ranges (equations)
3421 "Expand list of formulas.
3422 If some of the RHS in the formulas are ranges or a row reference,
3423 expand them to individual field equations for each field. This
3424 function assumes the table is already analyzed (i.e., using
3425 `org-table-analyze')."
3427 (dolist (e equations
(nreverse res
))
3431 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3432 ;; This just refers to one fixed field.
3434 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3435 ;; This just refers to one fixed named field.
3437 ((string-match-p "\\`\\$[0-9]+\\'" lhs
)
3438 ;; Column formulas are treated specially and are not
3441 ((string-match "\\`@[0-9]+\\'" lhs
)
3442 (dotimes (ic org-table-current-ncol
)
3443 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3447 (let* ((range (org-table-get-range
3448 lhs org-table-current-begin-pos
1 nil
'corners
))
3449 (r1 (org-table-line-to-dline (nth 0 range
)))
3451 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3453 (cl-loop for ir from r1 to r2 do
3454 (cl-loop for ic from c1 to c2 do
3455 (push (cons (propertize
3456 (format "@%d$%d" ir ic
) :orig-eqn e
)
3460 (defun org-table-formula-handle-first/last-rc
(s)
3461 "Replace @<, @>, $<, $> with first/last row/column of the table.
3462 So @< and $< will always be replaced with @1 and $1, respectively.
3463 The advantage of these special markers are that structure editing of
3464 the table will not change them, while @1 and $1 will be modified
3465 when a line/row is swapped out of that privileged position. So for
3466 formulas that use a range of rows or columns, it may often be better
3467 to anchor the formula with \"I\" row markers, or to offset from the
3468 borders of the table using the @< @> $< $> makers."
3469 (let (n nmax len char
(start 0))
3470 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3473 (setq start
(match-end 3))
3474 (setq nmax
(if (equal (match-string 1 s
) "@")
3475 (1- (length org-table-dlines
))
3476 org-table-current-ncol
)
3477 len
(- (match-end 2) (match-beginning 2))
3478 char
(string-to-char (match-string 2 s
))
3482 (if (or (< n
1) (> n nmax
))
3483 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3484 (match-string 0 s
) s
))
3485 (setq start
(match-beginning 0))
3486 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3489 (defun org-table-formula-substitute-names (f)
3490 "Replace $const with values in string F."
3492 (pp (/= (string-to-char f
) ?
'))
3493 (duration (string-match-p ";.*[Tt].*\\'" f
))
3494 (new (replace-regexp-in-string ; Check for column names.
3495 org-table-column-name-regexp
3497 (concat "$" (cdr (assoc (match-string 1 m
)
3498 org-table-column-names
))))
3500 ;; Parameters and constants.
3503 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3505 (if (match-end 2) (setq start
(match-end 2))
3507 ;; When a duration is expected, convert value on the fly.
3510 (let ((v (org-table-get-constant (match-string 1 new
))))
3511 (if (and (org-string-nw-p v
) duration
)
3512 (org-table-time-string-to-seconds v
)
3515 (setq new
(replace-match
3516 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3517 (if org-table-formula-debug
(propertize new
:orig-formula f
) new
)))
3519 (defun org-table-get-constant (const)
3520 "Find the value for a parameter or constant in a formula.
3521 Parameters get priority."
3522 (or (cdr (assoc const org-table-local-parameters
))
3523 (cdr (assoc const org-table-formula-constants-local
))
3524 (cdr (assoc const org-table-formula-constants
))
3525 (and (fboundp 'constants-get
) (constants-get const
))
3526 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3527 (org-entry-get nil
(substring const
5) 'inherit
))
3530 (defvar org-table-fedit-map
3531 (let ((map (make-sparse-keymap)))
3532 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3533 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3534 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3535 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3536 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3537 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3538 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3539 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3540 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3541 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3542 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3543 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3544 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3545 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3546 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3547 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3548 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3549 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3550 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3551 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3554 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3556 ["Finish and Install" org-table-fedit-finish t
]
3557 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3558 ["Abort" org-table-fedit-abort t
]
3560 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3561 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3563 "Shift Reference at Point"
3564 ["Up" org-table-fedit-ref-up t
]
3565 ["Down" org-table-fedit-ref-down t
]
3566 ["Left" org-table-fedit-ref-left t
]
3567 ["Right" org-table-fedit-ref-right t
]
3569 "Change Test Row for Column Formulas"
3570 ["Up" org-table-fedit-line-up t
]
3571 ["Down" org-table-fedit-line-down t
]
3573 ["Scroll Table Window" org-table-fedit-scroll t
]
3574 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3575 ["Show Table Grid" org-table-fedit-toggle-coordinates
3576 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3577 org-table-overlay-coordinates
)]
3579 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3580 :style toggle
:selected org-table-buffer-is-an
]))
3583 (defvar org-table--fedit-source nil
3584 "Position of the TBLFM line being edited.")
3587 (defun org-table-edit-formulas ()
3588 "Edit the formulas of the current table in a separate buffer."
3590 (let ((at-tblfm (org-at-TBLFM-p)))
3591 (unless (or at-tblfm
(org-at-table-p))
3592 (user-error "Not at a table"))
3594 ;; Move point within the table before analyzing it.
3595 (when at-tblfm
(re-search-backward "^[ \t]*|"))
3596 (org-table-analyze))
3597 (let ((key (org-table-current-field-formula 'key
'noerror
))
3598 (eql (sort (org-table-get-stored-formulas t
(and at-tblfm
(point)))
3599 #'org-table-formula-less-p
))
3600 (pos (point-marker))
3601 (source (copy-marker (line-beginning-position)))
3603 (wc (current-window-configuration))
3604 (sel-win (selected-window))
3605 (titles '((column .
"# Column Formulas\n")
3606 (field .
"# Field and Range Formulas\n")
3607 (named .
"# Named Field Formulas\n"))))
3608 (org-switch-to-buffer-other-window "*Edit Formulas*")
3610 ;; Keep global-font-lock-mode from turning on font-lock-mode
3611 (let ((font-lock-global-modes '(not fundamental-mode
)))
3613 (setq-local font-lock-global-modes
(list 'not major-mode
))
3614 (setq-local org-pos pos
)
3615 (setq-local org-table--fedit-source source
)
3616 (setq-local org-window-configuration wc
)
3617 (setq-local org-selected-window sel-win
)
3618 (use-local-map org-table-fedit-map
)
3619 (add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3620 (easy-menu-add org-table-fedit-menu
)
3621 (setq startline
(org-current-line))
3624 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry
))
3626 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3628 (title (assq type titles
)))
3630 (unless (bobp) (insert "\n"))
3632 (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3633 (setq titles
(remove title titles
)))
3634 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3636 (if (memq (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3637 (car entry
) " = " (cdr entry
) "\n")))
3638 (remove-text-properties 0 (length s
) '(face nil
) s
)
3640 (when (eq org-table-use-standard-references t
)
3641 (org-table-fedit-toggle-ref-type))
3642 (org-goto-line startline
)
3643 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3644 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3645 See menu for more commands.")))))
3647 (defun org-table-fedit-post-command ()
3648 (when (not (memq this-command
'(lisp-complete-symbol)))
3649 (let ((win (selected-window)))
3651 (ignore-errors (org-table-show-reference))
3652 (select-window win
)))))
3654 (defun org-table-formula-to-user (s)
3655 "Convert a formula from internal to user representation."
3656 (if (eq org-table-use-standard-references t
)
3657 (org-table-convert-refs-to-an s
)
3660 (defun org-table-formula-from-user (s)
3661 "Convert a formula from user to internal representation."
3662 (if org-table-use-standard-references
3663 (org-table-convert-refs-to-rc s
)
3666 (defun org-table-convert-refs-to-rc (s)
3667 "Convert spreadsheet references from A7 to @7$28.
3668 Works for single references, but also for entire formulas and even the
3671 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3674 ;; format match, just advance
3675 (setq start
(match-end 0)))
3676 ((and (> (match-beginning 0) 0)
3677 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3678 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3679 ;; 3.e5 or something like this.
3680 (setq start
(match-end 0)))
3681 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3682 ;; (member (match-string 1 s)
3683 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3685 ;; function name, just advance
3686 (setq start
(match-end 0)))
3688 (setq start
(match-beginning 0)
3690 (if (equal (match-string 2 s
) "&")
3691 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3693 (string-to-number (match-string 2 s
))
3694 (org-letters-to-number (match-string 1 s
))))
3698 (defun org-table-convert-refs-to-an (s)
3699 "Convert spreadsheet references from to @7$28 to AB7.
3700 Works for single references, but also for entire formulas and even the
3702 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3703 (setq s
(replace-match
3705 (org-number-to-letters
3706 (string-to-number (match-string 2 s
)))
3707 (string-to-number (match-string 1 s
)))
3709 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3710 (setq s
(replace-match (concat "\\1"
3711 (org-number-to-letters
3712 (string-to-number (match-string 2 s
))) "&")
3716 (defun org-letters-to-number (s)
3717 "Convert a base 26 number represented by letters into an integer.
3718 For example: AB -> 28."
3721 (while (> (length s
) 0)
3722 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3726 (defun org-number-to-letters (n)
3727 "Convert an integer into a base 26 number represented by letters.
3728 For example: 28 -> AB."
3731 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3735 (defun org-table-time-string-to-seconds (s)
3736 "Convert a time string into numerical duration in seconds.
3737 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3738 If S is a string representing a number, keep this number."
3741 (let (hour minus min sec res
)
3743 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3744 (setq minus
(< 0 (length (match-string 1 s
)))
3745 hour
(string-to-number (match-string 2 s
))
3746 min
(string-to-number (match-string 3 s
))
3747 sec
(string-to-number (match-string 4 s
)))
3749 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3750 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3751 ((and (not (string-match org-ts-regexp-both s
))
3752 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3753 (setq minus
(< 0 (length (match-string 1 s
)))
3754 hour
(string-to-number (match-string 2 s
))
3755 min
(string-to-number (match-string 3 s
)))
3757 (setq res
(- (+ (* hour
3600) (* min
60))))
3758 (setq res
(+ (* hour
3600) (* min
60)))))
3759 (t (setq res
(string-to-number s
))))
3760 (number-to-string res
))))
3762 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3763 "Convert a number of seconds to a time string.
3764 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3765 minutes or seconds."
3766 (let* ((secs0 (abs secs
))
3768 (cond ((eq output-format
'days
)
3769 (format "%.3f" (/ (float secs0
) 86400)))
3770 ((eq output-format
'hours
)
3771 (format "%.2f" (/ (float secs0
) 3600)))
3772 ((eq output-format
'minutes
)
3773 (format "%.1f" (/ (float secs0
) 60)))
3774 ((eq output-format
'seconds
)
3775 (format "%d" secs0
))
3776 ((eq output-format
'hh
:mm
)
3778 (substring (format-seconds
3779 (if org-table-duration-hour-zero-padding
3780 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3784 (if org-table-duration-hour-zero-padding
3785 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3787 (if (< secs
0) (concat "-" res
) res
)))
3789 (defun org-table-fedit-convert-buffer (function)
3790 "Convert all references in this buffer, using FUNCTION."
3791 (let ((origin (copy-marker (line-beginning-position))))
3792 (goto-char (point-min))
3794 (insert (funcall function
(buffer-substring (point) (line-end-position))))
3795 (delete-region (point) (line-end-position))
3798 (set-marker origin nil
)))
3800 (defun org-table-fedit-toggle-ref-type ()
3801 "Convert all references in the buffer from B3 to @3$2 and back."
3803 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
3804 (org-table-fedit-convert-buffer
3805 (if org-table-buffer-is-an
3806 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3807 (message "Reference type switched to %s"
3808 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3810 (defun org-table-fedit-ref-up ()
3811 "Shift the reference at point one row/hline up."
3813 (org-table-fedit-shift-reference 'up
))
3814 (defun org-table-fedit-ref-down ()
3815 "Shift the reference at point one row/hline down."
3817 (org-table-fedit-shift-reference 'down
))
3818 (defun org-table-fedit-ref-left ()
3819 "Shift the reference at point one field to the left."
3821 (org-table-fedit-shift-reference 'left
))
3822 (defun org-table-fedit-ref-right ()
3823 "Shift the reference at point one field to the right."
3825 (org-table-fedit-shift-reference 'right
))
3827 (defun org-table-fedit-shift-reference (dir)
3829 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3830 (if (memq dir
'(left right
))
3831 (org-rematch-and-replace 1 (eq dir
'left
))
3832 (user-error "Cannot shift reference in this direction")))
3833 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3834 ;; A B3-like reference
3835 (if (memq dir
'(up down
))
3836 (org-rematch-and-replace 2 (eq dir
'up
))
3837 (org-rematch-and-replace 1 (eq dir
'left
))))
3839 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3840 ;; An internal reference
3841 (if (memq dir
'(up down
))
3842 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3843 (org-rematch-and-replace 5 (eq dir
'left
))))))
3845 (defun org-rematch-and-replace (n &optional decr hline
)
3846 "Re-match the group N, and replace it with the shifted reference."
3847 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3848 (goto-char (match-beginning n
))
3849 (and (looking-at (regexp-quote (match-string n
)))
3850 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3853 (defun org-table-shift-refpart (ref &optional decr hline
)
3854 "Shift a reference part REF.
3855 If DECR is set, decrease the references row/column, else increase.
3856 If HLINE is set, this may be a hline reference, it certainly is not
3857 a translation reference."
3859 (let* ((sign (string-match "^[-+]" ref
)) n
)
3861 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3863 ((and hline
(string-match "^I+" ref
))
3864 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3865 (setq n
(+ n
(if decr -
1 1)))
3866 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3868 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3870 (concat sign
(make-string n ?I
)))
3872 ((string-match "^[0-9]+" ref
)
3873 (setq n
(string-to-number (concat sign ref
)))
3874 (setq n
(+ n
(if decr -
1 1)))
3876 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3877 (number-to-string (max 1 n
))))
3879 ((string-match "^[a-zA-Z]+" ref
)
3880 (org-number-to-letters
3881 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3883 (t (user-error "Cannot shift reference"))))))
3885 (defun org-table-fedit-toggle-coordinates ()
3886 "Toggle the display of coordinates in the referenced table."
3888 (let ((pos (marker-position org-pos
)))
3889 (with-current-buffer (marker-buffer org-pos
)
3892 (org-table-toggle-coordinate-overlays)))))
3894 (defun org-table-fedit-finish (&optional arg
)
3895 "Parse the buffer for formula definitions and install them.
3896 With prefix ARG, apply the new formulas to the table."
3898 (org-table-remove-rectangle-highlight)
3899 (when org-table-use-standard-references
3900 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3901 (setq org-table-buffer-is-an nil
))
3903 (sel-win org-selected-window
)
3904 (source org-table--fedit-source
)
3906 (goto-char (point-min))
3907 (while (re-search-forward
3908 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3910 (let ((var (match-string 1))
3911 (form (org-trim (match-string 3))))
3912 (unless (equal form
"")
3913 (while (string-match "[ \t]*\n[ \t]*" form
)
3914 (setq form
(replace-match " " t t form
)))
3915 (when (assoc var eql
)
3916 (user-error "Double formulas for %s" var
))
3917 (push (cons var form
) eql
))))
3918 (set-window-configuration org-window-configuration
)
3919 (select-window sel-win
)
3921 (org-table-store-formulas eql
)
3922 (set-marker pos nil
)
3923 (set-marker source nil
)
3924 (kill-buffer "*Edit Formulas*")
3926 (org-table-recalculate 'all
)
3927 (message "New formulas installed - press C-u C-c C-c to apply."))))
3929 (defun org-table-fedit-abort ()
3930 "Abort editing formulas, without installing the changes."
3932 (org-table-remove-rectangle-highlight)
3933 (let ((pos org-pos
) (sel-win org-selected-window
))
3934 (set-window-configuration org-window-configuration
)
3935 (select-window sel-win
)
3937 (move-marker pos nil
)
3938 (message "Formula editing aborted without installing changes")))
3940 (defun org-table-fedit-lisp-indent ()
3941 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3943 (let ((pos (point)) beg end ind
)
3944 (beginning-of-line 1)
3946 ((looking-at "[ \t]")
3948 (call-interactively 'lisp-indent-line
))
3949 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3950 ((not (fboundp 'pp-buffer
))
3951 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3952 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3953 (goto-char (- (match-end 0) 2))
3955 (setq ind
(make-string (current-column) ?\
))
3956 (condition-case nil
(forward-sexp 1)
3958 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3961 (narrow-to-region beg end
)
3962 (if (eq last-command this-command
)
3964 (goto-char (point-min))
3965 (setq this-command nil
)
3966 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3967 (replace-match " ")))
3969 (untabify (point-min) (point-max))
3970 (goto-char (1+ (point-min)))
3971 (while (re-search-forward "^." nil t
)
3972 (beginning-of-line 1)
3974 (goto-char (point-max))
3975 (org-delete-backward-char 1)))
3979 (defvar org-show-positions nil
)
3981 (defun org-table-show-reference (&optional local
)
3982 "Show the location/value of the $ expression at point.
3983 When LOCAL is non-nil, show references for the table at point."
3985 (org-table-remove-rectangle-highlight)
3986 (when local
(org-table-analyze))
3988 (let ((pos (if local
(point) org-pos
))
3990 (org-inhibit-highlight-removal t
)
3991 (win (selected-window))
3992 (org-show-positions nil
)
3993 var name e what match dest
)
3995 ((org-in-regexp "^@[0-9]+[ \t=]")
3996 (setq match
(concat (substring (match-string 0) 0 -
1)
3998 (substring (match-string 0) 0 -
1)
4001 ((or (org-in-regexp org-table-range-regexp2
)
4002 (org-in-regexp org-table-translate-regexp
)
4003 (org-in-regexp org-table-range-regexp
))
4006 (org-table-convert-refs-to-rc (match-string 0))))
4008 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
4009 ((org-in-regexp "\\$[0-9]+") 'column
)
4011 (t (user-error "No reference at point")))
4012 match
(and what
(or match
(match-string 0))))
4013 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
4014 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
4015 'secondary-selection
))
4016 (add-hook 'before-change-functions
4017 #'org-table-remove-rectangle-highlight
)
4018 (when (eq what
'name
) (setq var
(substring match
1)))
4019 (when (eq what
'range
)
4020 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
4021 (setq match
(org-table-formula-substitute-names match
)))
4025 (re-search-backward "^\\S-" nil t
)
4027 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4028 \\([0-9]+\\|&\\)\\) *=")
4031 (org-table-convert-refs-to-rc (match-string 1))))
4032 (org-table-add-rectangle-overlay
4033 (match-beginning 1) (match-end 1) face2
))))
4034 (if (and (markerp pos
) (marker-buffer pos
))
4035 (if (get-buffer-window (marker-buffer pos
))
4036 (select-window (get-buffer-window (marker-buffer pos
)))
4037 (org-switch-to-buffer-other-window (get-buffer-window
4038 (marker-buffer pos
)))))
4040 (org-table-force-dataline)
4042 (if local org-table-current-begin-pos
(org-table-begin))))
4044 (setq name
(substring dest
1))
4046 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
4047 (org-table-goto-field dest
))
4048 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4050 (org-table-goto-field dest
))
4051 (t (org-table-goto-column (string-to-number name
))))
4052 (move-marker pos
(point))
4053 (org-table-highlight-rectangle nil nil face2
))
4055 ((equal dest match
))
4058 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
4059 ((setq e
(assoc var org-table-named-field-locations
))
4060 (org-table-goto-field var
)
4061 (org-table-highlight-rectangle)
4062 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
4063 ((setq e
(assoc var org-table-column-names
))
4064 (org-table-goto-column (string-to-number (cdr e
)))
4065 (org-table-highlight-rectangle)
4066 (goto-char table-start
)
4067 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
4070 (goto-char (match-beginning 1))
4071 (org-table-highlight-rectangle)
4072 (message "Named column (column %s)" (cdr e
)))
4073 (user-error "Column name not found")))
4076 (org-table-goto-column (string-to-number (substring match
1)))
4077 (org-table-highlight-rectangle)
4078 (message "Column %s" (substring match
1)))
4079 ((setq e
(assoc var org-table-local-parameters
))
4080 (goto-char table-start
)
4081 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
4083 (goto-char (match-beginning 1))
4084 (org-table-highlight-rectangle)
4085 (message "Local parameter."))
4086 (user-error "Parameter not found")))
4087 ((not var
) (user-error "No reference at point"))
4088 ((setq e
(assoc var org-table-formula-constants-local
))
4089 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4091 ((setq e
(assoc var org-table-formula-constants
))
4092 (message "Constant: $%s=%s in `org-table-formula-constants'."
4094 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4095 (message "Constant: $%s=%s, from `constants.el'%s."
4096 var e
(format " (%s units)" constants-unit-system
)))
4097 (t (user-error "Undefined name $%s" var
)))
4099 (when (and org-show-positions
4100 (not (memq this-command
'(org-table-fedit-scroll
4101 org-table-fedit-scroll-down
))))
4102 (push pos org-show-positions
)
4103 (push table-start org-show-positions
)
4104 (let ((min (apply 'min org-show-positions
))
4105 (max (apply 'max org-show-positions
)))
4106 (set-window-start (selected-window) min
)
4108 (or (pos-visible-in-window-p max
)
4109 (set-window-start (selected-window) max
)))))
4110 (select-window win
))))
4112 (defun org-table-force-dataline ()
4113 "Make sure the cursor is in a dataline in a table."
4114 (unless (save-excursion
4115 (beginning-of-line 1)
4116 (looking-at org-table-dataline-regexp
))
4117 (let* ((re org-table-dataline-regexp
)
4118 (p1 (save-excursion (re-search-forward re nil
'move
)))
4119 (p2 (save-excursion (re-search-backward re nil
'move
))))
4121 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4123 ((or p1 p2
) (goto-char (or p1 p2
)))
4124 (t (user-error "No table dataline around here"))))))
4126 (defun org-table-fedit-line-up ()
4127 "Move cursor one line up in the window showing the table."
4129 (org-table-fedit-move 'previous-line
))
4131 (defun org-table-fedit-line-down ()
4132 "Move cursor one line down in the window showing the table."
4134 (org-table-fedit-move 'next-line
))
4136 (defun org-table-fedit-move (command)
4137 "Move the cursor in the window showing the table.
4138 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4139 (let ((org-table-allow-automatic-line-recalculation nil
)
4140 (pos org-pos
) (win (selected-window)) p
)
4141 (select-window (get-buffer-window (marker-buffer org-pos
)))
4143 (call-interactively command
)
4144 (while (and (org-at-table-p)
4145 (org-at-table-hline-p))
4146 (call-interactively command
))
4147 (or (org-at-table-p) (goto-char p
))
4148 (move-marker pos
(point))
4149 (select-window win
)))
4151 (defun org-table-fedit-scroll (N)
4153 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4154 (scroll-other-window N
)))
4156 (defun org-table-fedit-scroll-down (N)
4158 (org-table-fedit-scroll (- N
)))
4160 (defvar org-table-rectangle-overlays nil
)
4162 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4163 "Add a new overlay."
4164 (let ((ov (make-overlay beg end
)))
4165 (overlay-put ov
'face
(or face
'secondary-selection
))
4166 (push ov org-table-rectangle-overlays
)))
4168 (defun org-table-highlight-rectangle (&optional beg end face
)
4169 "Highlight rectangular region in a table.
4170 When buffer positions BEG and END are provided, use them to
4171 delimit the region to highlight. Otherwise, refer to point. Use
4172 FACE, when non-nil, for the highlight."
4173 (let* ((beg (or beg
(point)))
4174 (end (or end
(point)))
4180 (cons (line-beginning-position) (org-table-current-column))))
4184 (cons (line-beginning-position) (org-table-current-column)))))
4185 (when (boundp 'org-show-positions
)
4186 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4187 (goto-char (car start-coordinates
))
4188 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
4189 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
4190 (last-row (car end-coordinates
)))
4191 (while (<= (point) last-row
)
4192 (when (looking-at org-table-dataline-regexp
)
4193 (org-table-goto-column column-start
)
4194 (skip-chars-backward "^|\n")
4196 (org-table-goto-column column-end
)
4197 (skip-chars-forward "^|\n")
4198 (org-table-add-rectangle-overlay p
(point) face
)))
4200 (goto-char (car start-coordinates
)))
4201 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
4203 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
4204 "Remove the rectangle overlays."
4205 (unless org-inhibit-highlight-removal
4206 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4207 (mapc 'delete-overlay org-table-rectangle-overlays
)
4208 (setq org-table-rectangle-overlays nil
)))
4210 (defvar-local org-table-coordinate-overlays nil
4211 "Collects the coordinate grid overlays, so that they can be removed.")
4213 (defun org-table-overlay-coordinates ()
4214 "Add overlays to the table at point, to show row/column coordinates."
4216 (mapc 'delete-overlay org-table-coordinate-overlays
)
4217 (setq org-table-coordinate-overlays nil
)
4219 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4220 (goto-char (org-table-begin))
4221 (while (org-at-table-p)
4222 (setq eol
(point-at-eol))
4223 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4224 (push ov org-table-coordinate-overlays
)
4225 (setq hline
(looking-at org-table-hline-regexp
))
4226 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4227 (format "%4d" (setq id
(1+ id
)))))
4228 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4231 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4232 (setq beg
(1+ (match-beginning 0))
4234 s1
(concat "$" (int-to-string ic
))
4235 s2
(org-number-to-letters ic
)
4236 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4237 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4238 (push ov org-table-coordinate-overlays
)
4239 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4240 (beginning-of-line 2)))))
4243 (defun org-table-toggle-coordinate-overlays ()
4244 "Toggle the display of Row/Column numbers in tables."
4246 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4247 (message "Tables Row/Column numbers display turned %s"
4248 (if org-table-overlay-coordinates
"on" "off"))
4249 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4251 (unless org-table-overlay-coordinates
4252 (mapc 'delete-overlay org-table-coordinate-overlays
)
4253 (setq org-table-coordinate-overlays nil
)))
4256 (defun org-table-toggle-formula-debugger ()
4257 "Toggle the formula debugger in tables."
4259 (setq org-table-formula-debug
(not org-table-formula-debug
))
4260 (message "Formula debugging has been turned %s"
4261 (if org-table-formula-debug
"on" "off")))
4263 ;;; The orgtbl minor mode
4265 ;; Define a minor mode which can be used in other modes in order to
4266 ;; integrate the Org table editor.
4268 ;; This is really a hack, because the Org table editor uses several
4269 ;; keys which normally belong to the major mode, for example the TAB
4270 ;; and RET keys. Here is how it works: The minor mode defines all the
4271 ;; keys necessary to operate the table editor, but wraps the commands
4272 ;; into a function which tests if the cursor is currently inside
4273 ;; a table. If that is the case, the table editor command is
4274 ;; executed. However, when any of those keys is used outside a table,
4275 ;; the function uses `key-binding' to look up if the key has an
4276 ;; associated command in another currently active keymap (minor modes,
4277 ;; major mode, global), and executes that command. There might be
4278 ;; problems if any of the keys used by the table editor is otherwise
4279 ;; used as a prefix key.
4281 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4282 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4283 ;; addresses this by checking explicitly for both bindings.
4285 ;; The optimized version (see variable `orgtbl-optimized') takes over
4286 ;; all keys which are bound to `self-insert-command' in the *global map*.
4287 ;; Some modes bind other commands to simple characters, for example
4288 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4289 ;; active, this binding is ignored inside tables and replaced with a
4290 ;; modified self-insert.
4293 (defvar orgtbl-mode-map
(make-keymap)
4294 "Keymap for `orgtbl-mode'.")
4296 (defvar org-old-auto-fill-inhibit-regexp nil
4297 "Local variable used by `orgtbl-mode'.")
4299 (defconst orgtbl-line-start-regexp
4300 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4301 "Matches a line belonging to an orgtbl.")
4303 (defconst orgtbl-extra-font-lock-keywords
4304 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4305 0 (quote 'org-table
) 'prepend
))
4306 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4308 ;; Install it as a minor mode.
4309 (put 'orgtbl-mode
:included t
)
4310 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4313 (define-minor-mode orgtbl-mode
4314 "The `org-mode' table editor as a minor mode for use in other modes."
4315 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4316 (org-load-modules-maybe)
4318 ((derived-mode-p 'org-mode
)
4319 ;; Exit without error, in case some hook functions calls this
4320 ;; by accident in org-mode.
4321 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4323 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4324 ;; Make sure we are first in minor-mode-map-alist
4325 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4326 ;; FIXME: maybe it should use emulation-mode-map-alists?
4327 (and c
(setq minor-mode-map-alist
4328 (cons c
(delq c minor-mode-map-alist
)))))
4329 (setq-local org-table-may-need-update t
)
4330 (add-hook 'before-change-functions
'org-before-change-function
4332 (setq-local org-old-auto-fill-inhibit-regexp
4333 auto-fill-inhibit-regexp
)
4334 (setq-local auto-fill-inhibit-regexp
4335 (if auto-fill-inhibit-regexp
4336 (concat orgtbl-line-start-regexp
"\\|"
4337 auto-fill-inhibit-regexp
)
4338 orgtbl-line-start-regexp
))
4339 (add-to-invisibility-spec '(org-cwidth))
4340 (when (fboundp 'font-lock-add-keywords
)
4341 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4342 (org-restart-font-lock))
4343 (easy-menu-add orgtbl-mode-menu
))
4345 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4346 (org-table-cleanup-narrow-column-properties)
4347 (org-remove-from-invisibility-spec '(org-cwidth))
4348 (remove-hook 'before-change-functions
'org-before-change-function t
)
4349 (when (fboundp 'font-lock-remove-keywords
)
4350 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4351 (org-restart-font-lock))
4352 (easy-menu-remove orgtbl-mode-menu
)
4353 (force-mode-line-update 'all
))))
4355 (defun org-table-cleanup-narrow-column-properties ()
4356 "Remove all properties related to narrow-column invisibility."
4357 (let ((s (point-min)))
4358 (while (setq s
(text-property-any s
(point-max)
4359 'display org-narrow-column-arrow
))
4360 (remove-text-properties s
(1+ s
) '(display t
)))
4361 (setq s
(point-min))
4362 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4363 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4364 (setq s
(point-min))
4365 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4366 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4368 (defun orgtbl-make-binding (fun n
&rest keys
)
4369 "Create a function for binding in the table minor mode.
4370 FUN is the command to call inside a table. N is used to create a unique
4371 command name. KEYS are keys that should be checked in for a command
4372 to execute outside of tables."
4375 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4377 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4378 "Outside of tables, run the binding of `"
4379 (mapconcat #'key-description keys
"' or `")
4384 (list 'call-interactively
(list 'quote fun
))
4385 (list 'let
'(orgtbl-mode)
4386 (list 'call-interactively
4389 (list 'key-binding k
))
4391 '('orgtbl-error
))))))))
4393 (defun orgtbl-error ()
4394 "Error when there is no default binding for a table key."
4396 (user-error "This key has no function outside tables"))
4398 (defun orgtbl-setup ()
4399 "Setup orgtbl keymaps."
4402 '(([(meta shift left
)] org-table-delete-column
)
4403 ([(meta left
)] org-table-move-column-left
)
4404 ([(meta right
)] org-table-move-column-right
)
4405 ([(meta shift right
)] org-table-insert-column
)
4406 ([(meta shift up
)] org-table-kill-row
)
4407 ([(meta shift down
)] org-table-insert-row
)
4408 ([(meta up
)] org-table-move-row-up
)
4409 ([(meta down
)] org-table-move-row-down
)
4410 ("\C-c\C-w" org-table-cut-region
)
4411 ("\C-c\M-w" org-table-copy-region
)
4412 ("\C-c\C-y" org-table-paste-rectangle
)
4413 ("\C-c\C-w" org-table-wrap-region
)
4414 ("\C-c-" org-table-insert-hline
)
4415 ("\C-c}" org-table-toggle-coordinate-overlays
)
4416 ("\C-c{" org-table-toggle-formula-debugger
)
4417 ("\C-m" org-table-next-row
)
4418 ([(shift return
)] org-table-copy-down
)
4419 ("\C-c?" org-table-field-info
)
4420 ("\C-c " org-table-blank-field
)
4421 ("\C-c+" org-table-sum
)
4422 ("\C-c=" org-table-eval-formula
)
4423 ("\C-c'" org-table-edit-formulas
)
4424 ("\C-c`" org-table-edit-field
)
4425 ("\C-c*" org-table-recalculate
)
4426 ("\C-c^" org-table-sort-lines
)
4427 ("\M-a" org-table-beginning-of-field
)
4428 ("\M-e" org-table-end-of-field
)
4429 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4431 (while (setq elt
(pop bindings
))
4432 (setq nfunc
(1+ nfunc
))
4433 (setq key
(org-key (car elt
))
4435 cmd
(orgtbl-make-binding fun nfunc key
))
4436 (org-defkey orgtbl-mode-map key cmd
))
4438 ;; Special treatment needed for TAB, RET and DEL
4439 (org-defkey orgtbl-mode-map
[(return)]
4440 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4441 (org-defkey orgtbl-mode-map
"\C-m"
4442 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4443 (org-defkey orgtbl-mode-map
[(tab)]
4444 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4445 (org-defkey orgtbl-mode-map
"\C-i"
4446 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4447 (org-defkey orgtbl-mode-map
[(shift tab
)]
4448 (orgtbl-make-binding 'org-table-previous-field
104
4449 [(shift tab
)] [(tab)] "\C-i"))
4450 (org-defkey orgtbl-mode-map
[backspace]
4451 (orgtbl-make-binding 'org-delete-backward-char 109
4452 [backspace] (kbd "DEL")))
4454 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4455 (orgtbl-make-binding 'org-table-previous-field
107
4456 [S-iso-lefttab
] [backtab] [(shift tab)]
4459 (org-defkey orgtbl-mode-map [backtab]
4460 (orgtbl-make-binding 'org-table-previous-field
108
4461 [backtab] [S-iso-lefttab] [(shift tab)]
4464 (org-defkey orgtbl-mode-map "\M-\C-m"
4465 (orgtbl-make-binding 'org-table-wrap-region 105
4466 "\M-\C-m" [(meta return)]))
4467 (org-defkey orgtbl-mode-map [(meta return)]
4468 (orgtbl-make-binding 'org-table-wrap-region 106
4469 [(meta return)] "\M-\C-m"))
4471 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4472 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4474 (when orgtbl-optimized
4475 ;; If the user wants maximum table support, we need to hijack
4476 ;; some standard editing functions
4477 (org-remap orgtbl-mode-map
4478 'self-insert-command 'orgtbl-self-insert-command
4479 'delete-char 'org-delete-char
4480 'delete-backward-char 'org-delete-backward-char)
4481 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4482 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4484 ["Create or convert" org-table-create-or-convert-from-region
4485 :active (not (org-at-table-p)) :keys "C-c |" ]
4487 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4488 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4489 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4490 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4492 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4493 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4494 ["Copy Field from Above"
4495 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4498 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4499 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4500 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4501 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4503 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4504 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4505 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4506 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4507 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4509 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4511 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4512 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4513 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4514 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4517 ["Insert table template" orgtbl-insert-radio-table
4518 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
4519 ["Comment/uncomment table" orgtbl-toggle-comment t])
4521 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4522 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4523 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4524 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4525 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4526 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4527 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4528 ["Sum Column/Rectangle" org-table-sum
4529 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4530 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4532 org-table-toggle-formula-debugger :active (org-at-table-p)
4534 :style toggle :selected org-table-formula-debug]
4535 ["Show Col/Row Numbers"
4536 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4538 :style toggle :selected org-table-overlay-coordinates]
4541 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4542 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4545 (defun orgtbl-ctrl-c-ctrl-c (arg)
4546 "If the cursor is inside a table, realign the table.
4547 If it is a table to be sent away to a receiver, do it.
4548 With prefix arg, also recompute table."
4550 (let ((case-fold-search t) (pos (point)) action)
4552 (beginning-of-line 1)
4554 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4555 ((looking-at "[ \t]*|") pos)
4556 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4560 (org-table-maybe-eval-formula)
4562 (call-interactively 'org-table-recalculate)
4563 (org-table-maybe-recalculate-line))
4564 (call-interactively 'org-table-align)
4565 (when (orgtbl-send-table 'maybe)
4566 (run-hooks 'orgtbl-after-send-table-hook)))
4567 ((eq action 'recalc)
4569 (beginning-of-line 1)
4570 (skip-chars-backward " \r\n\t")
4571 (if (org-at-table-p)
4572 (org-call-with-arg 'org-table-recalculate t))))
4573 (t (let (orgtbl-mode)
4574 (call-interactively (key-binding "\C-c\C-c")))))))
4576 (defun orgtbl-create-or-convert-from-region (_arg)
4577 "Create table or convert region to table, if no conflicting binding.
4578 This installs the table binding `C-c |', but only if there is no
4579 conflicting binding to this key outside orgtbl-mode."
4581 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4583 (call-interactively cmd)
4584 (call-interactively 'org-table-create-or-convert-from-region))))
4586 (defun orgtbl-tab (arg)
4587 "Justification and field motion for `orgtbl-mode'."
4589 (if arg (org-table-edit-field t)
4590 (org-table-justify-field-maybe)
4591 (org-table-next-field)))
4593 (defun orgtbl-ret ()
4594 "Justification and field motion for `orgtbl-mode'."
4598 (org-table-justify-field-maybe)
4599 (org-table-next-row)))
4601 (defun orgtbl-self-insert-command (N)
4602 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4603 If the cursor is in a table looking at whitespace, the whitespace is
4604 overwritten, and the table is not marked as requiring realignment."
4606 (if (and (org-at-table-p)
4608 (and org-table-auto-blank-field
4609 (member last-command
4610 '(orgtbl-hijacker-command-100
4611 orgtbl-hijacker-command-101
4612 orgtbl-hijacker-command-102
4613 orgtbl-hijacker-command-103
4614 orgtbl-hijacker-command-104
4615 orgtbl-hijacker-command-105
4617 (org-table-blank-field))
4620 (looking-at "[^|\n]* \\( \\)|"))
4621 (let (org-table-may-need-update)
4622 (delete-region (match-beginning 1) (match-end 1))
4623 (self-insert-command N))
4624 (setq org-table-may-need-update t)
4627 (cmd (or (key-binding
4628 (or (and (listp function-key-map)
4629 (setq a (assoc last-input-event function-key-map))
4631 (vector last-input-event)))
4632 'self-insert-command)))
4633 (call-interactively cmd)
4634 (if (and org-self-insert-cluster-for-undo
4635 (eq cmd 'self-insert-command))
4636 (if (not (eq last-command 'orgtbl-self-insert-command))
4637 (setq org-self-insert-command-undo-counter 1)
4638 (if (>= org-self-insert-command-undo-counter 20)
4639 (setq org-self-insert-command-undo-counter 1)
4640 (and (> org-self-insert-command-undo-counter 0)
4642 (not (cadr buffer-undo-list)) ; remove nil entry
4643 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4644 (setq org-self-insert-command-undo-counter
4645 (1+ org-self-insert-command-undo-counter))))))))
4648 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4649 "Regular expression matching exponentials as produced by calc.")
4651 (defun orgtbl-gather-send-defs ()
4652 "Gather a plist of :name, :transform, :params for each destination before
4655 (goto-char (org-table-begin))
4657 (beginning-of-line 0)
4658 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4659 (let ((name (org-no-properties (match-string 1)))
4660 (transform (intern (match-string 2)))
4661 (params (if (match-end 3)
4662 (read (concat "(" (match-string 3) ")")))))
4663 (push (list :name name :transform transform :params params)
4665 (beginning-of-line 0)))
4668 (defun orgtbl-send-replace-tbl (name text)
4669 "Find and replace table NAME with TEXT."
4671 (goto-char (point-min))
4672 (let* ((location-flag nil)
4673 (name (regexp-quote name))
4674 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4675 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4676 (while (re-search-forward begin-re nil t)
4677 (unless location-flag (setq location-flag t))
4678 (let ((beg (line-beginning-position 2)))
4679 (unless (re-search-forward end-re nil t)
4680 (user-error "Cannot find end of receiver location at %d" beg))
4682 (delete-region beg (point))
4683 (insert text "\n")))
4684 (unless location-flag
4685 (user-error "No valid receiver location found in the buffer")))))
4688 (defun org-table-to-lisp (&optional txt)
4689 "Convert the table at point to a Lisp structure.
4690 The structure will be a list. Each item is either the symbol `hline'
4691 for a horizontal separator line, or a list of field values as strings.
4692 The table is taken from the parameter TXT, or from the buffer at point."
4693 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4695 (buffer-substring-no-properties (org-table-begin)
4698 (if (string-match org-table-hline-regexp x) 'hline
4699 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4700 (org-split-string txt "[ \t]*\n[ \t]*"))))
4702 (defun orgtbl-send-table (&optional maybe)
4703 "Send a transformed version of table at point to the receiver position.
4704 With argument MAYBE, fail quietly if no transformation is defined
4708 (unless (org-at-table-p) (user-error "Not at a table"))
4709 ;; when non-interactive, we assume align has just happened.
4710 (when (called-interactively-p 'any) (org-table-align))
4711 (let ((dests (orgtbl-gather-send-defs))
4712 (table (org-table-to-lisp
4713 (buffer-substring-no-properties (org-table-begin)
4717 (if maybe (throw 'exit nil)
4718 (user-error "Don't know how to transform this table")))
4719 (dolist (dest dests)
4720 (let ((name (plist-get dest :name))
4721 (transform (plist-get dest :transform))
4722 (params (plist-get dest :params)))
4723 (unless (fboundp transform)
4724 (user-error "No such transformation function %s" transform))
4725 (orgtbl-send-replace-tbl name (funcall transform table params)))
4727 (message "Table converted and installed at %d receiver location%s"
4728 ntbl (if (> ntbl 1) "s" ""))
4729 (and (> ntbl 0) ntbl))))
4731 (defun org-remove-by-index (list indices &optional i0)
4732 "Remove the elements in LIST with indices in INDICES.
4733 First element has index 0, or I0 if given."
4736 (if (integerp indices) (setq indices (list indices)))
4737 (setq i0 (1- (or i0 0)))
4738 (delq :rm (mapcar (lambda (x)
4740 (if (memq i0 indices) :rm x))
4743 (defun orgtbl-toggle-comment ()
4744 "Comment or uncomment the orgtbl at point."
4746 (let* ((case-fold-search t)
4747 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4748 (re2 (concat "^" orgtbl-line-start-regexp))
4749 (commented (save-excursion (beginning-of-line 1)
4750 (cond ((looking-at re1) t)
4751 ((looking-at re2) nil)
4752 (t (user-error "Not at an org table")))))
4753 (re (if commented re1 re2))
4756 (beginning-of-line 1)
4757 (while (looking-at re) (beginning-of-line 0))
4758 (beginning-of-line 2)
4760 (while (looking-at re) (beginning-of-line 2))
4762 (comment-region beg end (if commented '(4) nil))))
4764 (defun orgtbl-insert-radio-table ()
4765 "Insert a radio table template appropriate for this major mode."
4767 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
4770 (unless e (user-error "No radio table setup defined for %s" major-mode))
4771 (setq name (read-string "Table name: "))
4772 (while (string-match "%n" txt)
4773 (setq txt (replace-match name t t txt)))
4774 (or (bolp) (insert "\n"))
4780 (defun orgtbl-to-generic (table params)
4781 "Convert the orgtbl-mode TABLE to some other format.
4783 This generic routine can be used for many standard cases.
4785 TABLE is a list, each entry either the symbol `hline' for
4786 a horizontal separator line, or a list of fields for that
4787 line. PARAMS is a property list of parameters that can
4788 influence the conversion.
4790 Valid parameters are:
4794 Export back-end used as a basis to transcode elements of the
4795 table, when no specific parameter applies to it. It is also
4796 used to translate cells contents. You can prevent this by
4797 setting :raw property to a non-nil value.
4801 When non-nil, only convert rows, not the table itself. This is
4802 equivalent to setting to the empty string both :tstart
4803 and :tend, which see.
4807 When set to an integer N, skip the first N lines of the table.
4808 Horizontal separation lines do count for this parameter!
4812 List of columns that should be skipped. If the table has
4813 a column with calculation marks, that column is automatically
4814 discarded beforehand.
4818 String to be inserted on horizontal separation lines. May be
4819 nil to ignore these lines altogether.
4823 Separator between two fields, as a string.
4825 Each in the following group may be either a string or a function
4826 of no arguments returning a string:
4830 Strings to start and end the table. Ignored when :splice is t.
4834 Strings to start and end a new table line.
4838 Strings to start and end the last table line. Default,
4839 respectively, to :lstart and :lend.
4841 Each in the following group may be a string or a function of one
4842 argument (either the cells in the current row, as a list of
4843 strings, or the current cell) returning a string:
4847 Format string for an entire row, with enough %s to capture all
4848 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4852 Format for the entire last line, defaults to :lfmt.
4856 A format to be used to wrap the field, should contain %s for
4857 the original field value. For example, to wrap everything in
4858 dollars, you could use :fmt \"$%s$\". This may also be
4859 a property list with column numbers and format strings, or
4862 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4864 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4866 Same as above, specific for the header lines in the table.
4867 All lines before the first hline are treated as header. If
4868 any of these is not present, the data line value is used.
4870 This may be either a string or a function of two arguments:
4874 Use this format to print numbers with exponential. The format
4875 should have %s twice for inserting mantissa and exponent, for
4876 example \"%s\\\\times10^{%s}\". This may also be a property
4877 list with column numbers and format strings or functions.
4878 :fmt will still be applied after :efmt."
4879 ;; Make sure `org-export-create-backend' is available.
4881 (let* ((backend (plist-get params :backend))
4883 ;; Build a custom back-end according to PARAMS. Before
4884 ;; defining a translator, check if there is anything to do.
4885 ;; When there isn't, let BACKEND handle the element.
4886 (org-export-create-backend
4887 :parent (or backend 'org)
4889 `((table . ,(org-table--to-generic-table params))
4890 (table-row . ,(org-table--to-generic-row params))
4891 (table-cell . ,(org-table--to-generic-cell params))
4892 ;; Macros are not going to be expanded. However, no
4893 ;; regular back-end has a transcoder for them. We
4894 ;; provide one so they are not ignored, but displayed
4896 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4898 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4899 ;; Initialize communication channel in INFO.
4901 (let ((org-inhibit-startup t)) (org-mode))
4902 (let ((standard-output (current-buffer))
4903 (org-element-use-cache nil))
4905 (cond ((eq e 'hline) (princ "|--\n"))
4907 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4909 ;; Add back-end specific filters, but not user-defined ones. In
4910 ;; particular, make sure to call parse-tree filters on the
4913 (let ((org-export-filters-alist nil))
4914 (org-export-install-filters
4916 (org-export-get-environment backend nil params)
4917 `(:back-end ,(org-export-get-backend backend))))))
4919 (org-export-filter-apply-functions
4920 (plist-get info :filter-parse-tree)
4921 (org-element-map (org-element-parse-buffer) 'table
4924 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4925 (user-error "Unknown :backend value"))
4926 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4927 ;; Handle :skip parameter.
4928 (let ((skip (plist-get info :skip)))
4930 (unless (wholenump skip) (user-error "Wrong :skip value"))
4932 (org-element-map data 'table-row
4935 (org-element-extract-element row)
4939 ;; Handle :skipcols parameter.
4940 (let ((skipcols (plist-get info :skipcols)))
4942 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4943 (org-element-map data 'table
4945 (let ((specialp (org-export-table-has-special-column-p table)))
4946 (dolist (row (org-element-contents table))
4947 (when (eq (org-element-property :type row) 'standard)
4949 (dolist (cell (nthcdr (if specialp 1 0)
4950 (org-element-contents row)))
4951 (when (memq c skipcols)
4952 (org-element-extract-element cell))
4953 (cl-incf c))))))))))
4954 ;; Since we are going to export using a low-level mechanism,
4955 ;; ignore special column and special rows manually.
4956 (let ((special? (org-export-table-has-special-column-p data))
4958 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4960 (when (if (eq (org-element-type datum) 'table-row)
4961 (org-export-table-row-is-special-p datum nil)
4962 (org-export-first-sibling-p datum nil))
4963 (push datum ignore))))
4964 (setq info (plist-put info :ignore-list ignore)))
4965 ;; We use a low-level mechanism to export DATA so as to skip all
4966 ;; usual pre-processing and post-processing, i.e., hooks, Babel
4967 ;; code evaluation, include keywords and macro expansion. Only
4968 ;; back-end specific filters are retained.
4969 (let ((output (org-export-data-with-backend data custom-backend info)))
4970 ;; Remove final newline.
4971 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4973 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4974 (cond ((null value) nil)
4975 ((functionp value) `(funcall ',value ,@args))
4977 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4978 (args `(format ,value ,@args))
4980 ((and with-cons (consp value))
4981 `(let ((val (cadr (memq column ',value))))
4982 (cond ((null val) contents)
4983 ((stringp val) (format val ,@args))
4984 ((functionp val) (funcall val ,@args))
4985 (t (user-error "Wrong %s value" ,name)))))
4986 (t (user-error "Wrong %s value" name))))
4988 (defun org-table--to-generic-table (params)
4989 "Return custom table transcoder according to PARAMS.
4990 PARAMS is a plist. See `orgtbl-to-generic' for more
4992 (let ((backend (plist-get params :backend))
4993 (splice (plist-get params :splice))
4994 (tstart (plist-get params :tstart))
4995 (tend (plist-get params :tend)))
4996 `(lambda (table contents info)
4998 ,(and tstart (not splice)
4999 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
5000 ,(if (or (not backend) tstart tend splice) 'contents
5001 `(org-export-with-backend ',backend table contents info))
5002 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
5004 (defun org-table--to-generic-row (params)
5005 "Return custom table row transcoder according to PARAMS.
5006 PARAMS is a plist. See `orgtbl-to-generic' for more
5008 (let* ((backend (plist-get params :backend))
5009 (lstart (plist-get params :lstart))
5010 (llstart (plist-get params :llstart))
5011 (hlstart (plist-get params :hlstart))
5012 (hllstart (plist-get params :hllstart))
5013 (lend (plist-get params :lend))
5014 (llend (plist-get params :llend))
5015 (hlend (plist-get params :hlend))
5016 (hllend (plist-get params :hllend))
5017 (lfmt (plist-get params :lfmt))
5018 (llfmt (plist-get params :llfmt))
5019 (hlfmt (plist-get params :hlfmt))
5020 (hllfmt (plist-get params :hllfmt)))
5021 `(lambda (row contents info)
5022 (if (eq (org-element-property :type row) 'rule)
5024 ((plist-member params :hline)
5025 (org-table--generic-apply (plist-get params :hline) ":hline"))
5026 (backend `(org-export-with-backend ',backend row nil info)))
5027 (let ((headerp ,(and (or hlfmt hlstart hlend)
5028 '(org-export-table-row-in-header-p row info)))
5030 ,(and (or hllfmt hllstart hllend)
5031 '(org-export-table-row-ends-header-p row info)))
5032 (lastp (not (org-export-get-next-element row info))))
5034 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5035 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5036 ;; `:lstart', `:lend' and their relatives.
5038 '(org-element-map row 'table-cell
5040 ;; Export all cells, without separators.
5042 ;; Use `org-export-data-with-backend'
5043 ;; instead of `org-export-data' to eschew
5044 ;; cached values, which
5045 ;; ignore :orgtbl-ignore-sep parameter.
5046 (org-export-data-with-backend
5048 (plist-get info :back-end)
5049 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5053 `(last-header-p ,(org-table--generic-apply
5054 hllfmt ":hllfmt" nil cells)))
5056 `(headerp ,(org-table--generic-apply
5057 hlfmt ":hlfmt" nil cells)))
5059 `(lastp ,(org-table--generic-apply
5060 llfmt ":llfmt" nil cells)))
5062 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5066 (or hllstart hllend)
5069 ,(org-table--generic-apply hllstart ":hllstart")
5071 ,(org-table--generic-apply hllend ":hllend"))))
5076 ,(org-table--generic-apply hlstart ":hlstart")
5078 ,(org-table--generic-apply hlend ":hlend"))))
5083 ,(org-table--generic-apply llstart ":llstart")
5085 ,(org-table--generic-apply llend ":llend"))))
5090 ,(org-table--generic-apply lstart ":lstart")
5092 ,(org-table--generic-apply lend ":lend")))
5094 `(org-export-with-backend
5095 ',backend row contents info))
5096 (t 'contents)))))))))))))))
5098 (defun org-table--to-generic-cell (params)
5099 "Return custom table cell transcoder according to PARAMS.
5100 PARAMS is a plist. See `orgtbl-to-generic' for more
5102 (let* ((backend (plist-get params :backend))
5103 (efmt (plist-get params :efmt))
5104 (fmt (plist-get params :fmt))
5105 (hfmt (plist-get params :hfmt))
5106 (sep (plist-get params :sep))
5107 (hsep (plist-get params :hsep)))
5108 `(lambda (cell contents info)
5109 ;; Make sure that contents are exported as Org data when :raw
5110 ;; parameter is non-nil.
5111 ,(when (and backend (plist-get params :raw))
5113 ;; Since we don't know what are the pseudo object
5114 ;; types defined in backend, we cannot pass them to
5115 ;; `org-element-interpret-data'. As a consequence,
5116 ;; they will be treated as pseudo elements, and will
5117 ;; have newlines appended instead of spaces.
5118 ;; Therefore, we must make sure :post-blank value is
5119 ;; really turned into spaces.
5120 (replace-regexp-in-string
5123 (org-element-interpret-data
5124 (org-element-contents cell))))))
5126 (let ((headerp ,(and (or hfmt hsep)
5127 '(org-export-table-row-in-header-p
5128 (org-export-get-parent-element cell) info)))
5130 ;; Call costly `org-export-table-cell-address' only if
5131 ;; absolutely necessary, i.e., if one
5132 ;; of :fmt :efmt :hfmt has a "plist type" value.
5133 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5134 (list efmt hfmt fmt))
5135 '(1+ (cdr (org-export-table-cell-address cell info))))))
5137 ;; Check if we can apply `:efmt' on CONTENTS.
5139 `(when (string-match orgtbl-exp-regexp contents)
5140 (let ((mantissa (match-string 1 contents))
5141 (exponent (match-string 2 contents)))
5142 (setq contents ,(org-table--generic-apply
5143 efmt ":efmt" t 'mantissa 'exponent)))))
5144 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5146 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5147 hfmt ":hfmt" t 'contents))))
5148 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5149 fmt ":fmt" t 'contents))))))
5150 ;; If a separator is provided, use it instead of BACKEND's.
5151 ;; Separators are ignored when LFMT (or equivalent) is
5155 `(if (or ,(and (not sep) '(not headerp))
5156 (plist-get info :orgtbl-ignore-sep)
5157 (not (org-export-get-next-element cell info)))
5158 ,(if (not backend) 'contents
5159 `(org-export-with-backend ',backend cell contents info))
5161 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5163 (backend `(org-export-with-backend ',backend cell contents info))
5167 (defun orgtbl-to-tsv (table params)
5168 "Convert the orgtbl-mode table to TAB separated material."
5169 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5172 (defun orgtbl-to-csv (table params)
5173 "Convert the orgtbl-mode table to CSV material.
5174 This does take care of the proper quoting of fields with comma or quotes."
5175 (orgtbl-to-generic table
5176 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5180 (defun orgtbl-to-latex (table params)
5181 "Convert the orgtbl-mode TABLE to LaTeX.
5183 TABLE is a list, each entry either the symbol `hline' for
5184 a horizontal separator line, or a list of fields for that line.
5185 PARAMS is a property list of parameters that can influence the
5186 conversion. All parameters from `orgtbl-to-generic' are
5187 supported. It is also possible to use the following ones:
5191 When non-nil, use formal \"booktabs\" style.
5195 Specify environment to use, as a string. If you use
5196 \"longtable\", you may also want to specify :language property,
5197 as a string, to get proper continuation strings."
5202 ;; Provide sane default values.
5203 (list :backend 'latex
5204 :latex-default-table-mode 'table
5205 :latex-tables-centered nil
5206 :latex-tables-booktabs (plist-get params :booktabs)
5207 :latex-table-scientific-notation nil
5208 :latex-default-table-environment
5209 (or (plist-get params :environment) "tabular"))
5213 (defun orgtbl-to-html (table params)
5214 "Convert the orgtbl-mode TABLE to HTML.
5216 TABLE is a list, each entry either the symbol `hline' for
5217 a horizontal separator line, or a list of fields for that line.
5218 PARAMS is a property list of parameters that can influence the
5219 conversion. All parameters from `orgtbl-to-generic' are
5220 supported. It is also possible to use the following one:
5224 Attributes and values, as a plist, which will be used in
5230 ;; Provide sane default values.
5231 (list :backend 'html
5232 :html-table-data-tags '("<td%s>" . "</td>")
5233 :html-table-use-header-tags-for-first-column nil
5234 :html-table-align-individual-fields t
5235 :html-table-row-tags '("<tr>" . "</tr>")
5236 :html-table-attributes
5237 (if (plist-member params :attributes)
5238 (plist-get params :attributes)
5239 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5244 (defun orgtbl-to-texinfo (table params)
5245 "Convert the orgtbl-mode TABLE to Texinfo.
5247 TABLE is a list, each entry either the symbol `hline' for
5248 a horizontal separator line, or a list of fields for that line.
5249 PARAMS is a property list of parameters that can influence the
5250 conversion. All parameters from `orgtbl-to-generic' are
5251 supported. It is also possible to use the following one:
5255 Column widths, as a string. When providing column fractions,
5256 \"@columnfractions\" command can be omitted."
5257 (require 'ox-texinfo)
5262 (list :backend 'texinfo
5263 :texinfo-tables-verbatim nil
5264 :texinfo-table-scientific-notation nil)
5266 (columns (let ((w (plist-get params :columns)))
5268 ((string-match-p "{\\|@columnfractions " w) w)
5269 (t (concat "@columnfractions " w))))))
5270 (if (not columns) output
5271 (replace-regexp-in-string
5272 "@multitable \\(.*\\)" columns output t nil 1))))
5275 (defun orgtbl-to-orgtbl (table params)
5276 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5278 TABLE is a list, each entry either the symbol `hline' for
5279 a horizontal separator line, or a list of fields for that line.
5280 PARAMS is a property list of parameters that can influence the
5281 conversion. All parameters from `orgtbl-to-generic' are
5284 Useful when slicing one table into many. The :hline, :sep,
5285 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5286 be set to provide ORGTBL directives for the generated table."
5288 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5290 (defun orgtbl-to-table.el (table params)
5291 "Convert the orgtbl-mode TABLE into a table.el table.
5292 TABLE is a list, each entry either the symbol `hline' for
5293 a horizontal separator line, or a list of fields for that line.
5294 PARAMS is a property list of parameters that can influence the
5295 conversion. All parameters from `orgtbl-to-generic' are
5298 (insert (orgtbl-to-orgtbl table params))
5300 (replace-regexp-in-string
5302 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5304 (defun orgtbl-to-unicode (table params)
5305 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5307 TABLE is a list, each entry either the symbol `hline' for
5308 a horizontal separator line, or a list of fields for that line.
5309 PARAMS is a property list of parameters that can influence the
5310 conversion. All parameters from `orgtbl-to-generic' are
5311 supported. It is also possible to use the following ones:
5315 When non-nil, use \"ascii-art-to-unicode\" package to translate
5316 the table. You can download it here:
5317 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5321 When non-nil, narrow columns width than provided width cookie,
5322 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5327 (list :backend 'ascii
5328 :ascii-charset 'utf-8
5329 :ascii-table-widen-columns (not (plist-get params :narrow))
5330 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5333 ;; Put the cursor in a column containing numerical values
5336 ;; A new column is added with a bar plot.
5337 ;; When the table is refreshed (C-u C-c *),
5338 ;; the plot is updated to reflect the new values.
5340 (defun orgtbl-ascii-draw (value min max &optional width characters)
5341 "Draw an ascii bar in a table.
5342 VALUE is the value to plot, it determines the width of the bar to draw.
5343 MIN is the value that will be displayed as empty (zero width bar).
5344 MAX is the value that will draw a bar filling all the WIDTH.
5345 WIDTH is the span in characters from MIN to MAX.
5346 CHARACTERS is a string that will compose the bar, with shades of grey
5347 from pure white to pure black. It defaults to a 10 characters string
5348 of regular ascii characters."
5349 (let* ((width (ceiling (or width 12)))
5350 (characters (or characters " .:;c!lhVHW"))
5351 (len (1- (length characters)))
5352 (value (float (if (numberp value)
5353 value (string-to-number value))))
5354 (relative (/ (- value min) (- max min)))
5355 (steps (round (* relative width len))))
5356 (cond ((< steps 0) "too small")
5357 ((> steps (* width len)) "too large")
5358 (t (let* ((int-division (/ steps len))
5359 (remainder (- steps (* int-division len))))
5360 (concat (make-string int-division (elt characters len))
5361 (string (elt characters remainder))))))))
5364 (defun orgtbl-ascii-plot (&optional ask)
5365 "Draw an ASCII bar plot in a column.
5367 With cursor in a column containing numerical values, this function
5368 will draw a plot in a new column.
5370 ASK, if given, is a numeric prefix to override the default 12
5371 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5373 which will prompt for the width."
5375 (let ((col (org-table-current-column))
5376 (min 1e999) ; 1e999 will be converted to infinity
5377 (max -1e999) ; which is the desired result
5378 (table (org-table-to-lisp))
5381 (read-number "Length of column " 12))
5384 ;; Skip any hline a the top of table.
5385 (while (eq (car table) 'hline) (setq table (cdr table)))
5386 ;; Skip table header if any.
5387 (dolist (x (or (cdr (memq 'hline table)) table))
5389 (setq x (nth (1- col) x))
5391 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5393 (setq x (string-to-number x))
5394 (when (> min x) (setq min x))
5395 (when (< max x) (setq max x)))))
5396 (org-table-insert-column)
5397 (org-table-move-column-right)
5398 (org-table-store-formulas
5401 (concat "$" (number-to-string (1+ col)))
5402 (format "'(%s $%s %s %s %s)"
5403 "orgtbl-ascii-draw" col min max length))
5404 (org-table-get-stored-formulas)))
5405 (org-table-recalculate t)))
5407 ;; Example of extension: unicode characters
5408 ;; Here are two examples of different styles.
5410 ;; Unicode block characters are used to give a smooth effect.
5411 ;; See http://en.wikipedia.org/wiki/Block_Elements
5412 ;; Use one of those drawing functions
5413 ;; - orgtbl-ascii-draw (the default ascii)
5414 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5415 ;; - orgtbl-uc-draw-cont (smooth unicode)
5417 ;; This is best viewed with the "DejaVu Sans Mono" font
5418 ;; (use M-x set-default-font).
5420 (defun orgtbl-uc-draw-grid (value min max &optional width)
5421 "Draw a bar in a table using block unicode characters.
5422 It is a variant of orgtbl-ascii-draw with Unicode block
5423 characters, for a smooth display. Bars appear as grids (to the
5424 extent the font allows)."
5425 ;; http://en.wikipedia.org/wiki/Block_Elements
5426 ;; best viewed with the "DejaVu Sans Mono" font.
5427 (orgtbl-ascii-draw value min max width
5428 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5430 (defun orgtbl-uc-draw-cont (value min max &optional width)
5431 "Draw a bar in a table using block unicode characters.
5432 It is a variant of orgtbl-ascii-draw with Unicode block
5433 characters, for a smooth display. Bars are solid (to the extent
5435 (orgtbl-ascii-draw value min max width
5436 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5438 (defun org-table-get-remote-range (name-or-id form)
5439 "Get a field value or a list of values in a range from table at ID.
5441 NAME-OR-ID may be the name of a table in the current file as set
5442 by a \"#+NAME:\" directive. The first table following this line
5443 will then be used. Alternatively, it may be an ID referring to
5444 any entry, also in a different file. In this case, the first
5445 table in that entry will be referenced.
5446 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5447 \"@I$2..@II$2\". All the references must be absolute, not relative.
5449 The return value is either a single string for a single field, or a
5450 list of the fields in the rectangle."
5452 (let ((case-fold-search t) (id-loc nil)
5453 ;; Protect a bunch of variables from being overwritten by
5454 ;; the context of the remote table.
5455 org-table-column-names org-table-column-name-regexp
5456 org-table-local-parameters org-table-named-field-locations
5457 org-table-current-line-types
5458 org-table-current-begin-pos org-table-dlines
5459 org-table-current-ncol
5460 org-table-hlines org-table-last-alignment
5461 org-table-last-column-widths org-table-last-alignment
5462 org-table-last-column-widths
5464 (setq form (org-table-convert-refs-to-rc form))
5465 (org-with-wide-buffer
5466 (goto-char (point-min))
5467 (if (re-search-forward
5468 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5469 (regexp-quote name-or-id) "[ \t]*$")
5471 (setq buffer (current-buffer) loc (match-beginning 0))
5472 (setq id-loc (org-id-find name-or-id 'marker))
5473 (unless (and id-loc (markerp id-loc))
5474 (user-error "Can't find remote table \"%s\"" name-or-id))
5475 (setq buffer (marker-buffer id-loc)
5476 loc (marker-position id-loc))
5477 (move-marker id-loc nil))
5478 (with-current-buffer buffer
5479 (org-with-wide-buffer
5482 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5483 (not (match-beginning 1)))
5484 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5486 (setq form (org-table-formula-substitute-names
5487 (org-table-formula-handle-first/last-rc form)))
5488 (if (and (string-match org-table-range-regexp form)
5489 (> (length (match-string 0 form)) 1))
5490 (org-table-get-range
5491 (match-string 0 form) org-table-current-begin-pos 1)
5494 (defun org-table-remote-reference-indirection (form)
5495 "Return formula with table remote references substituted by indirection.
5496 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5497 This indirection works only with the format @ROW$COLUMN. The
5498 format \"B3\" is not supported because it can not be
5499 distinguished from a plain table name or ID."
5501 ;; Same as in `org-table-eval-formula'.
5502 (concat "\\<remote([ \t]*\\("
5503 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5505 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5506 (replace-regexp-in-string
5510 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5511 (org-table-get-range
5512 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5517 (defmacro org-define-lookup-function (mode)
5518 (let ((mode-str (symbol-name mode))
5519 (first-p (eq mode 'first))
5520 (all-p (eq mode 'all)))
5521 (let ((plural-str (if all-p "s" "")))
5522 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5523 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5524 If R-LIST is nil, return matching element%s of S-LIST.
5525 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5526 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5527 This function is generated by a call to the macro `org-define-lookup-function'."
5528 mode-str plural-str plural-str plural-str)
5529 (let ,(let ((lvars '((p (or predicate 'equal))
5531 (rl (or r-list s-list))
5533 (if first-p (cons '(match-p nil) lvars) lvars))
5534 (while ,(if first-p '(and (not match-p) sl) 'sl)
5535 (when (funcall p val (car sl))
5536 ,(when first-p '(setq match-p t))
5537 (let ((rval (car rl)))
5538 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5539 (setq sl (cdr sl) rl (cdr rl)))
5542 (org-define-lookup-function first)
5543 (org-define-lookup-function last)
5544 (org-define-lookup-function all)
5546 (provide 'org-table)
5549 ;; generated-autoload-file: "org-loaddefs.el"
5552 ;;; org-table.el ends here