1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
40 (declare-function org-element-at-point
"org-element" ())
41 (declare-function org-element-contents
"org-element" (element))
42 (declare-function org-element-extract-element
"org-element" (element))
43 (declare-function org-element-interpret-data
"org-element" (data))
44 (declare-function org-element-lineage
"org-element"
45 (blob &optional types with-self
))
46 (declare-function org-element-map
"org-element"
48 &optional info first-match no-recursion with-affiliated
))
49 (declare-function org-element-parse-buffer
"org-element"
50 (&optional granularity visible-only
))
51 (declare-function org-element-property
"org-element" (property element
))
52 (declare-function org-element-type
"org-element" (element))
54 (declare-function org-export-create-backend
"ox" (&rest rest
) t
)
55 (declare-function org-export-data-with-backend
"ox" (data backend info
))
56 (declare-function org-export-filter-apply-functions
"ox"
58 (declare-function org-export-first-sibling-p
"ox" (blob info
))
59 (declare-function org-export-get-backend
"ox" (name))
60 (declare-function org-export-get-environment
"ox"
61 (&optional backend subtreep ext-plist
))
62 (declare-function org-export-install-filters
"ox" (info))
63 (declare-function org-export-table-has-special-column-p
"ox" (table))
64 (declare-function org-export-table-row-is-special-p
"ox" (table-row info
))
66 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
68 (defvar constants-unit-system
)
69 (defvar org-element-use-cache
)
70 (defvar org-export-filters-alist
)
71 (defvar org-table-follow-field-mode
)
72 (defvar orgtbl-mode
) ; defined below
73 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
74 (defvar sort-fold-case
)
76 (defvar orgtbl-after-send-table-hook nil
77 "Hook for functions attaching to `C-c C-c', if the table is sent.
78 This can be used to add additional functionality after the table is sent
79 to the receiver position, otherwise, if table is not sent, the functions
82 (defvar org-table-TBLFM-begin-regexp
"^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
84 (defcustom orgtbl-optimized 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 (defcustom org-table-shrunk-column-indicator
"…"
426 "String to be displayed in a shrunk column."
427 :group
'org-table-editing
430 :package-version
'(Org .
"9.1")
431 :safe
(lambda (v) (and (stringp v
) (not (equal v
"")))))
433 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
434 "Regexp matching a line marked for automatic recalculation.")
436 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
437 "Regexp matching a line marked for recalculation.")
439 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
440 "Regexp matching a line marked for calculation.")
442 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
443 "Regexp matching any line outside an Org table.")
445 (defvar org-table-last-highlighted-reference nil
)
447 (defvar org-table-formula-history nil
)
449 (defvar org-table-column-names nil
450 "Alist with column names, derived from the `!' line.
451 This variable is initialized with `org-table-analyze'.")
453 (defvar org-table-column-name-regexp nil
454 "Regular expression matching the current column names.
455 This variable is initialized with `org-table-analyze'.")
457 (defvar org-table-local-parameters nil
458 "Alist with parameter names, derived from the `$' line.
459 This variable is initialized with `org-table-analyze'.")
461 (defvar org-table-named-field-locations nil
462 "Alist with locations of named fields.
463 Associations follow the pattern (NAME LINE COLUMN) where
464 NAME is the name of the field as a string,
465 LINE is the number of lines from the beginning of the table,
466 COLUMN is the column of the field, as an integer.
467 This variable is initialized with `org-table-analyze'.")
469 (defvar org-table-current-line-types nil
470 "Table row types in current table.
471 This variable is initialized with `org-table-analyze'.")
473 (defvar org-table-current-begin-pos nil
474 "Current table begin position, as a marker.
475 This variable is initialized with `org-table-analyze'.")
477 (defvar org-table-current-ncol nil
478 "Number of columns in current table.
479 This variable is initialized with `org-table-analyze'.")
481 (defvar org-table-dlines nil
482 "Vector of data line line numbers in the current table.
483 Line numbers are counted from the beginning of the table. This
484 variable is initialized with `org-table-analyze'.")
486 (defvar org-table-hlines nil
487 "Vector of hline line numbers in the current table.
488 Line numbers are counted from the beginning of the table. This
489 variable is initialized with `org-table-analyze'.")
491 (defconst org-table-range-regexp
492 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
494 "Regular expression for matching ranges in formulas.")
496 (defconst org-table-range-regexp2
498 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
500 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
501 "Match a range for reference display.")
503 (defconst org-table-translate-regexp
504 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
505 "Match a reference that needs translation, for reference display.")
507 (defmacro org-table-save-field
(&rest body
)
508 "Save current field; execute BODY; restore field.
509 Field is restored even in case of abnormal exit."
510 (declare (debug (body)))
511 (org-with-gensyms (line column
)
512 `(let ((,line
(copy-marker (line-beginning-position)))
513 (,column
(org-table-current-column)))
517 (org-table-goto-column ,column
)
518 (set-marker ,line nil
)))))
520 (defmacro org-table-with-shrunk-columns
(&rest body
)
521 "Expand all columns before executing BODY, then shrink them again."
522 (declare (debug (body)))
523 (org-with-gensyms (shrunk-columns begin end
)
524 `(let ((,begin
(copy-marker (org-table-begin)))
525 (,end
(copy-marker (org-table-end) t
))
526 (,shrunk-columns
(org-table--list-shrunk-columns)))
527 (org-with-point-at ,begin
(org-table--expand-all-columns ,begin
,end
))
530 (org-table--shrink-columns ,shrunk-columns
,begin
,end
)
531 (set-marker ,begin nil
)
532 (set-marker ,end nil
)))))
535 (defun org-table-create-with-table.el
()
536 "Use the table.el package to insert a new table.
537 If there is already a table at point, convert between Org tables
538 and table.el tables."
543 (if (y-or-n-p "Convert table to Org table? ")
544 (org-table-convert)))
546 (when (y-or-n-p "Convert table to table.el table? ")
548 (org-table-convert)))
549 (t (call-interactively 'table-insert
))))
552 (defun org-table-create-or-convert-from-region (arg)
553 "Convert region to table, or create an empty table.
554 If there is an active region, convert it to a table, using the function
555 `org-table-convert-region'. See the documentation of that function
556 to learn how the prefix argument is interpreted to determine the field
558 If there is no such region, create an empty table with `org-table-create'."
560 (if (org-region-active-p)
561 (org-table-convert-region (region-beginning) (region-end) arg
)
562 (org-table-create arg
)))
565 (defun org-table-create (&optional size
)
566 "Query for a size and insert a table skeleton.
567 SIZE is a string Columns x Rows like for example \"3x2\"."
570 (setq size
(read-string
571 (concat "Table size Columns x Rows [e.g. "
572 org-table-default-size
"]: ")
573 "" nil org-table-default-size
)))
576 (indent (make-string (current-column) ?\
))
577 (split (org-split-string size
" *x *"))
578 (rows (string-to-number (nth 1 split
)))
579 (columns (string-to-number (car split
)))
580 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
582 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
583 (point-at-bol) (point)))
584 (beginning-of-line 1)
586 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
587 (dotimes (_ rows
) (insert line
))
590 ;; Insert a hline after the first row.
598 (defun org-table-convert-region (beg0 end0
&optional separator
)
599 "Convert region to a table.
601 The region goes from BEG0 to END0, but these borders will be moved
602 slightly, to make sure a beginning of line in the first line is included.
604 SEPARATOR specifies the field separator in the lines. It can have the
607 (4) Use the comma as a field separator
608 (16) Use a TAB as field separator
609 (64) Prompt for a regular expression as field separator
610 integer When a number, use that many spaces, or a TAB, as field separator
611 regexp When a regular expression, use it to match the separator
612 nil When nil, the command tries to be smart and figure out the
613 separator in the following way:
614 - when each line contains a TAB, assume TAB-separated material
615 - when each line contains a comma, assume CSV material
616 - else, assume one or more SPACE characters as separator."
618 (let* ((beg (min beg0 end0
))
619 (end (max beg0 end0
))
621 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
622 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
623 org-table-convert-region-max-lines
)
624 (if (equal separator
'(64))
625 (setq separator
(read-regexp "Regexp for field separator")))
627 (beginning-of-line 1)
628 (setq beg
(point-marker))
630 (if (bolp) (backward-char 1) (end-of-line 1))
631 (setq end
(point-marker))
632 ;; Get the right field separator
637 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
638 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
641 (if (equal separator
'(4))
642 (while (< (point) end
)
643 ;; parse the csv stuff
645 ((looking-at "^") (insert "| "))
646 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
647 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
648 (replace-match "\\1")
649 (if (looking-at "\"") (insert "\"")))
650 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
651 ((looking-at "[ \t]*,") (replace-match " | "))
652 (t (beginning-of-line 2))))
654 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
655 ((equal separator
'(16)) "^\\|\t")
656 ((integerp separator
)
658 (user-error "Number of spaces in separator must be >= 1")
659 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
661 (format "^ *\\|%s" separator
))
662 (t (error "This should not happen"))))
663 (while (re-search-forward re end t
)
664 (replace-match "| " t t
)))
669 (defun org-table-import (file arg
)
670 "Import FILE as a table.
671 The file is assumed to be tab-separated. Such files can be produced by most
672 spreadsheet and database applications. If no tabs (at least one per line)
673 are found, lines will be split on whitespace into fields."
675 (or (bolp) (newline))
678 (insert-file-contents file
)
679 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
683 (defun org-table-export (&optional file format
)
684 "Export table to a file, with configurable format.
685 Such a file can be imported into usual spreadsheet programs.
687 FILE can be the output file name. If not given, it will be taken
688 from a TABLE_EXPORT_FILE property in the current entry or higher
689 up in the hierarchy, or the user will be prompted for a file
690 name. FORMAT can be an export format, of the same kind as it
691 used when `orgtbl-mode' sends a table in a different format.
693 The command suggests a format depending on TABLE_EXPORT_FORMAT,
694 whether it is set locally or up in the hierarchy, then on the
695 extension of the given file name, and finally on the variable
696 `org-table-export-default-format'."
698 (unless (org-at-table-p) (user-error "No table at point"))
699 (org-table-align) ; Make sure we have everything we need.
700 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
702 (setq file
(read-file-name "Export table to: "))
703 (unless (or (not (file-exists-p file
))
704 (y-or-n-p (format "Overwrite file %s? " file
)))
705 (user-error "File not written")))
706 (when (file-directory-p file
)
707 (user-error "This is a directory path, not a file"))
708 (when (and (buffer-file-name (buffer-base-buffer))
711 (file-truename (buffer-file-name (buffer-base-buffer)))))
712 (user-error "Please specify a file name that is different from current"))
713 (let ((fileext (concat (file-name-extension file
) "$"))
714 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
716 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
717 "orgtbl-to-html" "orgtbl-to-generic"
718 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
719 "orgtbl-to-unicode"))
721 (replace-regexp-in-string
723 (replace-regexp-in-string
728 (and (string-match-p fileext f
) f
))
730 org-table-export-default-format
)
734 "Format: " formats nil nil deffmt-readable
))))
735 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
736 (let ((transform (intern (match-string 1 format
)))
737 (params (and (match-end 2)
738 (read (concat "(" (match-string 2 format
) ")"))))
739 (table (org-table-to-lisp
740 (buffer-substring-no-properties
741 (org-table-begin) (org-table-end)))))
742 (unless (fboundp transform
)
743 (user-error "No such transformation function %s" transform
))
745 (with-current-buffer (find-file-noselect file
)
746 (setq buf
(current-buffer))
749 (insert (funcall transform table params
) "\n")
752 (message "Export done."))
753 (user-error "TABLE_EXPORT_FORMAT invalid")))))
755 (defvar org-table-aligned-begin-marker
(make-marker)
756 "Marker at the beginning of the table last aligned.
757 Used to check if cursor still is in that table, to minimize realignment.")
758 (defvar org-table-aligned-end-marker
(make-marker)
759 "Marker at the end of the table last aligned.
760 Used to check if cursor still is in that table, to minimize realignment.")
761 (defvar org-table-last-alignment nil
762 "List of flags for flushright alignment, from the last re-alignment.
763 This is being used to correctly align a single field after TAB or RET.")
764 (defvar org-table-last-column-widths nil
765 "List of max width of fields in each column.
766 This is being used to correctly align a single field after TAB or RET.")
767 (defvar-local org-table-formula-debug nil
768 "Non-nil means debug table formulas.
769 When nil, simply write \"#ERROR\" in corrupted fields.")
770 (defvar-local org-table-overlay-coordinates nil
771 "Overlay coordinates after each align of a table.")
773 (defvar org-last-recalc-line nil
)
776 (defun org-table-align ()
777 "Align the table at point by aligning all vertical bars."
779 (let ((beg (org-table-begin))
780 (end (copy-marker (org-table-end))))
781 (org-table-save-field
782 ;; Make sure invisible characters in the table are at the right
783 ;; place since column widths take them into account.
784 (org-font-lock-ensure beg end
)
785 (move-marker org-table-aligned-begin-marker beg
)
786 (move-marker org-table-aligned-end-marker end
)
788 (org-table-with-shrunk-columns
789 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
792 (re-search-forward "|[ \t]*<[lrc][0-9]*>[ \t]*\\(?:|\\|$\\)"
794 ;; Table's rows. Rules are replaced by nil. Trailing
795 ;; spaces are removed.
798 (and (not (string-match-p org-table-hline-regexp l
))
800 (split-string (buffer-substring beg end
) "\n" t
"[ \t]")))
801 ;; List of lists of data fields.
802 (fields (mapcar (lambda (l) (org-split-string l
"[ \t]*|[ \t]*"))
804 ;; Compute number of fields in the longest line. If the
805 ;; table contains no field, create a default table.
806 (maxfields (if fields
(apply #'max
(mapcar #'length fields
))
807 (kill-region beg end
)
808 (org-table-create org-table-default-size
)
809 (user-error "Empty table - created default table")))
810 ;; A list of empty strings to fill any short rows on output.
811 (emptycells (make-list maxfields
""))
813 ;; Compute alignment and width for each column.
814 (dotimes (i maxfields
)
815 (let* ((column (mapcar (lambda (x) (or (nth i x
) ""))
819 (cl-some (lambda (cell)
820 (and (string-match "\\`<\\([lrc]\\)[0-9]*>\\'"
822 (match-string 1 cell
)))
824 ;; Get the maximum width for each column.
825 (push (apply #'max
1 (mapcar #'org-string-width column
))
827 ;; If there is no alignment cookie, get the fraction of
828 ;; numbers among non-empty cells to decide about alignment
830 (if falign
(push (equal (downcase falign
) "r") typenums
)
837 (if (string-match-p org-table-number-regexp x
)
841 (push (>= frac org-table-number-fraction
) typenums
)))))
842 (setq lengths
(nreverse lengths
))
843 (setq typenums
(nreverse typenums
))
844 ;; Store alignment of this table, for later editing of single
846 (setq org-table-last-alignment typenums
)
847 (setq org-table-last-column-widths lengths
)
848 ;; With invisible characters, `format' does not get the field
849 ;; width right So we need to make these fields wide by hand.
850 ;; Invisible characters may be introduced by fontified links,
851 ;; emphasis, macros or sub/superscripts.
852 (when (or (text-property-any beg end
'invisible
'org-link
)
853 (text-property-any beg end
'invisible t
))
854 (dotimes (i maxfields
)
855 (let ((len (nth i lengths
)))
856 (dotimes (j (length fields
))
857 (let* ((c (nthcdr i
(nth j fields
)))
861 (let ((l (length cell
)))
862 (or (text-property-any 0 l
'invisible
'org-link cell
)
863 (text-property-any beg end
'invisible t
)))
864 (< (org-string-width cell
) len
))
865 (let ((s (make-string (- len
(org-string-width cell
)) ?\s
)))
866 (setcar c
(if (nth i typenums
) (concat s cell
)
867 (concat cell s
))))))))))
869 ;; Compute the formats needed for output of the table.
870 (let ((hfmt (concat indent
"|"))
871 (rfmt (concat indent
"|"))
874 (dolist (l lengths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
875 (let ((ty (if (pop typenums
) "" "-"))) ; Flush numbers right.
876 (setq rfmt
(concat rfmt
(format rfmt1 ty l
)))
877 (setq hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
))))))
878 ;; Replace modified lines only.
881 (if l
(apply #'format rfmt
(append (pop fields
) emptycells
))
883 (previous (buffer-substring (point) (line-end-position))))
884 (if (equal previous line
)
887 (delete-region (point) (line-beginning-position 2))))))
889 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
890 (setq org-table-may-need-update nil
))))))
893 (defun org-table-begin (&optional table-type
)
894 "Find the beginning of the table and return its position.
895 With a non-nil optional argument TABLE-TYPE, return the beginning
896 of a table.el-type table. This function assumes point is on
899 (org-element-property :post-affiliated
(org-element-at-point)))
901 (and (re-search-backward org-table-border-regexp nil t
)
902 (line-beginning-position 2))))
906 (defun org-table-end (&optional table-type
)
907 "Find the end of the table and return its position.
908 With a non-nil optional argument TABLE-TYPE, return the end of
909 a table.el-type table. This function assumes point is on
913 (goto-char (org-element-property :end
(org-element-at-point)))
914 (skip-chars-backward " \t\n")
915 (line-beginning-position 2))
916 ((re-search-forward org-table-border-regexp nil t
)
918 ;; When the line right after the table is the last line in
919 ;; the buffer with trailing spaces but no final newline
920 ;; character, be sure to catch the correct ending at its
921 ;; beginning. In any other case, ending is expected to be
923 (t (goto-char (point-max))
924 (skip-chars-backward " \t")
925 (if (bolp) (point) (line-end-position))))))
928 (defun org-table-justify-field-maybe (&optional new
)
929 "Justify the current field, text to left, number to right.
930 Optional argument NEW may specify text to replace the current field content."
932 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
933 ((org-at-table-hline-p))
935 (or (not (eq (marker-buffer org-table-aligned-begin-marker
)
937 (< (point) org-table-aligned-begin-marker
)
938 (>= (point) org-table-aligned-end-marker
)))
939 ;; This is not the same table, force a full re-align.
940 (setq org-table-may-need-update t
))
942 ;; Realign the current field, based on previous full realign.
944 (col (org-table-current-column)))
946 (skip-chars-backward "^|")
947 (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
948 (setq org-table-may-need-update t
)
949 (let* ((numbers?
(nth (1- col
) org-table-last-alignment
))
950 (cell (match-string 0))
951 (field (match-string 1))
952 (len (max 1 (- (org-string-width cell
) 3)))
953 (properly-closed?
(/= (match-beginning 2) (match-end 2)))
954 (fmt (format (if numbers?
" %%%ds %s" " %%-%ds %s")
956 (if properly-closed?
"|"
957 (setq org-table-may-need-update t
)
960 (cond ((not new
) (format fmt field
))
961 ((<= (org-string-width new
) len
) (format fmt new
))
963 (setq org-table-may-need-update t
)
964 (format " %s |" new
)))))
965 (unless (equal new-cell cell
)
966 (let (org-table-may-need-update)
967 (replace-match new-cell t t
)))
968 (goto-char pos
))))))))
971 (defun org-table-next-field ()
972 "Go to the next field in the current table, creating new lines as needed.
973 Before doing so, re-align the table if necessary."
975 (org-table-maybe-eval-formula)
976 (org-table-maybe-recalculate-line)
977 (if (and org-table-automatic-realign
978 org-table-may-need-update
)
980 (let ((end (org-table-end)))
981 (if (org-at-table-hline-p)
985 (re-search-forward "|" end
)
986 (if (looking-at "[ \t]*$")
987 (re-search-forward "|" end
))
988 (if (and (looking-at "-")
989 org-table-tab-jumps-over-hlines
990 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
991 (goto-char (match-beginning 1)))
994 (beginning-of-line 0)
995 (org-table-insert-row 'below
))
996 (if (looking-at " ") (forward-char 1))))
998 (org-table-insert-row 'below
)))))
1001 (defun org-table-previous-field ()
1002 "Go to the previous field in the table.
1003 Before doing so, re-align the table if necessary."
1005 (org-table-justify-field-maybe)
1006 (org-table-maybe-recalculate-line)
1007 (when (and org-table-automatic-realign
1008 org-table-may-need-update
)
1010 (when (org-at-table-hline-p)
1012 (let ((start (org-table-begin))
1016 (search-backward "|" start nil
2)
1017 (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)")
1018 (search-backward "|" start
)))
1021 (user-error "Cannot move to previous table field"))))
1022 (when (looking-at "| ?")
1023 (goto-char (match-end 0))))
1025 (defun org-table-beginning-of-field (&optional n
)
1026 "Move to the beginning of the current table field.
1027 If already at or before the beginning, move to the beginning of the
1029 With numeric argument N, move N-1 fields backward first."
1031 (let ((pos (point)))
1034 (org-table-previous-field))
1035 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1036 (user-error "No more table fields before the current")
1037 (goto-char (match-end 0))
1038 (and (looking-at " ") (forward-char 1)))
1039 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1041 (defun org-table-end-of-field (&optional n
)
1042 "Move to the end of the current table field.
1043 If already at or after the end, move to the end of the next table field.
1044 With numeric argument N, move N-1 fields forward first."
1046 (let ((pos (point)))
1049 (org-table-next-field))
1050 (when (re-search-forward "|" (point-at-eol 1) t
)
1052 (skip-chars-backward " ")
1053 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1055 (if (<= (point) pos
) (org-table-end-of-field 2))))
1058 (defun org-table-next-row ()
1059 "Go to the next row (same column) in the current table.
1060 Before doing so, re-align the table if necessary."
1062 (org-table-maybe-eval-formula)
1063 (org-table-maybe-recalculate-line)
1064 (if (or (looking-at "[ \t]*$")
1065 (save-excursion (skip-chars-backward " \t") (bolp)))
1067 (if (and org-table-automatic-realign
1068 org-table-may-need-update
)
1070 (let ((col (org-table-current-column)))
1071 (beginning-of-line 2)
1072 (if (or (not (org-at-table-p))
1073 (org-at-table-hline-p))
1075 (beginning-of-line 0)
1076 (org-table-insert-row 'below
)))
1077 (org-table-goto-column col
)
1078 (skip-chars-backward "^|\n\r")
1079 (if (looking-at " ") (forward-char 1)))))
1082 (defun org-table-copy-down (n)
1083 "Copy the value of the current field one row below.
1085 If the field at the cursor is empty, copy the content of the
1086 nearest non-empty field above. With argument N, use the Nth
1089 If the current field is not empty, it is copied down to the next
1090 row, and the cursor is moved with it. Therefore, repeating this
1091 command causes the column to be filled row-by-row.
1093 If the variable `org-table-copy-increment' is non-nil and the
1094 field is an integer or a timestamp, it will be incremented while
1095 copying. By default, increment by the difference between the
1096 value in the current field and the one in the field above. To
1097 increment using a fixed integer, set `org-table-copy-increment'
1098 to a number. In the case of a timestamp, increment by days."
1100 (let* ((colpos (org-table-current-column))
1101 (col (current-column))
1102 (field (save-excursion (org-table-get-field)))
1103 (field-up (or (save-excursion
1104 (org-table-get (1- (org-table-current-line))
1105 (org-table-current-column))) ""))
1106 (non-empty (string-match "[^ \t]" field
))
1107 (non-empty-up (string-match "[^ \t]" field-up
))
1108 (beg (org-table-begin))
1111 (org-table-check-inside-data-field)
1116 (while (progn (beginning-of-line 1)
1117 (re-search-backward org-table-dataline-regexp
1119 (org-table-goto-column colpos t
)
1120 (if (and (looking-at
1121 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1122 (<= (setq n
(1- n
)) 0))
1123 (throw 'exit
(match-string 1))))))
1126 (while (progn (beginning-of-line 1)
1127 (re-search-backward org-table-dataline-regexp
1129 (org-table-goto-column colpos t
)
1130 (if (and (looking-at
1131 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1132 (<= (setq n
(1- n
)) 0))
1133 (throw 'exit
(match-string 1))))))
1134 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1135 ;; Above field was not empty, go down to the next row
1136 (setq txt
(org-trim field
))
1137 (org-table-next-row)
1138 (org-table-blank-field))
1139 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1141 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1142 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1143 (string-match org-ts-regexp3 txt
))
1144 (- (org-time-string-to-absolute txt
)
1145 (org-time-string-to-absolute txt-up
)))
1146 ((string-match org-ts-regexp3 txt
) 1)
1147 ((string-match "\\([-+]\\)?[0-9]+\\(?:\.[0-9]+\\)?" txt-up
)
1148 (- (string-to-number txt
)
1149 (string-to-number (match-string 0 txt-up
))))
1153 (user-error "No non-empty field found")
1154 (if (and org-table-copy-increment
1155 (not (equal orig-n
0))
1156 (string-match-p "^[-+^/*0-9eE.]+$" txt
)
1157 (< (string-to-number txt
) 100000000))
1158 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1160 (org-move-to-column col
)
1161 (if (and org-table-copy-increment
(org-at-timestamp-p))
1162 (org-timestamp-up-day inc
)
1163 (org-table-maybe-recalculate-line))
1165 (org-move-to-column col
))))
1167 (defun org-table-check-inside-data-field (&optional noerror
)
1168 "Is point inside a table data field?
1169 I.e. not on a hline or before the first or after the last column?
1170 This actually throws an error, so it aborts the current command."
1171 (cond ((and (org-at-table-p)
1172 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1173 (not (org-at-table-hline-p))
1174 (not (looking-at "[ \t]*$"))))
1176 (t (user-error "Not in table data field"))))
1178 (defvar org-table-clip nil
1179 "Clipboard for table regions.")
1181 (defun org-table-get (line column
)
1182 "Get the field in table line LINE, column COLUMN.
1183 If LINE is larger than the number of data lines in the table, the function
1184 returns nil. However, if COLUMN is too large, we will simply return an
1186 If LINE is nil, use the current line.
1187 If COLUMN is nil, use the current column."
1188 (setq column
(or column
(org-table-current-column)))
1190 (and (or (not line
) (org-table-goto-line line
))
1191 (org-trim (org-table-get-field column
)))))
1193 (defun org-table-put (line column value
&optional align
)
1194 "Put VALUE into line LINE, column COLUMN.
1195 When ALIGN is set, also realign the table."
1196 (setq column
(or column
(org-table-current-column)))
1197 (prog1 (save-excursion
1198 (and (or (not line
) (org-table-goto-line line
))
1199 (progn (org-table-goto-column column nil
'force
) t
)
1200 (org-table-get-field column value
)))
1201 (and align
(org-table-align))))
1203 (defun org-table-current-line ()
1204 "Return the index of the current data line."
1205 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1207 (goto-char (org-table-begin))
1208 (while (and (re-search-forward org-table-dataline-regexp end t
)
1210 (< (point-at-eol) pos
))))
1213 (defun org-table-goto-line (N)
1214 "Go to the Nth data line in the current table.
1215 Return t when the line exists, nil if it does not exist."
1216 (goto-char (org-table-begin))
1217 (let ((end (org-table-end)) (cnt 0))
1218 (while (and (re-search-forward org-table-dataline-regexp end t
)
1219 (< (setq cnt
(1+ cnt
)) N
)))
1223 (defun org-table-blank-field ()
1224 "Blank the current table field or active region."
1226 (org-table-check-inside-data-field)
1227 (if (and (called-interactively-p 'any
) (org-region-active-p))
1228 (let (org-table-clip)
1229 (org-table-cut-region (region-beginning) (region-end)))
1230 (skip-chars-backward "^|")
1232 (if (looking-at "|[^|\n]+")
1233 (let* ((pos (match-beginning 0))
1234 (match (match-string 0))
1235 (len (org-string-width match
)))
1236 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1237 (goto-char (+ 2 pos
))
1238 (substring match
1)))))
1240 (defun org-table-get-field (&optional n replace
)
1241 "Return the value of the field in column N of current row.
1242 N defaults to current column. If REPLACE is a string, replace
1243 field with this value. The return value is always the old
1245 (when n
(org-table-goto-column n
))
1246 (skip-chars-backward "^|\n")
1247 (if (or (bolp) (looking-at-p "[ \t]*$"))
1248 ;; Before first column or after last one.
1250 (looking-at "[^|\r\n]*")
1251 (let* ((pos (match-beginning 0))
1252 (val (buffer-substring pos
(match-end 0))))
1254 ;; Since we are going to remove any hidden field, do not rely
1255 ;; on `org-table--hidden-field' as it could be GC'ed before
1257 (let* ((hide-overlay (org-table--shrunk-field))
1258 (begin (and hide-overlay
(overlay-start hide-overlay
))))
1259 (when hide-overlay
(delete-overlay hide-overlay
))
1260 (replace-match (if (equal replace
"") " " replace
) t t
)
1262 (move-overlay hide-overlay
1263 begin
(+ begin
(min 1 (length replace
)))))))
1264 (goto-char (min (line-end-position) (1+ pos
)))
1268 (defun org-table-field-info (_arg)
1269 "Show info about the current field, and highlight any reference at point."
1271 (unless (org-at-table-p) (user-error "Not at a table"))
1274 (let* ((pos (point))
1275 (col (org-table-current-column))
1276 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1277 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1278 (line-beginning-position))
1280 org-table-named-field-locations
)))
1281 (eql (org-table-expand-lhs-ranges
1284 (cons (org-table-formula-handle-first/last-rc
(car e
))
1286 (org-table-get-stored-formulas))))
1287 (dline (org-table-current-dline))
1288 (ref (format "@%d$%d" dline col
))
1289 (ref1 (org-table-convert-refs-to-an ref
))
1290 ;; Prioritize field formulas over column formulas.
1291 (fequation (or (assoc name eql
) (assoc ref eql
)))
1292 (cequation (assoc (format "$%d" col
) eql
))
1293 (eqn (or fequation cequation
)))
1294 (let ((p (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))))
1295 (when p
(setq eqn p
)))
1297 (ignore-errors (org-table-show-reference 'local
))
1298 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1300 (if cname
(concat " or $" cname
) "")
1302 (if name
(concat " or $" name
) "")
1303 ;; FIXME: formula info not correct if special table line
1305 (concat ", formula: "
1306 (org-table-formula-to-user
1308 (if (or (string-prefix-p "$" (car eqn
))
1309 (string-prefix-p "@" (car eqn
)))
1312 (car eqn
) "=" (cdr eqn
))))
1315 (defun org-table-current-column ()
1316 "Find out which column we are in."
1319 (let ((column 0) (pos (point)))
1321 (while (search-forward "|" pos t
) (cl-incf column
))
1324 (defun org-table-current-dline ()
1325 "Find out what table data line we are in.
1326 Only data lines count for this."
1329 (pos (line-beginning-position)))
1330 (goto-char (org-table-begin))
1331 (while (<= (point) pos
)
1332 (when (looking-at org-table-dataline-regexp
) (cl-incf c
))
1337 (defun org-table-goto-column (n &optional on-delim force
)
1338 "Move the cursor to the Nth column in the current table line.
1339 With optional argument ON-DELIM, stop with point before the left delimiter
1341 If there are less than N fields, just go to after the last delimiter.
1342 However, when FORCE is non-nil, create new columns if necessary."
1344 (beginning-of-line 1)
1346 (while (and (> (setq n
(1- n
)) -
1)
1347 (or (search-forward "|" (point-at-eol) t
)
1349 (progn (end-of-line 1)
1350 (skip-chars-backward "^|")
1353 (when (and force
(not (looking-at ".*|")))
1354 (save-excursion (end-of-line 1) (insert " | ")))
1357 (if (looking-at " ") (forward-char 1)))))
1360 (defun org-table-insert-column ()
1361 "Insert a new column into the table."
1363 (unless (org-at-table-p) (user-error "Not at a table"))
1364 (org-table-find-dataline)
1365 (let ((col (max 1 (org-table-current-column)))
1366 (beg (org-table-begin))
1367 (end (copy-marker (org-table-end)))
1368 (shrunk-columns (org-table--list-shrunk-columns)))
1369 (org-table--expand-all-columns beg end
)
1370 (org-table-save-field
1372 (while (< (point) end
)
1373 (unless (org-at-table-hline-p)
1374 (org-table-goto-column col t
)
1378 ;; Shift appropriately stored shrunk column numbers, then hide the
1380 (org-table--shrink-columns (mapcar (lambda (c) (if (< c col
) c
(1+ c
)))
1383 (set-marker end nil
)
1384 ;; Fix TBLFM formulas, if desirable.
1385 (when (or (not org-table-fix-formulas-confirm
)
1386 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1387 (org-table-fix-formulas "$" nil
(1- col
) 1)
1388 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1390 (defun org-table-find-dataline ()
1391 "Find a data line in the current table, which is needed for column commands."
1392 (if (and (org-at-table-p)
1393 (not (org-at-table-hline-p)))
1395 (let ((col (current-column))
1396 (end (org-table-end)))
1397 (org-move-to-column col
)
1398 (while (and (< (point) end
)
1399 (or (not (= (current-column) col
))
1400 (org-at-table-hline-p)))
1401 (beginning-of-line 2)
1402 (org-move-to-column col
))
1403 (if (and (org-at-table-p)
1404 (not (org-at-table-hline-p)))
1407 "Please position cursor in a data line for column operations")))))
1409 (defun org-table-line-to-dline (line &optional above
)
1410 "Turn a buffer line number into a data line number.
1412 If there is no data line in this line, return nil.
1414 If there is no matching dline (most likely the reference was
1415 a hline), the first dline below it is used. When ABOVE is
1416 non-nil, the one above is used."
1418 (max (1- (length org-table-dlines
))))
1419 (cond ((or (> (aref org-table-dlines min
) line
)
1420 (< (aref org-table-dlines max
) line
))
1422 ((= (aref org-table-dlines max
) line
) max
)
1424 (while (> (- max min
) 1)
1425 (let* ((mean (/ (+ max min
) 2))
1426 (v (aref org-table-dlines mean
)))
1427 (cond ((= v line
) (throw 'exit mean
))
1428 ((> v line
) (setq max mean
))
1429 (t (setq min mean
)))))
1430 (if above min max
))))))
1433 (defun org-table-delete-column ()
1434 "Delete a column from the table."
1436 (unless (org-at-table-p) (user-error "Not at a table"))
1437 (org-table-find-dataline)
1438 (org-table-check-inside-data-field)
1439 (let* ((col (org-table-current-column))
1440 (beg (org-table-begin))
1441 (end (copy-marker (org-table-end)))
1442 (shrunk-columns (remq col
(org-table--list-shrunk-columns))))
1443 (org-table--expand-all-columns beg end
)
1444 (org-table-save-field
1446 (while (< (point) end
)
1447 (if (org-at-table-hline-p)
1449 (org-table-goto-column col t
)
1450 (and (looking-at "|[^|\n]+|")
1451 (replace-match "|")))
1453 (org-table-goto-column (max 1 (1- col
)))
1455 ;; Shift appropriately stored shrunk column numbers, then hide the
1457 (org-table--shrink-columns (mapcar (lambda (c) (if (< c col
) c
(1- c
)))
1460 (set-marker end nil
)
1461 ;; Fix TBLFM formulas, if desirable.
1462 (when (or (not org-table-fix-formulas-confirm
)
1463 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1464 (org-table-fix-formulas
1465 "$" (list (cons (number-to-string col
) "INVALID")) col -
1 col
)
1466 (org-table-fix-formulas
1467 "$LR" (list (cons (number-to-string col
) "INVALID")) col -
1 col
))))
1470 (defun org-table-move-column-right ()
1471 "Move column to the right."
1473 (org-table-move-column nil
))
1476 (defun org-table-move-column-left ()
1477 "Move column to the left."
1479 (org-table-move-column 'left
))
1482 (defun org-table-move-column (&optional left
)
1483 "Move the current column to the right. With arg LEFT, move to the left."
1485 (unless (org-at-table-p) (user-error "Not at a table"))
1486 (org-table-find-dataline)
1487 (org-table-check-inside-data-field)
1488 (let* ((col (org-table-current-column))
1489 (col1 (if left
(1- col
) col
))
1490 (colpos (if left
(1- col
) (1+ col
)))
1491 (beg (org-table-begin))
1492 (end (copy-marker (org-table-end))))
1493 (when (and left
(= col
1))
1494 (user-error "Cannot move column further left"))
1495 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1496 (user-error "Cannot move column further right"))
1497 (let ((shrunk-columns (org-table--list-shrunk-columns)))
1498 (org-table--expand-all-columns beg end
)
1499 (org-table-save-field
1501 (while (< (point) end
)
1502 (unless (org-at-table-hline-p)
1503 (org-table-goto-column col1 t
)
1504 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1506 (match-beginning 1) (match-end 1)
1507 (match-beginning 2) (match-end 2))))
1509 (org-table-goto-column colpos
)
1511 ;; Shift appropriately stored shrunk column numbers, then shrink
1512 ;; the columns again.
1513 (org-table--shrink-columns
1515 (cond ((and (= col c
) left
) (1- c
))
1517 ((and (= col
(1+ c
)) left
) (1+ c
))
1518 ((and (= col
(1- c
)) (not left
) (1- c
)))
1522 (set-marker end nil
)
1523 ;; Fix TBLFM formulas, if desirable.
1524 (when (or (not org-table-fix-formulas-confirm
)
1525 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1526 (org-table-fix-formulas
1527 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1528 (cons (number-to-string colpos
) (number-to-string col
))))
1529 (org-table-fix-formulas
1531 (cons (number-to-string col
) (number-to-string colpos
))
1532 (cons (number-to-string colpos
) (number-to-string col
))))))))
1535 (defun org-table-move-row-down ()
1536 "Move table row down."
1538 (org-table-move-row nil
))
1541 (defun org-table-move-row-up ()
1542 "Move table row up."
1544 (org-table-move-row 'up
))
1547 (defun org-table-move-row (&optional up
)
1548 "Move the current table line down. With arg UP, move it up."
1550 (let* ((col (current-column))
1552 (hline1p (save-excursion (beginning-of-line 1)
1553 (looking-at org-table-hline-regexp
)))
1554 (dline1 (org-table-current-dline))
1555 (dline2 (+ dline1
(if up -
1 1)))
1558 (when (and up
(= (point-min) (line-beginning-position)))
1559 (user-error "Cannot move row further"))
1560 (beginning-of-line tonew
)
1561 (when (or (and (not up
) (eobp)) (not (org-at-table-p)))
1563 (user-error "Cannot move row further"))
1564 (org-table-with-shrunk-columns
1565 (setq hline2p
(looking-at org-table-hline-regexp
))
1567 (let ((row (delete-and-extract-region (line-beginning-position)
1568 (line-beginning-position 2))))
1569 (beginning-of-line tonew
)
1570 (unless (bolp) (insert "\n")) ;at eob without a newline
1572 (unless (bolp) (insert "\n")) ;missing final newline in ROW
1573 (beginning-of-line 0)
1574 (org-move-to-column col
)
1575 (unless (or hline1p hline2p
1576 (not (or (not org-table-fix-formulas-confirm
)
1577 (funcall org-table-fix-formulas-confirm
1578 "Fix formulas? "))))
1579 (org-table-fix-formulas
1581 (cons (number-to-string dline1
) (number-to-string dline2
))
1582 (cons (number-to-string dline2
) (number-to-string dline1
)))))))))
1585 (defun org-table-insert-row (&optional arg
)
1586 "Insert a new row above the current line into the table.
1587 With prefix ARG, insert below the current line."
1589 (unless (org-at-table-p) (user-error "Not at a table"))
1590 (org-table-with-shrunk-columns
1591 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1592 (new (org-table-clean-line line
)))
1593 ;; Fix the first field if necessary
1594 (when (string-match "^[ \t]*| *[#$] *|" line
)
1595 (setq new
(replace-match (match-string 0 line
) t t new
)))
1596 (beginning-of-line (if arg
2 1))
1597 ;; Buffer may not end of a newline character, so ensure
1598 ;; (beginning-of-line 2) moves point to a new line.
1599 (unless (bolp) (insert "\n"))
1600 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1601 (beginning-of-line 0)
1602 (re-search-forward "| ?" (line-end-position) t
)
1603 (when (or org-table-may-need-update org-table-overlay-coordinates
)
1605 (when (or (not org-table-fix-formulas-confirm
)
1606 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1607 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))))
1610 (defun org-table-insert-hline (&optional above
)
1611 "Insert a horizontal-line below the current line into the table.
1612 With prefix ABOVE, insert above the current line."
1614 (unless (org-at-table-p) (user-error "Not at a table"))
1615 (when (eobp) (save-excursion (insert "\n")))
1616 (unless (string-match-p "|[ \t]*$" (org-current-line-string))
1618 (org-table-with-shrunk-columns
1619 (let ((line (org-table-clean-line
1620 (buffer-substring (point-at-bol) (point-at-eol))))
1621 (col (current-column)))
1622 (while (string-match "|\\( +\\)|" line
)
1623 (setq line
(replace-match
1624 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1625 ?-
) "|") t t line
)))
1626 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1627 (beginning-of-line (if above
1 2))
1629 (beginning-of-line (if above
1 -
1))
1630 (org-move-to-column col
)
1631 (when org-table-overlay-coordinates
(org-table-align)))))
1634 (defun org-table-hline-and-move (&optional same-column
)
1635 "Insert a hline and move to the row below that line."
1637 (let ((col (org-table-current-column)))
1638 (org-table-maybe-eval-formula)
1639 (org-table-maybe-recalculate-line)
1640 (org-table-insert-hline)
1642 (if (looking-at "\n[ \t]*|-")
1643 (progn (insert "\n|") (org-table-align))
1644 (org-table-next-field))
1645 (if same-column
(org-table-goto-column col
))))
1647 (defun org-table-clean-line (s)
1648 "Convert a table line S into a string with only \"|\" and space.
1649 In particular, this does handle wide and invisible characters."
1650 (if (string-match "^[ \t]*|-" s
)
1651 ;; It's a hline, just map the characters
1652 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1653 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1654 (setq s
(replace-match
1655 (concat "|" (make-string (org-string-width (match-string 1 s
))
1661 (defun org-table-kill-row ()
1662 "Delete the current row or horizontal line from the table."
1664 (unless (org-at-table-p) (user-error "Not at a table"))
1665 (let ((col (current-column))
1666 (dline (org-table-current-dline)))
1667 (org-table-with-shrunk-columns
1668 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1669 (if (not (org-at-table-p)) (beginning-of-line 0))
1670 (org-move-to-column col
)
1671 (when (or (not org-table-fix-formulas-confirm
)
1672 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1673 (org-table-fix-formulas
1674 "@" (list (cons (number-to-string dline
) "INVALID")) dline -
1 dline
)))))
1677 (defun org-table-sort-lines
1678 (&optional with-case sorting-type getkey-func compare-func interactive?
)
1679 "Sort table lines according to the column at point.
1681 The position of point indicates the column to be used for
1682 sorting, and the range of lines is the range between the nearest
1683 horizontal separator lines, or the entire table of no such lines
1684 exist. If point is before the first column, you will be prompted
1685 for the sorting column. If there is an active region, the mark
1686 specifies the first line and the sorting column, while point
1687 should be in the last line to be included into the sorting.
1689 The command then prompts for the sorting type which can be
1690 alphabetically, numerically, or by time (as given in a time stamp
1691 in the field, or as a HH:MM value). Sorting in reverse order is
1694 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1696 If SORTING-TYPE is specified when this function is called from a Lisp
1697 program, no prompting will take place. SORTING-TYPE must be a character,
1698 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1699 sorting should be done in reverse order.
1701 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1702 a function to be called to extract the key. It must return a value
1703 that is compatible with COMPARE-FUNC, the function used to compare
1706 A non-nil value for INTERACTIVE? is used to signal that this
1707 function is being called interactively."
1708 (interactive (list current-prefix-arg nil nil nil t
))
1709 (when (org-region-active-p) (goto-char (region-beginning)))
1710 ;; Point must be either within a field or before a data line.
1712 (skip-chars-backward " \t")
1713 (when (bolp) (search-forward "|" (line-end-position) t
))
1714 (org-table-check-inside-data-field))
1715 ;; Set appropriate case sensitivity and column used for sorting.
1716 (let ((column (let ((c (org-table-current-column)))
1719 (read-number "Use column N for sorting: "))
1723 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1724 \[t]ime, [f]unc. A/N/T/F means reversed: ")))
1725 (start (org-table-begin))
1726 (end (org-table-end)))
1728 ;; Narrow buffer to appropriate sorting area.
1729 (if (org-region-active-p)
1730 (progn (goto-char (region-beginning))
1733 (save-excursion (goto-char (region-end))
1734 (line-beginning-position 2))))
1737 (if (re-search-backward org-table-hline-regexp start t
)
1738 (line-beginning-position 2)
1740 (if (save-excursion (re-search-forward org-table-hline-regexp end t
))
1743 ;; Determine arguments for `sort-subr'. Also record original
1744 ;; position. `org-table-save-field' cannot help here since
1745 ;; sorting is too much destructive.
1746 (let* ((sort-fold-case (not with-case
))
1748 (cons (count-lines (point-min) (line-beginning-position))
1750 (extract-key-from-field
1751 ;; Function to be called on the contents of the field
1752 ;; used for sorting in the current row.
1753 (cl-case sorting-type
1754 ((?n ?N
) #'string-to-number
)
1755 ((?a ?A
) #'org-sort-remove-invisible
)
1758 (cond ((string-match org-ts-regexp-both f
)
1760 (org-time-string-to-time (match-string 0 f
))))
1761 ((org-duration-p f
) (org-duration-to-minutes f
))
1762 ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f
)
1763 (org-duration-to-minutes (match-string 0 f
)))
1768 (org-read-function "Function for extracting keys: "))
1769 (error "Missing key extractor to sort rows")))
1770 (t (user-error "Invalid sorting type `%c'" sorting-type
))))
1772 (cl-case sorting-type
1779 "Function for comparing keys (empty for default \
1780 `sort-subr' predicate): "
1782 (shrunk-columns (remq column
(org-table--list-shrunk-columns))))
1783 (goto-char (point-min))
1784 (sort-subr (memq sorting-type
'(?A ?N ?T ?F
))
1787 (while (and (not (eobp))
1788 (not (looking-at org-table-dataline-regexp
)))
1792 (funcall extract-key-from-field
1793 (org-trim (org-table-get-field column
))))
1796 ;; Hide all columns but the one being sorted.
1797 (org-table--shrink-columns shrunk-columns start end
)
1798 ;; Move back to initial field.
1799 (forward-line (car coordinates
))
1800 (move-to-column (cdr coordinates
))))))
1803 (defun org-table-cut-region (beg end
)
1804 "Copy region in table to the clipboard and blank all relevant fields.
1805 If there is no active region, use just the field at point."
1807 (if (org-region-active-p) (region-beginning) (point))
1808 (if (org-region-active-p) (region-end) (point))))
1809 (org-table-copy-region beg end
'cut
))
1812 (defun org-table-copy-region (beg end
&optional cut
)
1813 "Copy rectangular region in table to clipboard.
1814 A special clipboard is used which can only be accessed
1815 with `org-table-paste-rectangle'."
1817 (if (org-region-active-p) (region-beginning) (point))
1818 (if (org-region-active-p) (region-end) (point))
1819 current-prefix-arg
))
1820 (goto-char (min beg end
))
1821 (org-table-check-inside-data-field)
1822 (let ((beg (line-beginning-position))
1823 (c01 (org-table-current-column))
1825 (goto-char (max beg end
))
1826 (org-table-check-inside-data-field)
1827 (let* ((end (copy-marker (line-end-position)))
1828 (c02 (org-table-current-column))
1829 (column-start (min c01 c02
))
1830 (column-end (max c01 c02
))
1831 (column-number (1+ (- column-end column-start
)))
1832 (rpl (and cut
" ")))
1834 (while (< (point) end
)
1835 (unless (org-at-table-hline-p)
1836 ;; Collect every cell between COLUMN-START and COLUMN-END.
1838 (dotimes (c column-number
)
1839 (push (org-table-get-field (+ c column-start
) rpl
) cols
))
1840 (push (nreverse cols
) region
)))
1842 (set-marker end nil
))
1843 (when cut
(org-table-align))
1844 (setq org-table-clip
(nreverse region
))))
1847 (defun org-table-paste-rectangle ()
1848 "Paste a rectangular region into a table.
1849 The upper right corner ends up in the current field. All involved fields
1850 will be overwritten. If the rectangle does not fit into the present table,
1851 the table is enlarged as needed. The process ignores horizontal separator
1854 (unless (consp org-table-clip
)
1855 (user-error "First cut/copy a region to paste!"))
1856 (org-table-check-inside-data-field)
1857 (let* ((column (org-table-current-column))
1858 (org-table-automatic-realign nil
))
1859 (org-table-save-field
1860 (dolist (row org-table-clip
)
1861 (while (org-at-table-hline-p) (forward-line))
1862 ;; If we left the table, create a new row.
1863 (when (and (bolp) (not (looking-at "[ \t]*|")))
1865 (org-table-next-field))
1868 (org-table-goto-column c nil
'force
)
1869 (org-table-get-field nil field
)
1875 (defun org-table-convert ()
1876 "Convert from `org-mode' table to table.el and back.
1877 Obviously, this only works within limits. When an Org table is converted
1878 to table.el, all horizontal separator lines get lost, because table.el uses
1879 these as cell boundaries and has no notion of horizontal lines. A table.el
1880 table can be converted to an Org table only if it does not do row or column
1881 spanning. Multiline cells will become multiple cells. Beware, Org mode
1882 does not test if the table can be successfully converted - it blindly
1883 applies a recipe that works for simple tables."
1886 (if (org-at-table.el-p
)
1887 ;; convert to Org table
1888 (let ((beg (copy-marker (org-table-begin t
)))
1889 (end (copy-marker (org-table-end t
))))
1890 (table-unrecognize-region beg end
)
1892 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1895 (if (org-at-table-p)
1896 ;; convert to table.el table
1897 (let ((beg (copy-marker (org-table-begin)))
1898 (end (copy-marker (org-table-end))))
1899 ;; first, get rid of all horizontal lines
1901 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1903 ;; insert a hline before first
1905 (org-table-insert-hline 'above
)
1906 (beginning-of-line -
1)
1907 ;; insert a hline after each line
1908 (while (progn (beginning-of-line 3) (< (point) end
))
1909 (org-table-insert-hline))
1911 (setq end
(move-marker end
(org-table-end)))
1912 ;; replace "+" at beginning and ending of hlines
1913 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1914 (replace-match "\\1+-"))
1916 (while (re-search-forward "-|[ \t]*$" end t
)
1917 (replace-match "-+"))
1920 (defun org-table-transpose-table-at-point ()
1921 "Transpose Org table at point and eliminate hlines.
1929 will be transposed as
1936 Note that horizontal lines disappear."
1938 (let* ((table (delete 'hline
(org-table-to-lisp)))
1939 (dline_old (org-table-current-line))
1940 (col_old (org-table-current-column))
1941 (contents (mapcar (lambda (_)
1947 (setq tp
(cdr tp
))))
1950 (goto-char (org-table-begin))
1951 (re-search-forward "|")
1953 (delete-region (point) (org-table-end))
1956 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1958 (org-table-goto-line col_old
)
1959 (org-table-goto-column dline_old
))
1963 (defun org-table-wrap-region (arg)
1964 "Wrap several fields in a column like a paragraph.
1965 This is useful if you'd like to spread the contents of a field over several
1966 lines, in order to keep the table compact.
1968 If there is an active region, and both point and mark are in the same column,
1969 the text in the column is wrapped to minimum width for the given number of
1970 lines. Generally, this makes the table more compact. A prefix ARG may be
1971 used to change the number of desired lines. For example, \
1972 `C-2 \\[org-table-wrap-region]'
1973 formats the selected text to two lines. If the region was longer than two
1974 lines, the remaining lines remain empty. A negative prefix argument reduces
1975 the current number of lines by that amount. The wrapped text is pasted back
1976 into the table. If you formatted it to more lines than it was before, fields
1977 further down in the table get overwritten - so you might need to make space in
1980 If there is no region, the current field is split at the cursor position and
1981 the text fragment to the right of the cursor is prepended to the field one
1984 If there is no region, but you specify a prefix ARG, the current field gets
1985 blank, and the content is appended to the field above."
1987 (org-table-check-inside-data-field)
1988 (if (org-region-active-p)
1989 ;; There is a region: fill as a paragraph.
1990 (let ((start (region-beginning)))
1991 (org-table-cut-region (region-beginning) (region-end))
1992 (when (> (length (car org-table-clip
)) 1)
1993 (user-error "Region must be limited to single column"))
1994 (let ((nlines (cond ((not arg
) (length org-table-clip
))
1995 ((< arg
1) (+ (length org-table-clip
) arg
))
1997 (setq org-table-clip
1999 (org-wrap (mapconcat #'car org-table-clip
" ")
2003 (org-table-paste-rectangle))
2004 ;; No region, split the current field at point.
2005 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
2006 (skip-chars-forward "^\r\n|"))
2008 (arg ; Combine with field above.
2009 (let ((s (org-table-blank-field))
2010 (col (org-table-current-column)))
2012 (while (org-at-table-hline-p) (forward-line -
1))
2013 (org-table-goto-column col
)
2014 (skip-chars-forward "^|")
2015 (skip-chars-backward " ")
2016 (insert " " (org-trim s
))
2018 ((looking-at "\\([^|]+\\)+|") ; Split field.
2019 (let ((s (match-string 1)))
2020 (replace-match " |")
2021 (goto-char (match-beginning 0))
2022 (org-table-next-row)
2023 (insert (org-trim s
) " ")
2025 (t (org-table-next-row)))))
2027 (defvar org-field-marker nil
)
2030 (defun org-table-edit-field (arg)
2031 "Edit table field in a different window.
2032 This is mainly useful for fields that contain hidden parts.
2034 When called with a `\\[universal-argument]' prefix, just make the full field
2035 visible so that it can be edited in place.
2037 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2038 toggle `org-table-follow-field-mode'."
2040 (unless (org-at-table-p) (user-error "Not at a table"))
2043 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2045 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2046 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2047 (remove-text-properties b e
'(invisible t intangible t
))
2048 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2049 (font-lock-fontify-block))))
2051 (let ((pos (point-marker))
2053 (if (eq org-table-use-standard-references t
)
2054 (concat (org-number-to-letters (org-table-current-column))
2055 (int-to-string (org-table-current-dline)))
2056 (concat "@" (int-to-string (org-table-current-dline))
2057 "$" (int-to-string (org-table-current-column)))))
2058 (field (org-table-get-field))
2059 (cw (current-window-configuration))
2062 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2063 (when (and (local-variable-p 'org-field-marker
)
2064 (markerp org-field-marker
))
2065 (move-marker org-field-marker nil
))
2067 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2068 (let ((org-inhibit-startup t
)) (org-mode))
2070 (setq truncate-lines nil
)
2072 (goto-char (setq p
(point-max)))
2073 (insert (org-trim field
))
2074 (remove-text-properties p
(point-max) '(invisible t intangible t
))
2076 (setq-local org-finish-function
'org-table-finish-edit-field
)
2077 (setq-local org-window-configuration cw
)
2078 (setq-local org-field-marker pos
)
2079 (message "Edit and finish with C-c C-c")))))
2081 (defun org-table-finish-edit-field ()
2082 "Finish editing a table data field.
2083 Remove all newline characters, insert the result into the table, realign
2084 the table and kill the editing buffer."
2085 (let ((pos org-field-marker
)
2086 (cw org-window-configuration
)
2087 (cb (current-buffer))
2089 (goto-char (point-min))
2090 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2091 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2092 (replace-match " "))
2093 (setq text
(org-trim (buffer-string)))
2094 (set-window-configuration cw
)
2096 (select-window (get-buffer-window (marker-buffer pos
)))
2098 (move-marker pos nil
)
2099 (org-table-check-inside-data-field)
2100 (org-table-get-field nil text
)
2102 (message "New field value inserted")))
2104 (define-minor-mode org-table-follow-field-mode
2105 "Minor mode to make the table field editor window follow the cursor.
2106 When this mode is active, the field editor window will always show the
2107 current field. The mode exits automatically when the cursor leaves the
2108 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2109 nil
" TblFollow" nil
2110 (if org-table-follow-field-mode
2111 (add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2113 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2114 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2115 (win (and buf
(get-buffer-window buf
))))
2116 (when win
(delete-window win
))
2118 (with-current-buffer buf
2119 (move-marker org-field-marker nil
))
2120 (kill-buffer buf
)))))
2122 (defun org-table-follow-fields-with-editor ()
2123 (if (and org-table-exit-follow-field-mode-when-leaving-table
2124 (not (org-at-table-p)))
2125 ;; We have left the table, exit the follow mode
2126 (org-table-follow-field-mode -
1)
2127 (when (org-table-check-inside-data-field 'noerror
)
2128 (let ((win (selected-window)))
2129 (org-table-edit-field nil
)
2130 (org-fit-window-to-buffer)
2131 (select-window win
)))))
2133 (defvar org-timecnt
) ; dynamically scoped parameter
2136 (defun org-table-sum (&optional beg end nlast
)
2137 "Sum numbers in region of current table column.
2138 The result will be displayed in the echo area, and will be available
2139 as kill to be inserted with \\[yank].
2141 If there is an active region, it is interpreted as a rectangle and all
2142 numbers in that rectangle will be summed. If there is no active
2143 region and point is located in a table column, sum all numbers in that
2146 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2147 numbers are assumed to be times as well (in decimal hours) and the
2148 numbers are added as such.
2150 If NLAST is a number, only the NLAST fields will actually be summed."
2153 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2155 ((and beg end
)) ; beg and end given explicitly
2156 ((org-region-active-p)
2157 (setq beg
(region-beginning) end
(region-end)))
2159 (setq col
(org-table-current-column))
2160 (goto-char (org-table-begin))
2161 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2162 (user-error "No table data"))
2163 (org-table-goto-column col
)
2165 (goto-char (org-table-end))
2166 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2167 (user-error "No table data"))
2168 (org-table-goto-column col
)
2169 (setq end
(point))))
2170 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2171 (items1 (cond ((not nlast
) items
)
2172 ((>= nlast
(length items
)) items
)
2173 (t (setq items
(reverse items
))
2174 (setcdr (nthcdr (1- nlast
) items
) nil
)
2176 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2178 (res (apply '+ numbers
))
2179 (sres (if (= org-timecnt
0)
2180 (number-to-string res
)
2181 (setq diff
(* 3600 res
)
2182 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2183 m
(floor (/ diff
60)) diff
(mod diff
60)
2185 (format "%.0f:%02.0f:%02.0f" h m s
))))
2187 (when (called-interactively-p 'interactive
)
2188 (message "%s" (substitute-command-keys
2189 (format "Sum of %d items: %-20s \
2190 \(\\[yank] will insert result into buffer)" (length numbers
) sres
))))
2193 (defun org-table-get-number-for-summing (s)
2195 (if (string-match "^ *|? *" s
)
2196 (setq s
(replace-match "" nil nil s
)))
2197 (if (string-match " *|? *$" s
)
2198 (setq s
(replace-match "" nil nil s
)))
2199 (setq n
(string-to-number s
))
2201 ((and (string-match "0" s
)
2202 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2203 ((string-match "\\`[ \t]+\\'" s
) nil
)
2204 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2205 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2206 (m (string-to-number (or (match-string 2 s
) "0")))
2207 (s (string-to-number (or (match-string 4 s
) "0"))))
2208 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2209 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2213 (defun org-table-current-field-formula (&optional key noerror
)
2214 "Return the formula active for the current field.
2216 Assumes that table is already analyzed. If KEY is given, return
2217 the key to this formula. Otherwise return the formula preceded
2218 with \"=\" or \":=\"."
2219 (let* ((line (count-lines org-table-current-begin-pos
2220 (line-beginning-position)))
2221 (row (org-table-line-to-dline line
)))
2224 (let* ((col (org-table-current-column))
2225 (name (car (rassoc (list line col
)
2226 org-table-named-field-locations
)))
2227 (scol (format "$%d" col
))
2228 (ref (format "@%d$%d" (org-table-current-dline) col
))
2229 (stored-list (org-table-get-stored-formulas noerror
))
2230 (ass (or (assoc name stored-list
)
2231 (assoc ref stored-list
)
2232 (assoc scol stored-list
))))
2233 (cond (key (car ass
))
2234 (ass (concat (if (string-match-p "^[0-9]+$" (car ass
)) "=" ":=")
2237 (t (error "No formula active for the current field")))))
2239 (defun org-table-get-formula (&optional equation named
)
2240 "Read a formula from the minibuffer, offer stored formula as default.
2241 When NAMED is non-nil, look for a named equation."
2242 (let* ((stored-list (org-table-get-stored-formulas))
2243 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2244 (line-beginning-position))
2245 (org-table-current-column))
2246 org-table-named-field-locations
)))
2247 (ref (format "@%d$%d"
2248 (org-table-current-dline)
2249 (org-table-current-column)))
2251 ((not named
) (format "$%d" (org-table-current-column)))
2252 ((and name
(not (string-match "\\`LR[0-9]+\\'" name
))) name
)
2254 (name (or name ref
))
2255 (org-table-may-need-update nil
)
2256 (stored (cdr (assoc scol stored-list
)))
2258 ((and stored equation
(string-match-p "^ *=? *$" equation
))
2262 (t (org-table-formula-from-user
2264 (org-table-formula-to-user
2265 (format "%s formula %s="
2266 (if named
"Field" "Column")
2268 (if stored
(org-table-formula-to-user stored
) "")
2269 'org-table-formula-history
2272 (when (not (string-match "\\S-" eq
))
2274 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2275 (org-table-store-formulas stored-list
)
2276 (user-error "Formula removed"))
2277 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2278 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2279 (if (and name
(not named
))
2280 ;; We set the column equation, delete the named one.
2281 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2284 (setcdr (assoc scol stored-list
) eq
)
2285 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2286 (if (or mustsave
(not (equal stored eq
)))
2287 (org-table-store-formulas stored-list
))
2290 (defun org-table-store-formulas (alist &optional location
)
2291 "Store the list of formulas below the current table.
2292 If optional argument LOCATION is a buffer position, insert it at
2296 (progn (goto-char location
) (beginning-of-line))
2297 (goto-char (org-table-end)))
2298 (let ((case-fold-search t
))
2299 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2301 ;; Don't overwrite TBLFM, we might use text properties to
2303 (goto-char (match-beginning 3))
2304 (delete-region (match-beginning 3) (match-end 0)))
2306 (insert (or (match-string 2) "#+TBLFM:")))
2308 (mapconcat (lambda (x) (concat (car x
) "=" (cdr x
)))
2309 (sort alist
#'org-table-formula-less-p
)
2313 (defsubst org-table-formula-make-cmp-string
(a)
2314 (when (string-match "\\`$[<>]" a
)
2315 (let ((arrow (string-to-char (substring a
1))))
2316 ;; Fake a high number to make sure this is sorted at the end.
2317 (setq a
(org-table-formula-handle-first/last-rc a
))
2318 (setq a
(format "$%d" (+ 10000
2319 (if (= arrow ?
<) -
1000 0)
2320 (string-to-number (substring a
1)))))))
2322 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2326 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2328 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2330 (concat "@@" (match-string 5 a
))))))
2332 (defun org-table-formula-less-p (a b
)
2333 "Compare two formulas for sorting."
2334 (let ((as (org-table-formula-make-cmp-string (car a
)))
2335 (bs (org-table-formula-make-cmp-string (car b
))))
2336 (and as bs
(string< as bs
))))
2339 (defun org-table-get-stored-formulas (&optional noerror location
)
2340 "Return an alist with the stored formulas directly after current table.
2341 By default, only return active formulas, i.e., formulas located
2342 on the first line after the table. However, if optional argument
2343 LOCATION is a buffer position, consider the formulas there."
2346 (progn (goto-char location
) (beginning-of-line))
2347 (goto-char (org-table-end)))
2348 (let ((case-fold-search t
))
2349 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2350 (let ((strings (org-split-string (match-string-no-properties 2)
2353 (dolist (string strings
(nreverse eq-alist
))
2354 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2355 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2358 (let ((m (match-string 1 string
)))
2360 ((not (match-end 2)) m
)
2361 ;; Is it a column reference?
2362 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m
) m
)
2363 ;; Since named columns are not possible in
2364 ;; LHS, assume this is a named field.
2365 (t (match-string 2 string
)))))
2366 (rhs (match-string 3 string
)))
2367 (push (cons lhs rhs
) eq-alist
)
2369 ((not (member lhs seen
)) (push lhs seen
))
2372 "Double definition `%s=' in TBLFM line, please fix by hand"
2378 "Double definition `%s=' in TBLFM line, please fix by hand"
2381 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2382 "Modify the equations after the table structure has been edited.
2383 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2384 For all numbers larger than LIMIT, shift them by DELTA."
2386 (goto-char (org-table-end))
2387 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2388 (let ((msg "The formulas in #+TBLFM have been updated")
2389 (re (concat key
"\\([0-9]+\\)"))
2392 (if (or (equal key
"$") (equal key
"$LR"))
2393 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2394 (regexp-quote key
) remove
)
2395 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2398 (while (re-search-forward re2
(point-at-eol) t
)
2399 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2400 (if (equal (char-before (match-beginning 0)) ?.
)
2402 "Change makes TBLFM term %s invalid, use undo to recover"
2404 (replace-match "")))))
2405 (while (re-search-forward re
(point-at-eol) t
)
2406 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2407 (setq s
(match-string 1) n
(string-to-number s
))
2409 ((setq a
(assoc s replace
))
2410 (replace-match (concat key
(cdr a
)) t t
)
2412 ((and limit
(> n limit
))
2413 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2418 (defun org-table-maybe-eval-formula ()
2419 "Check if the current field starts with \"=\" or \":=\".
2420 If yes, store the formula and apply it."
2421 ;; We already know we are in a table. Get field will only return a formula
2422 ;; when appropriate. It might return a separator line, but no problem.
2423 (when org-table-formula-evaluate-inline
2424 (let* ((field (org-trim (or (org-table-get-field) "")))
2426 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2427 (setq named
(equal (string-to-char field
) ?
:)
2428 eq
(match-string 1 field
))
2429 (org-table-eval-formula (and named
'(4))
2430 (org-table-formula-from-user eq
))))))
2432 (defvar org-recalc-commands nil
2433 "List of commands triggering the recalculation of a line.
2434 Will be filled automatically during use.")
2436 (defvar org-recalc-marks
2437 '((" " .
"Unmarked: no special line, no automatic recalculation")
2438 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2439 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2440 ("!" .
"Column name definition line. Reference in formula as $name.")
2441 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2442 ("_" .
"Names for values in row below this one.")
2443 ("^" .
"Names for values in row above this one.")))
2446 (defun org-table-rotate-recalc-marks (&optional newchar
)
2447 "Rotate the recalculation mark in the first column.
2448 If in any row, the first field is not consistent with a mark,
2449 insert a new column for the markers.
2450 When there is an active region, change all the lines in the region,
2451 after prompting for the marking character.
2452 After each change, a message will be displayed indicating the meaning
2455 (unless (org-at-table-p) (user-error "Not at a table"))
2456 (let* ((region (org-region-active-p))
2458 (save-excursion (goto-char (region-beginning))
2459 (copy-marker (line-beginning-position)))))
2461 (save-excursion (goto-char (region-end))
2462 (copy-marker (line-beginning-position)))))
2463 (l (copy-marker (line-beginning-position)))
2464 (col (org-table-current-column))
2467 (read-char-exclusive
2468 "Change region to what mark? Type # * ! $ or SPC: "))
2472 (goto-char (org-table-begin))
2474 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2475 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2476 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2478 (when l1
(goto-char l1
))
2481 (unless (looking-at org-table-dataline-regexp
)
2482 (user-error "Not at a table data line")))
2483 (when no-special-column
2484 (org-table-goto-column 1)
2485 (org-table-insert-column))
2486 (let ((previous-line-end (line-end-position))
2490 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2492 (t (cadr (member (match-string 1)
2493 (append (mapcar #'car org-recalc-marks
)
2495 ;; Rotate mark in first row.
2496 (org-table-get-field 1 (format " %s " newchar
))
2497 ;; Rotate marks in additional rows if a region is active.
2501 (while (<= (point) l2
)
2502 (when (looking-at org-table-dataline-regexp
)
2503 (org-table-get-field 1 (format " %s " newchar
)))
2505 ;; Only align if rotation actually changed lines' length.
2506 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2508 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2509 (when l1
(set-marker l1 nil
))
2510 (when l2
(set-marker l2 nil
))
2512 (when (called-interactively-p 'interactive
)
2513 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2516 (defun org-table-analyze ()
2517 "Analyze table at point and store results.
2519 This function sets up the following dynamically scoped variables:
2521 `org-table-column-name-regexp',
2522 `org-table-column-names',
2523 `org-table-current-begin-pos',
2524 `org-table-current-line-types',
2525 `org-table-current-ncol',
2528 `org-table-local-parameters',
2529 `org-table-named-field-locations'."
2530 (let ((beg (org-table-begin))
2531 (end (org-table-end)))
2534 ;; Extract column names.
2535 (setq org-table-column-names nil
)
2536 (when (save-excursion
2537 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
2539 (dolist (name (org-split-string (match-string 1) " *| *"))
2541 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
2542 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
2543 (setq org-table-column-names
(nreverse org-table-column-names
))
2544 (setq org-table-column-name-regexp
2545 (format "\\$\\(%s\\)\\>"
2546 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
2547 ;; Extract local parameters.
2548 (setq org-table-local-parameters nil
)
2550 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2551 (dolist (field (org-split-string (match-string 1) " *| *"))
2553 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2554 (push (cons (match-string 1 field
) (match-string 2 field
))
2555 org-table-local-parameters
)))))
2556 ;; Update named fields locations. We minimize `count-lines'
2557 ;; processing by storing last known number of lines in LAST.
2558 (setq org-table-named-field-locations nil
)
2560 (let ((last (cons (point) 0)))
2561 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2562 (let ((c (match-string 1))
2563 (fields (org-split-string (match-string 2) " *| *")))
2565 (forward-line (if (equal c
"_") 1 -
1))
2567 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2568 (org-split-string (match-string 1) " *| *")))
2569 (line (cl-incf (cdr last
) (count-lines (car last
) (point))))
2571 (setcar last
(point)) ; Update last known position.
2572 (while (and fields fields1
)
2573 (let ((field (pop fields
))
2576 (when (and (stringp field
)
2578 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2580 (push (cons field v
) org-table-local-parameters
)
2581 (push (list field line col
)
2582 org-table-named-field-locations
))))))))))
2583 ;; Re-use existing markers when possible.
2584 (if (markerp org-table-current-begin-pos
)
2585 (move-marker org-table-current-begin-pos
(point))
2586 (setq org-table-current-begin-pos
(point-marker)))
2587 ;; Analyze the line types.
2588 (let ((l 0) hlines dlines types
)
2589 (while (looking-at "[ \t]*|\\(-\\)?")
2590 (push (if (match-end 1) 'hline
'dline
) types
)
2591 (if (match-end 1) (push l hlines
) (push l dlines
))
2594 (push 'hline types
) ; Add an imaginary extra hline to the end.
2595 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
2596 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
2597 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
)))))
2598 ;; Get the number of columns from the first data line in table.
2600 (forward-line (aref org-table-dlines
1))
2603 (buffer-substring (line-beginning-position) (line-end-position))
2605 (nfields (length fields
))
2607 (setq org-table-current-ncol nfields
)
2609 (aref org-table-dlines
(1- (length org-table-dlines
)))))
2610 (dotimes (i nfields
)
2611 (let ((column (1+ i
)))
2612 (push (list (format "LR%d" column
) last-dline column
) al
)
2613 (push (cons (format "LR%d" column
) (nth i fields
)) al2
))))
2614 (setq org-table-named-field-locations
2615 (append org-table-named-field-locations al
))
2616 (setq org-table-local-parameters
2617 (append org-table-local-parameters al2
))))))
2619 (defun org-table-goto-field (ref &optional create-column-p
)
2620 "Move point to a specific field in the current table.
2622 REF is either the name of a field its absolute reference, as
2623 a string. No column is created unless CREATE-COLUMN-P is
2624 non-nil. If it is a function, it is called with the column
2625 number as its argument as is used as a predicate to know if the
2626 column can be created.
2628 This function assumes the table is already analyzed (i.e., using
2629 `org-table-analyze')."
2632 ((cdr (assoc ref org-table-named-field-locations
)))
2633 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
2634 (list (condition-case nil
2635 (aref org-table-dlines
2636 (string-to-number (match-string 1 ref
)))
2637 (error (user-error "Invalid row number in %s" ref
)))
2638 (string-to-number (match-string 2 ref
))))
2639 (t (user-error "Unknown field: %s" ref
))))
2640 (line (car coordinates
))
2641 (column (nth 1 coordinates
))
2642 (create-new-column (if (functionp create-column-p
)
2643 (funcall create-column-p column
)
2646 (goto-char org-table-current-begin-pos
)
2648 (org-table-goto-column column nil create-new-column
))))
2651 (defun org-table-maybe-recalculate-line ()
2652 "Recompute the current line if marked for it, and if we haven't just done it."
2654 (and org-table-allow-automatic-line-recalculation
2655 (not (and (memq last-command org-recalc-commands
)
2656 (eq org-last-recalc-line
(line-beginning-position))))
2657 (save-excursion (beginning-of-line 1)
2658 (looking-at org-table-auto-recalculate-regexp
))
2659 (org-table-recalculate) t
))
2661 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2662 (defsubst org-set-calc-mode
(var &optional value
)
2664 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2665 ("R" calc-angle-mode rad
)
2666 ("F" calc-prefer-frac t
)
2667 ("S" calc-symbolic-mode t
)))
2668 value
(nth 2 var
) var
(nth 1 var
)))
2669 (if (memq var org-tbl-calc-modes
)
2670 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2671 (cons var
(cons value org-tbl-calc-modes
)))
2675 (defun org-table-eval-formula (&optional arg equation
2676 suppress-align suppress-const
2677 suppress-store suppress-analysis
)
2678 "Replace the table field value at the cursor by the result of a calculation.
2680 In a table, this command replaces the value in the current field with the
2681 result of a formula. It also installs the formula as the \"current\" column
2682 formula, by storing it in a special line below the table. When called
2683 with a `\\[universal-argument]' prefix the formula is installed as a \
2686 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2687 insert the active equation for the field
2688 back into the current field, so that it can be edited there. This is \
2690 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2691 check the referenced fields.
2693 When called, the command first prompts for a formula, which is read in
2694 the minibuffer. Previously entered formulas are available through the
2695 history list, and the last used formula is offered as a default.
2696 These stored formulas are adapted correctly when moving, inserting, or
2697 deleting columns with the corresponding commands.
2699 The formula can be any algebraic expression understood by the Calc package.
2700 For details, see the Org mode manual.
2702 This function can also be called from Lisp programs and offers
2703 additional arguments: EQUATION can be the formula to apply. If this
2704 argument is given, the user will not be prompted.
2706 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2709 SUPPRESS-CONST suppresses the interpretation of constants in the
2710 formula, assuming that this has been done already outside the
2713 SUPPRESS-STORE means the formula should not be stored, either
2714 because it is already stored, or because it is a modified
2715 equation that should not overwrite the stored one.
2717 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2720 (unless suppress-analysis
2721 (org-table-check-inside-data-field)
2722 (org-table-analyze))
2723 (if (equal arg
'(16))
2724 (let ((eq (org-table-current-field-formula)))
2725 (org-table-get-field nil eq
)
2727 (setq org-table-may-need-update t
))
2729 (ndown (if (integerp arg
) arg
1))
2730 (org-table-automatic-realign nil
)
2731 (case-fold-search nil
)
2733 (formula (if (and equation suppress-store
)
2735 (org-table-get-formula equation
(equal arg
'(4)))))
2736 (n0 (org-table-current-column))
2737 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2738 (numbers nil
) ; was a variable, now fixed default
2740 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2741 duration duration-output-format
)
2742 ;; Parse the format string. Since we have a lot of modes, this is
2743 ;; a lot of work. However, I think calc still uses most of the time.
2744 (if (string-match ";" formula
)
2745 (let ((tmp (org-split-string formula
";")))
2746 (setq formula
(car tmp
)
2747 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2749 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2750 (setq c
(string-to-char (match-string 1 fmt
))
2751 n
(string-to-number (match-string 2 fmt
)))
2753 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2754 (setq org-tbl-calc-modes
2757 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2758 (?s . sci
) (?e . eng
))))
2760 (setq fmt
(replace-match "" t t fmt
)))
2761 (if (string-match "[tTU]" fmt
)
2762 (let ((ff (match-string 0 fmt
)))
2763 (setq duration t numbers t
2764 duration-output-format
2765 (cond ((equal ff
"T") nil
)
2766 ((equal ff
"t") org-table-duration-custom-format
)
2767 ((equal ff
"U") 'hh
:mm
))
2768 fmt
(replace-match "" t t fmt
))))
2769 (if (string-match "N" fmt
)
2771 fmt
(replace-match "" t t fmt
)))
2772 (if (string-match "L" fmt
)
2774 fmt
(replace-match "" t t fmt
)))
2775 (if (string-match "E" fmt
)
2777 fmt
(replace-match "" t t fmt
)))
2778 (while (string-match "[DRFS]" fmt
)
2779 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2780 (setq fmt
(replace-match "" t t fmt
)))
2781 (unless (string-match "\\S-" fmt
)
2783 (when (and (not suppress-const
) org-table-formula-use-constants
)
2784 (setq formula
(org-table-formula-substitute-names formula
)))
2785 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2786 (setq formula
(org-table-formula-handle-first/last-rc formula
))
2788 (setq fields
(org-split-string
2790 (buffer-substring-no-properties
2791 (line-beginning-position) (line-end-position)))
2793 ;; replace fields with duration values if relevant
2796 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2799 (setq fields
(mapcar
2801 (if (string-match "\\S-" x
)
2802 (number-to-string (string-to-number x
))
2805 (setq ndown
(1- ndown
))
2806 (setq form
(copy-sequence formula
)
2807 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2808 (if (and lispp literal
) (setq lispp
'literal
))
2810 ;; Insert row and column number of formula result field
2811 (while (string-match "[@$]#" form
)
2816 (if (equal (substring form
(match-beginning 0)
2817 (1+ (match-beginning 0)))
2819 (org-table-current-dline)
2820 (org-table-current-column))))
2823 ;; Check for old vertical references
2824 (org-table--error-on-old-row-references form
)
2825 ;; Insert remote references
2826 (setq form
(org-table-remote-reference-indirection form
))
2827 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2831 (org-table-make-reference
2832 (let ((rmtrng (org-table-get-remote-range
2833 (match-string 1 form
) (match-string 2 form
))))
2836 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2837 (org-table-time-string-to-seconds rmtrng
))
2839 keep-empty numbers lispp
))
2841 ;; Insert complex ranges
2842 (while (and (string-match org-table-range-regexp form
)
2843 (> (length (match-string 0 form
)) 1))
2846 (org-table-get-range
2847 (match-string 0 form
) org-table-current-begin-pos n0
)))
2850 (org-table-make-reference
2851 ;; possibly handle durations
2854 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2855 (org-table-time-string-to-seconds formrg
))
2857 keep-empty numbers lispp
)))
2858 (if (not (save-match-data
2859 (string-match (regexp-quote form
) formrpl
)))
2860 (setq form
(replace-match formrpl t t form
))
2861 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2862 ;; Insert simple ranges, i.e. included in the current row.
2863 (while (string-match
2864 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2869 (org-table-make-reference
2871 (+ (if (match-end 2) n0
0)
2872 (string-to-number (match-string 1 form
))
2874 (+ (if (match-end 4) n0
0)
2875 (string-to-number (match-string 3 form
))))
2876 keep-empty numbers lispp
))
2879 ;; Insert the references to fields in same row
2880 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2881 (setq n
(+ (string-to-number (match-string 1 form
))
2882 (if (match-end 2) n0
0))
2883 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2884 formrpl
(save-match-data
2885 (org-table-make-reference
2886 x keep-empty numbers lispp
)))
2889 (string-match (regexp-quote formula
) formrpl
)))
2890 (user-error "Invalid field specifier \"%s\""
2891 (match-string 0 form
)))
2892 (setq form
(replace-match formrpl t t form
)))
2895 (setq ev
(condition-case nil
2896 (eval (eval (read form
)))
2898 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2899 ev
(if duration
(org-table-time-seconds-to-string
2900 (string-to-number ev
)
2901 duration-output-format
) ev
))
2903 ;; Use <...> time-stamps so that Calc can handle them.
2905 (replace-regexp-in-string org-ts-regexp-inactive
"<\\1>" form
))
2906 ;; Internationalize local time-stamps by setting locale to
2909 (replace-regexp-in-string
2912 (let ((system-time-locale "C"))
2914 (org-time-stamp-format
2915 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2916 (apply #'encode-time
2917 (save-match-data (org-parse-time-string ts
))))))
2920 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2922 (calc-eval (cons form org-tbl-calc-modes
)
2923 (when (and (not keep-empty
) numbers
) 'num
)))
2924 ev
(if duration
(org-table-time-seconds-to-string
2925 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2926 (string-to-number (org-table-time-string-to-seconds ev
))
2927 (string-to-number ev
))
2928 duration-output-format
)
2931 (when org-table-formula-debug
2932 (with-output-to-temp-buffer "*Substitution History*"
2933 (princ (format "Substitution history of formula
2937 $1-> %s\n" orig formula form0 form
))
2939 (princ (format " %s^\nError: %s"
2940 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2941 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2943 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2944 (setq bw
(get-buffer-window "*Substitution History*"))
2945 (org-fit-window-to-buffer bw
)
2946 (unless (and (called-interactively-p 'any
) (not ndown
))
2947 (unless (let (inhibit-redisplay)
2948 (y-or-n-p "Debugging Formula. Continue to next? "))
2950 (user-error "Abort"))
2953 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2954 (org-table-justify-field-maybe
2955 (format org-table-formula-field-format
2957 ((not (stringp ev
)) ev
)
2958 (fmt (format fmt
(string-to-number ev
)))
2959 ;; Replace any active time stamp in the result with
2960 ;; an inactive one. Dates in tables are likely
2961 ;; piece of regular data, not meant to appear in the
2963 (t (replace-regexp-in-string org-ts-regexp
"[\\1]" ev
)))))
2964 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2965 (call-interactively 'org-return
)
2967 (and down
(org-table-maybe-recalculate-line))
2968 (or suppress-align
(and org-table-may-need-update
2969 (org-table-align))))))
2971 (defun org-table-put-field-property (prop value
)
2973 (put-text-property (progn (skip-chars-backward "^|") (point))
2974 (progn (skip-chars-forward "^|") (point))
2977 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2978 "Get a calc vector from a column, according to descriptor DESC.
2980 Optional arguments TBEG and COL can give the beginning of the table and
2981 the current column, to avoid unnecessary parsing.
2983 HIGHLIGHT means just highlight the range.
2985 When CORNERS-ONLY is set, only return the corners of the range as
2986 a list (line1 column1 line2 column2) where line1 and line2 are
2987 line numbers relative to beginning of table, or TBEG, and column1
2988 and column2 are table column numbers."
2989 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc
)
2990 (replace-regexp-in-string "\\$" "@0$" desc
)
2992 (col (or col
(org-table-current-column)))
2993 (tbeg (or tbeg
(org-table-begin)))
2994 (thisline (count-lines tbeg
(line-beginning-position))))
2995 (unless (string-match org-table-range-regexp desc
)
2996 (user-error "Invalid table range specifier `%s'" desc
))
2997 (let ((rangep (match-end 3))
2998 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2999 (or (save-match-data
3000 (and (org-string-nw-p r
)
3001 (org-table--descriptor-line r thisline
)))
3003 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
3004 (or (save-match-data
3005 (and (org-string-nw-p r
)
3006 (org-table--descriptor-line r thisline
)))
3008 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
3009 (if (or (not c
) (= (string-to-number c
) 0)) col
3010 (+ (string-to-number c
)
3011 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
3012 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
3013 (if (or (not c
) (= (string-to-number c
) 0)) col
3014 (+ (string-to-number c
)
3015 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
3017 (if (and (not corners-only
)
3018 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
3021 (forward-line (- r1 thisline
))
3022 (while (not (looking-at org-table-dataline-regexp
))
3024 (prog1 (org-trim (org-table-get-field c1
))
3025 (when highlight
(org-table-highlight-rectangle))))
3026 ;; A range, return a vector. First sort the numbers to get
3027 ;; a regular rectangle.
3028 (let ((first-row (min r1 r2
))
3029 (last-row (max r1 r2
))
3030 (first-column (min c1 c2
))
3031 (last-column (max c1 c2
)))
3032 (if corners-only
(list first-row first-column last-row last-column
)
3033 ;; Copy the range values into a list.
3034 (forward-line (- first-row thisline
))
3035 (while (not (looking-at org-table-dataline-regexp
))
3037 (cl-incf first-row
))
3038 (org-table-goto-column first-column
)
3039 (let ((beg (point)))
3040 (forward-line (- last-row first-row
))
3041 (while (not (looking-at org-table-dataline-regexp
))
3043 (org-table-goto-column last-column
)
3044 (let ((end (point)))
3046 (org-table-highlight-rectangle
3047 beg
(progn (skip-chars-forward "^|\n") (point))))
3048 ;; Return string representation of calc vector.
3051 (org-table-copy-region beg end
))))))))))))
3053 (defun org-table--descriptor-line (desc cline
)
3054 "Return relative line number corresponding to descriptor DESC.
3055 The cursor is currently in relative line number CLINE."
3056 (if (string-match "\\`[0-9]+\\'" desc
)
3057 (aref org-table-dlines
(string-to-number desc
))
3058 (when (or (not (string-match
3059 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3062 (and (not (match-end 3)) (not (match-end 6)))
3063 (and (match-end 3) (match-end 6) (not (match-end 5))))
3064 (user-error "Invalid row descriptor `%s'" desc
))
3065 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3066 (hdir (match-string 2 desc
))
3067 (odir (match-string 5 desc
))
3068 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
3069 (rel (and (match-end 6)
3070 (or (and (match-end 1) (not (match-end 3)))
3072 (when (and hn
(not hdir
))
3075 (when (eq (aref org-table-current-line-types
0) 'hline
) (cl-decf hn
)))
3076 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
3079 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
3082 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
3085 (defun org-table--row-type (type n i backwards relative desc
)
3086 "Return relative line of Nth row with type TYPE.
3087 Search starts from relative line I. When BACKWARDS in non-nil,
3088 look before I. When RELATIVE is non-nil, the reference is
3089 relative. DESC is the original descriptor that started the
3090 search, as a string."
3091 (let ((l (length org-table-current-line-types
)))
3094 (while (and (cl-incf i
(if backwards -
1 1))
3097 (not (eq (aref org-table-current-line-types i
) type
))
3098 ;; We are going to cross a hline. Check if this is
3099 ;; an authorized move.
3102 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
3103 ((eq org-table-relative-ref-may-cross-hline t
))
3104 ((eq org-table-relative-ref-may-cross-hline
'error
)
3105 (user-error "Row descriptor %s crosses hline" desc
))
3106 (t (cl-decf i
(if backwards -
1 1)) ; Step back.
3107 (throw :exit nil
)))))))
3108 (cond ((or (< i
0) (>= i l
))
3109 (user-error "Row descriptor %s leads outside table" desc
))
3110 ;; The last hline doesn't exist. Instead, point to last row
3112 ((= i
(1- l
)) (1- i
))
3115 (defun org-table--error-on-old-row-references (s)
3116 (when (string-match "&[-+0-9I]" s
)
3117 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3119 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3120 "Convert list ELEMENTS to something appropriate to insert into formula.
3121 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3122 NUMBERS indicates that everything should be converted to numbers.
3123 LISPP non-nil means to return something appropriate for a Lisp
3124 list, `literal' is for the format specifier L."
3125 ;; Calc nan (not a number) is used for the conversion of the empty
3126 ;; field to a reference for several reasons: (i) It is accepted in a
3127 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3128 ;; (ii) In a single field (not in range) it can be distinguished
3129 ;; from "(nan)" which is the reference made from a single field
3130 ;; containing "nan".
3131 (if (stringp elements
)
3134 (if (eq lispp
'literal
)
3136 (if (and (eq elements
"") (not keep-empty
))
3139 (if numbers
(string-to-number elements
) elements
))))
3140 (if (string-match "\\S-" elements
)
3142 (when numbers
(setq elements
(number-to-string
3143 (string-to-number elements
))))
3144 (concat "(" elements
")"))
3145 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3150 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3152 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3156 (if (eq lispp
'literal
)
3158 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3160 (concat "[" (mapconcat
3162 (if (string-match "\\S-" x
)
3164 (number-to-string (string-to-number x
))
3166 (if (or (not keep-empty
) numbers
) "0" "nan")))
3170 (defun org-table-message-once-per-second (t1 &rest args
)
3171 "If there has been more than one second since T1, display message.
3172 ARGS are passed as arguments to the `message' function. Returns
3173 current time if a message is printed, otherwise returns T1. If
3174 T1 is nil, always messages."
3175 (let ((curtime (current-time)))
3176 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3177 (progn (apply 'message args
)
3182 (defun org-table-recalculate (&optional all noalign
)
3183 "Recalculate the current table line by applying all stored formulas.
3185 With prefix arg ALL, do this for all lines in the table.
3187 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3188 if ALL is the symbol `iterate',
3189 recompute the table until it no longer changes.
3191 If NOALIGN is not nil, do not re-align the table after the computations
3192 are done. This is typically used internally to save time, if it is
3193 known that the table will be realigned a little later anyway."
3195 (unless (memq this-command org-recalc-commands
)
3196 (push this-command org-recalc-commands
))
3197 (unless (org-at-table-p) (user-error "Not at a table"))
3198 (if (or (eq all
'iterate
) (equal all
'(16)))
3201 (let* ((eqlist (sort (org-table-get-stored-formulas)
3202 (lambda (a b
) (string< (car a
) (car b
)))))
3203 (inhibit-redisplay (not debug-on-error
))
3204 (line-re org-table-dataline-regexp
)
3205 (log-first-time (current-time))
3206 (log-last-time log-first-time
)
3208 beg end eqlcol eqlfield
)
3209 ;; Insert constants in all formulas.
3211 (org-table-save-field
3212 ;; Expand equations, then split the equation list between
3213 ;; column formulas and field formulas.
3215 (let* ((rhs (org-table-formula-substitute-names
3216 (org-table-formula-handle-first/last-rc
(cdr eq
))))
3219 (org-table-formula-handle-first/last-rc
3221 ((string-match "\\`@-?I+" old-lhs
)
3222 (user-error "Can't assign to hline relative reference"))
3223 ((string-match "\\`$[<>]" old-lhs
)
3224 (let ((new (org-table-formula-handle-first/last-rc
3226 (when (assoc new eqlist
)
3227 (user-error "\"%s=\" formula tries to overwrite \
3228 existing formula for column %s"
3233 (if (string-match-p "\\`\\$[0-9]+\\'" lhs
)
3234 (push (cons lhs rhs
) eqlcol
)
3235 (push (cons lhs rhs
) eqlfield
))))
3236 (setq eqlcol
(nreverse eqlcol
))
3237 ;; Expand ranges in lhs of formulas
3238 (setq eqlfield
(org-table-expand-lhs-ranges (nreverse eqlfield
)))
3239 ;; Get the correct line range to process.
3242 (setq end
(copy-marker (org-table-end)))
3243 (goto-char (setq beg org-table-current-begin-pos
))
3245 ((re-search-forward org-table-calculate-mark-regexp end t
)
3246 ;; This is a table with marked lines, compute selected
3248 (setq line-re org-table-recalculate-regexp
))
3249 ;; Move forward to the first non-header line.
3250 ((and (re-search-forward org-table-dataline-regexp end t
)
3251 (re-search-forward org-table-hline-regexp end t
)
3252 (re-search-forward org-table-dataline-regexp end t
))
3253 (setq beg
(match-beginning 0)))
3254 ;; Just leave BEG at the start of the table.
3256 (setq beg
(line-beginning-position)
3257 end
(copy-marker (line-beginning-position 2))))
3259 ;; Mark named fields untouchable. Also check if several
3260 ;; field/range formulas try to set the same field.
3261 (remove-text-properties beg end
'(org-untouchable t
))
3262 (let ((current-line (count-lines org-table-current-begin-pos
3263 (line-beginning-position)))
3265 (dolist (eq eqlfield
)
3266 (let* ((name (car eq
))
3267 (location (assoc name org-table-named-field-locations
))
3268 (eq-line (or (nth 1 location
)
3269 (and (string-match "\\`@\\([0-9]+\\)" name
)
3270 (aref org-table-dlines
3272 (match-string 1 name
))))))
3275 ;; Turn field coordinates associated to NAME
3276 ;; into an absolute reference.
3278 (org-table-line-to-dline eq-line
)
3281 (when (member reference seen-fields
)
3282 (user-error "Several field/range formulas try to set %s"
3284 (push reference seen-fields
)
3285 (when (or all
(eq eq-line current-line
))
3286 (org-table-goto-field name
)
3287 (org-table-put-field-property :org-untouchable t
)))))
3288 ;; Evaluate the column formulas, but skip fields covered by
3291 (while (re-search-forward line-re end t
)
3292 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3293 ;; Unprotected line, recalculate.
3297 (org-table-message-once-per-second
3299 "Re-applying formulas to full table...(line %d)" cnt
)))
3300 (if (markerp org-last-recalc-line
)
3301 (move-marker org-last-recalc-line
(line-beginning-position))
3302 (setq org-last-recalc-line
3303 (copy-marker (line-beginning-position))))
3304 (dolist (entry eqlcol
)
3305 (goto-char org-last-recalc-line
)
3306 (org-table-goto-column
3307 (string-to-number (substring (car entry
) 1)) nil
'force
)
3308 (unless (get-text-property (point) :org-untouchable
)
3309 (org-table-eval-formula
3310 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
3311 ;; Evaluate the field formulas.
3312 (dolist (eq eqlfield
)
3313 (let ((reference (car eq
))
3316 (org-table-message-once-per-second
3317 (and all log-last-time
)
3318 "Re-applying formula to field: %s" (car eq
)))
3319 (org-table-goto-field
3321 ;; Possibly create a new column, as long as
3322 ;; `org-table-formula-create-columns' allows it.
3323 (let ((column-count (progn (end-of-line)
3324 (1- (org-table-current-column)))))
3326 (when (> column
1000)
3327 (user-error "Formula column target too large"))
3328 (and (> column column-count
)
3329 (or (eq org-table-formula-create-columns t
)
3330 (and (eq org-table-formula-create-columns
'warn
)
3332 (org-display-warning
3333 "Out-of-bounds formula added columns")
3335 (and (eq org-table-formula-create-columns
'prompt
)
3337 "Out-of-bounds formula. Add columns? ")))))))
3338 (org-table-eval-formula nil formula t t t t
))))
3339 ;; Clean up markers and internal text property.
3340 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3341 (set-marker end nil
)
3343 (when org-table-may-need-update
(org-table-align))
3345 (org-table-message-once-per-second
3346 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
3347 (org-table-message-once-per-second
3348 (and all log-first-time
) "Re-applying formulas... done")))))
3351 (defun org-table-iterate (&optional arg
)
3352 "Recalculate the table until it does not change anymore.
3353 The maximum number of iterations is 10, but you can choose a different value
3354 with the prefix ARG."
3356 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3358 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3363 (org-table-recalculate 'all
)
3364 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3365 (if (not (string= lasttbl thistbl
))
3366 (setq lasttbl thistbl
)
3368 (message "Convergence after %d iterations" i
)
3369 (message "Table was already stable"))
3371 (user-error "No convergence after %d iterations" i
))))
3374 (defun org-table-recalculate-buffer-tables ()
3375 "Recalculate all tables in the current buffer."
3377 (org-with-wide-buffer
3378 (org-table-map-tables
3380 ;; Reason for separate `org-table-align': When repeating
3381 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3383 (org-table-recalculate t t
)
3388 (defun org-table-iterate-buffer-tables ()
3389 "Iterate all tables in the buffer, to converge inter-table dependencies."
3393 (checksum (md5 (buffer-string)))
3395 (org-with-wide-buffer
3399 (org-table-map-tables (lambda () (org-table-recalculate t t
)) t
)
3400 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3402 (org-table-map-tables #'org-table-align t
)
3403 (message "Convergence after %d iterations" (- imax i
))
3405 (setq checksum c1
)))
3406 (org-table-map-tables #'org-table-align t
)
3407 (user-error "No convergence after %d iterations" imax
)))))
3409 (defun org-table-calc-current-TBLFM (&optional arg
)
3410 "Apply the #+TBLFM in the line at point to the table."
3412 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3413 (let ((formula (buffer-substring
3414 (line-beginning-position)
3415 (line-end-position))))
3417 ;; Insert a temporary formula at right after the table
3418 (goto-char (org-table-TBLFM-begin))
3419 (let ((s (point-marker)))
3420 (insert formula
"\n")
3421 (let ((e (point-marker)))
3422 ;; Recalculate the table.
3423 (beginning-of-line 0) ; move to the inserted line
3424 (skip-chars-backward " \r\n\t")
3426 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3427 ;; Delete the formula inserted temporarily.
3430 (set-marker e nil
)))))))
3432 (defun org-table-TBLFM-begin ()
3433 "Find the beginning of the TBLFM lines and return its position.
3434 Return nil when the beginning of TBLFM line was not found."
3436 (when (progn (forward-line 1)
3437 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3438 (line-beginning-position 2))))
3440 (defun org-table-expand-lhs-ranges (equations)
3441 "Expand list of formulas.
3442 If some of the RHS in the formulas are ranges or a row reference,
3443 expand them to individual field equations for each field. This
3444 function assumes the table is already analyzed (i.e., using
3445 `org-table-analyze')."
3447 (dolist (e equations
(nreverse res
))
3451 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3452 ;; This just refers to one fixed field.
3454 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3455 ;; This just refers to one fixed named field.
3457 ((string-match-p "\\`\\$[0-9]+\\'" lhs
)
3458 ;; Column formulas are treated specially and are not
3461 ((string-match "\\`@[0-9]+\\'" lhs
)
3462 (dotimes (ic org-table-current-ncol
)
3463 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3467 (let* ((range (org-table-get-range
3468 lhs org-table-current-begin-pos
1 nil
'corners
))
3469 (r1 (org-table-line-to-dline (nth 0 range
)))
3471 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3473 (cl-loop for ir from r1 to r2 do
3474 (cl-loop for ic from c1 to c2 do
3475 (push (cons (propertize
3476 (format "@%d$%d" ir ic
) :orig-eqn e
)
3480 (defun org-table-formula-handle-first/last-rc
(s)
3481 "Replace @<, @>, $<, $> with first/last row/column of the table.
3482 So @< and $< will always be replaced with @1 and $1, respectively.
3483 The advantage of these special markers are that structure editing of
3484 the table will not change them, while @1 and $1 will be modified
3485 when a line/row is swapped out of that privileged position. So for
3486 formulas that use a range of rows or columns, it may often be better
3487 to anchor the formula with \"I\" row markers, or to offset from the
3488 borders of the table using the @< @> $< $> makers."
3489 (let (n nmax len char
(start 0))
3490 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3493 (setq start
(match-end 3))
3494 (setq nmax
(if (equal (match-string 1 s
) "@")
3495 (1- (length org-table-dlines
))
3496 org-table-current-ncol
)
3497 len
(- (match-end 2) (match-beginning 2))
3498 char
(string-to-char (match-string 2 s
))
3502 (if (or (< n
1) (> n nmax
))
3503 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3504 (match-string 0 s
) s
))
3505 (setq start
(match-beginning 0))
3506 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3509 (defun org-table-formula-substitute-names (f)
3510 "Replace $const with values in string F."
3512 (pp (/= (string-to-char f
) ?
'))
3513 (duration (string-match-p ";.*[Tt].*\\'" f
))
3514 (new (replace-regexp-in-string ; Check for column names.
3515 org-table-column-name-regexp
3517 (concat "$" (cdr (assoc (match-string 1 m
)
3518 org-table-column-names
))))
3520 ;; Parameters and constants.
3523 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3525 (if (match-end 2) (setq start
(match-end 2))
3527 ;; When a duration is expected, convert value on the fly.
3530 (let ((v (org-table-get-constant (match-string 1 new
))))
3531 (if (and (org-string-nw-p v
) duration
)
3532 (org-table-time-string-to-seconds v
)
3535 (setq new
(replace-match
3536 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3537 (if org-table-formula-debug
(propertize new
:orig-formula f
) new
)))
3539 (defun org-table-get-constant (const)
3540 "Find the value for a parameter or constant in a formula.
3541 Parameters get priority."
3542 (or (cdr (assoc const org-table-local-parameters
))
3543 (cdr (assoc const org-table-formula-constants-local
))
3544 (cdr (assoc const org-table-formula-constants
))
3545 (and (fboundp 'constants-get
) (constants-get const
))
3546 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3547 (org-entry-get nil
(substring const
5) 'inherit
))
3550 (defvar org-table-fedit-map
3551 (let ((map (make-sparse-keymap)))
3552 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3553 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3554 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3555 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3556 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3557 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3558 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3559 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3560 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3561 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3562 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3563 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3564 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3565 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3566 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3567 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3568 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3569 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3570 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3571 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3574 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3576 ["Finish and Install" org-table-fedit-finish t
]
3577 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3578 ["Abort" org-table-fedit-abort t
]
3580 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3581 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3583 "Shift Reference at Point"
3584 ["Up" org-table-fedit-ref-up t
]
3585 ["Down" org-table-fedit-ref-down t
]
3586 ["Left" org-table-fedit-ref-left t
]
3587 ["Right" org-table-fedit-ref-right t
]
3589 "Change Test Row for Column Formulas"
3590 ["Up" org-table-fedit-line-up t
]
3591 ["Down" org-table-fedit-line-down t
]
3593 ["Scroll Table Window" org-table-fedit-scroll t
]
3594 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3595 ["Show Table Grid" org-table-fedit-toggle-coordinates
3596 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3597 org-table-overlay-coordinates
)]
3599 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3600 :style toggle
:selected org-table-buffer-is-an
]))
3603 (defvar org-table--fedit-source nil
3604 "Position of the TBLFM line being edited.")
3607 (defun org-table-edit-formulas ()
3608 "Edit the formulas of the current table in a separate buffer."
3610 (let ((at-tblfm (org-at-TBLFM-p)))
3611 (unless (or at-tblfm
(org-at-table-p))
3612 (user-error "Not at a table"))
3614 ;; Move point within the table before analyzing it.
3615 (when at-tblfm
(re-search-backward "^[ \t]*|"))
3616 (org-table-analyze))
3617 (let ((key (org-table-current-field-formula 'key
'noerror
))
3618 (eql (sort (org-table-get-stored-formulas t
(and at-tblfm
(point)))
3619 #'org-table-formula-less-p
))
3620 (pos (point-marker))
3621 (source (copy-marker (line-beginning-position)))
3623 (wc (current-window-configuration))
3624 (sel-win (selected-window))
3625 (titles '((column .
"# Column Formulas\n")
3626 (field .
"# Field and Range Formulas\n")
3627 (named .
"# Named Field Formulas\n"))))
3628 (org-switch-to-buffer-other-window "*Edit Formulas*")
3630 ;; Keep global-font-lock-mode from turning on font-lock-mode
3631 (let ((font-lock-global-modes '(not fundamental-mode
)))
3633 (setq-local font-lock-global-modes
(list 'not major-mode
))
3634 (setq-local org-pos pos
)
3635 (setq-local org-table--fedit-source source
)
3636 (setq-local org-window-configuration wc
)
3637 (setq-local org-selected-window sel-win
)
3638 (use-local-map org-table-fedit-map
)
3639 (add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3640 (easy-menu-add org-table-fedit-menu
)
3641 (setq startline
(org-current-line))
3644 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry
))
3646 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3648 (title (assq type titles
)))
3650 (unless (bobp) (insert "\n"))
3652 (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3653 (setq titles
(remove title titles
)))
3654 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3656 (if (memq (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3657 (car entry
) " = " (cdr entry
) "\n")))
3658 (remove-text-properties 0 (length s
) '(face nil
) s
)
3660 (when (eq org-table-use-standard-references t
)
3661 (org-table-fedit-toggle-ref-type))
3662 (org-goto-line startline
)
3663 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3664 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3665 See menu for more commands.")))))
3667 (defun org-table-fedit-post-command ()
3668 (when (not (memq this-command
'(lisp-complete-symbol)))
3669 (let ((win (selected-window)))
3671 (ignore-errors (org-table-show-reference))
3672 (select-window win
)))))
3674 (defun org-table-formula-to-user (s)
3675 "Convert a formula from internal to user representation."
3676 (if (eq org-table-use-standard-references t
)
3677 (org-table-convert-refs-to-an s
)
3680 (defun org-table-formula-from-user (s)
3681 "Convert a formula from user to internal representation."
3682 (if org-table-use-standard-references
3683 (org-table-convert-refs-to-rc s
)
3686 (defun org-table-convert-refs-to-rc (s)
3687 "Convert spreadsheet references from A7 to @7$28.
3688 Works for single references, but also for entire formulas and even the
3691 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3694 ;; format match, just advance
3695 (setq start
(match-end 0)))
3696 ((and (> (match-beginning 0) 0)
3697 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3698 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3699 ;; 3.e5 or something like this.
3700 (setq start
(match-end 0)))
3701 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3702 ;; (member (match-string 1 s)
3703 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3705 ;; function name, just advance
3706 (setq start
(match-end 0)))
3708 (setq start
(match-beginning 0)
3710 (if (equal (match-string 2 s
) "&")
3711 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3713 (string-to-number (match-string 2 s
))
3714 (org-letters-to-number (match-string 1 s
))))
3718 (defun org-table-convert-refs-to-an (s)
3719 "Convert spreadsheet references from to @7$28 to AB7.
3720 Works for single references, but also for entire formulas and even the
3722 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3723 (setq s
(replace-match
3725 (org-number-to-letters
3726 (string-to-number (match-string 2 s
)))
3727 (string-to-number (match-string 1 s
)))
3729 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3730 (setq s
(replace-match (concat "\\1"
3731 (org-number-to-letters
3732 (string-to-number (match-string 2 s
))) "&")
3736 (defun org-letters-to-number (s)
3737 "Convert a base 26 number represented by letters into an integer.
3738 For example: AB -> 28."
3741 (while (> (length s
) 0)
3742 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3746 (defun org-number-to-letters (n)
3747 "Convert an integer into a base 26 number represented by letters.
3748 For example: 28 -> AB."
3751 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3755 (defun org-table-time-string-to-seconds (s)
3756 "Convert a time string into numerical duration in seconds.
3757 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3758 If S is a string representing a number, keep this number."
3761 (let (hour minus min sec res
)
3763 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3764 (setq minus
(< 0 (length (match-string 1 s
)))
3765 hour
(string-to-number (match-string 2 s
))
3766 min
(string-to-number (match-string 3 s
))
3767 sec
(string-to-number (match-string 4 s
)))
3769 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3770 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3771 ((and (not (string-match org-ts-regexp-both s
))
3772 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3773 (setq minus
(< 0 (length (match-string 1 s
)))
3774 hour
(string-to-number (match-string 2 s
))
3775 min
(string-to-number (match-string 3 s
)))
3777 (setq res
(- (+ (* hour
3600) (* min
60))))
3778 (setq res
(+ (* hour
3600) (* min
60)))))
3779 (t (setq res
(string-to-number s
))))
3780 (number-to-string res
))))
3782 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3783 "Convert a number of seconds to a time string.
3784 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3785 minutes or seconds."
3786 (let* ((secs0 (abs secs
))
3788 (cond ((eq output-format
'days
)
3789 (format "%.3f" (/ (float secs0
) 86400)))
3790 ((eq output-format
'hours
)
3791 (format "%.2f" (/ (float secs0
) 3600)))
3792 ((eq output-format
'minutes
)
3793 (format "%.1f" (/ (float secs0
) 60)))
3794 ((eq output-format
'seconds
)
3795 (format "%d" secs0
))
3796 ((eq output-format
'hh
:mm
)
3798 (substring (format-seconds
3799 (if org-table-duration-hour-zero-padding
3800 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3804 (if org-table-duration-hour-zero-padding
3805 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3807 (if (< secs
0) (concat "-" res
) res
)))
3811 ;;; Columns shrinking
3813 (defun org-table--shrunk-field ()
3814 "Non-nil if current field is narrowed.
3815 When non-nil, return the overlay narrowing the field."
3816 (cl-some (lambda (o)
3817 (and (eq 'table-column-hide
(overlay-get o
'org-overlay-type
))
3819 (overlays-in (1- (point)) (1+ (point)))))
3821 (defun org-table--list-shrunk-columns ()
3822 "List currently shrunk columns in table at point."
3824 ;; We really check shrunk columns in current row only. It could
3825 ;; be wrong if all rows do not contain the same number of columns
3826 ;; (i.e. the table is not properly aligned). As a consequence,
3827 ;; some columns may not be shrunk again upon aligning the table.
3829 ;; For example, in the following table, cursor is on first row and
3830 ;; "<>" indicates a shrunk column.
3835 ;; Aligning table from the first row will not shrink again the
3836 ;; second row, which was not visible initially.
3838 ;; However, fixing it requires to check every row, which may be
3839 ;; slow on large tables. Moreover, the hindrance of this
3840 ;; pathological case is very limited.
3842 (search-forward "|")
3843 (let ((separator (if (org-at-table-hline-p) "+" "|"))
3845 (shrunk (and (org-table--shrunk-field) (list 1)))
3846 (end (line-end-position)))
3847 (while (search-forward separator end t
)
3849 (when (org-table--shrunk-field) (push column shrunk
)))
3850 (nreverse shrunk
))))
3852 (defun org-table--shrink-field (width start end contents
)
3853 "Shrink a table field to a specified width.
3855 WIDTH is an integer representing the number of characters to
3856 display, in addition to `org-table-shrunk-column-indicator'. START
3857 and END are, respectively, the beginning and ending positions of
3858 the field. CONTENTS is its trimmed contents, as a string, or
3859 `hline' for table rules.
3861 Real field is hidden under an overlay. The latter has the
3862 following properties:
3866 Set to `table-column-hide'. Used to identify overlays
3867 responsible for the task.
3869 `org-table-column-overlays'
3871 It is a list with the pattern (siblings . COLUMN-OVERLAYS)
3872 where COLUMN-OVERLAYS is the list of all overlays hiding the
3875 Whenever the text behind or next to the overlay is modified, all
3876 the overlays in the column are deleted, effectively displaying
3879 Return overlay used to hide the field."
3880 (unless (org-table--shrunk-field)
3883 ((= width
0) org-table-shrunk-column-indicator
)
3884 ((eq contents
'hline
)
3885 (concat (make-string (1+ width
) ?-
)
3886 org-table-shrunk-column-indicator
))
3888 ;; Remove invisible parts from links in CONTENTS. Since
3889 ;; shrinking could happen before first fontification
3890 ;; (e.g., using a #+STARTUP keyword), this cannot be done
3891 ;; using text properties.
3892 (let* ((contents (org-string-display contents
))
3893 (field-width (string-width contents
)))
3894 (if (>= width field-width
)
3898 (make-string (- width field-width
) ?\s
)
3899 org-table-shrunk-column-indicator
)
3902 (substring contents
0 width
)
3903 org-table-shrunk-column-indicator
))))))
3905 (list (lambda (o &rest _
)
3906 ;; Removing one overlay removes all other overlays
3907 ;; in the same column.
3908 (mapc #'delete-overlay
3909 (cdr (overlay-get o
'org-table-column-overlays
))))))
3910 (o (make-overlay start end
)))
3911 (overlay-put o
'insert-behind-hooks show-before-edit
)
3912 (overlay-put o
'insert-in-front-hooks show-before-edit
)
3913 (overlay-put o
'modification-hooks show-before-edit
)
3914 (overlay-put o
'org-overlay-type
'table-column-hide
)
3915 (when (stringp contents
) (overlay-put o
'help-echo contents
))
3916 ;; Make sure overlays stays on top of table coordinates
3917 ;; overlays. See `org-table-overlay-coordinates'.
3918 (overlay-put o
'priority
1)
3919 (org-overlay-display o display
'org-table t
)
3922 (defun org-table--read-column-selection (select max
)
3923 "Read column selection select as a list of numbers.
3925 SELECT is a string containing column ranges, separated by white
3926 space characters, see `org-table-hide-column' for details. MAX
3927 is the maximum column number.
3929 Return value is a sorted list of numbers. Ignore any number
3930 outside of the [1;MAX] range."
3937 ((member s
'("-" "1-")) (throw :all
(number-sequence 1 max
)))
3938 ((string-match-p "\\`[0-9]+\\'" s
)
3939 (let ((n (string-to-number s
)))
3940 (and (> n
0) (<= n max
) (list n
))))
3941 ((string-match "\\`\\([0-9]+\\)?-\\([0-9]+\\)?\\'" s
)
3942 (let ((n (match-string 1 s
))
3943 (m (match-string 2 s
)))
3944 (number-sequence (if n
(max 1 (string-to-number n
))
3946 (if m
(min max
(string-to-number m
))
3948 (t nil
))) ;invalid specification
3949 (split-string select
)))
3952 (defun org-table--shrink-columns (columns beg end
)
3953 "Shrink COLUMNS in an Org table.
3954 COLUMNS is a sorted list of column numbers. BEG and END are,
3955 respectively, the beginning position and the end position of the
3957 (org-with-wide-buffer
3958 (font-lock-ensure beg end
)
3963 (while (< (point) end
)
3965 (let* ((hline?
(org-at-table-hline-p))
3966 (separator (if hline?
"+" "|")))
3968 (search-forward "|")
3969 (or (= c
1) ;already there
3970 (search-forward separator
(line-end-position) t
(1- c
))
3971 (throw :continue nil
)) ;skip invalid columns
3972 ;; Extract boundaries and contents from current field.
3973 ;; Also set the column's width if we encounter a width
3974 ;; cookie for the first time.
3975 (let* ((start (point))
3977 (skip-chars-forward (concat "^|" separator
)
3978 (line-end-position))
3980 (contents (if hline?
'hline
3981 (org-trim (buffer-substring start end
)))))
3982 (push (list start end contents
) fields
)
3983 (when (and (null width
)
3985 (string-match "\\`<[lrc]?\\([0-9]+\\)>\\'" contents
))
3986 (setq width
(string-to-number (match-string 1 contents
)))))))
3988 ;; Link overlay to the other overlays in the same column.
3989 (let ((chain (list 'siblings
)))
3990 (dolist (field fields
)
3991 (let ((new (apply #'org-table--shrink-field
(or width
0) field
)))
3992 (push new
(cdr chain
))
3993 (overlay-put new
'org-table-column-overlays chain
))))))))
3995 (defun org-table--expand-all-columns (beg end
)
3996 "Expand all columns in an Org table.
3997 BEG and END are, respectively, the beginning position and the end
3998 position of the table."
3999 (remove-overlays beg end
'org-overlay-type
'table-column-hide
))
4002 (defun org-table-toggle-column-width (&optional arg
)
4003 "Shrink or expand current column in an Org table.
4005 If a width cookie specifies a width W for the column, the first
4006 W visible characters are displayed. Otherwise, the column is
4007 shrunk to a single character.
4009 When optional argument ARG is a string, use it as white space
4010 separated list of column ranges. A column range can be one of
4011 the following patterns:
4014 N-M every column between N and M (both inclusive)
4015 N- every column between N (inclusive) and the last column
4016 -M every column between the first one and M (inclusive)
4019 When called with `\\[universal-argument]' prefix, ask for the \
4020 range specification.
4022 When called with `\\[universal-argument] \\[universal-argument]' \
4023 prefix, expand all columns."
4025 (cond ((not (org-at-table-p)) (user-error "Not in a table"))
4028 (skip-chars-backward "^|" (line-beginning-position))
4029 (or (bolp) (looking-at-p "[ \t]*$"))))
4030 ;; Point is either before first column or past last one.
4031 (user-error "Not in a valid column")))
4032 (let* ((pos (point))
4033 (begin (org-table-begin))
4034 (end (org-table-end))
4035 ;; Compute an upper bound for the number of columns.
4036 ;; Nonexistent columns are ignored anyway.
4037 (max-columns (/ (- (line-end-position) (line-beginning-position)) 2))
4038 (shrunk (org-table--list-shrunk-columns))
4041 ;; Find current column, even when on a hline.
4042 (let ((separator (if (org-at-table-hline-p) "+" "|"))
4046 (search-forward "|" pos t
)
4047 (while (search-forward separator pos t
) (cl-incf c
)))
4050 (org-table--read-column-selection arg max-columns
))
4052 (org-table--read-column-selection
4053 (read-string "Column ranges (e.g. 2-4 6-): ")
4056 (_ (user-error "Invalid argument: %S" arg
)))))
4057 (org-table--expand-all-columns begin end
)
4058 (unless (equal arg
'(16))
4059 (org-table--shrink-columns (cl-set-exclusive-or columns shrunk
) begin end
)
4060 ;; Move before overlay if point is under it.
4061 (let ((o (org-table--shrunk-field)))
4062 (when o
(goto-char (overlay-start o
)))))))
4065 (defun org-table-shrink ()
4066 "Shrink all columns with a width cookie in the table at point.
4067 Columns without a width cookie are expanded."
4069 (unless (org-at-table-p) (user-error "Not at a table"))
4070 (org-with-wide-buffer
4071 (let ((begin (org-table-begin))
4072 (end (org-table-end))
4073 (regexp "|[ \t]*<[lrc]?[0-9]+>[ \t]*\\(|\\|$\\)")
4076 (while (re-search-forward regexp end t
)
4077 (goto-char (match-beginning 1))
4078 (cl-pushnew (org-table-current-column) columns
))
4079 (org-table--expand-all-columns begin end
)
4080 ;; Make sure invisible characters in the table are at the right
4081 ;; place since column widths take them into account.
4082 (org-font-lock-ensure begin end
)
4083 (org-table--shrink-columns (sort columns
#'<) begin end
))))
4089 (defun org-table-fedit-convert-buffer (function)
4090 "Convert all references in this buffer, using FUNCTION."
4091 (let ((origin (copy-marker (line-beginning-position))))
4092 (goto-char (point-min))
4094 (insert (funcall function
(buffer-substring (point) (line-end-position))))
4095 (delete-region (point) (line-end-position))
4098 (set-marker origin nil
)))
4100 (defun org-table-fedit-toggle-ref-type ()
4101 "Convert all references in the buffer from B3 to @3$2 and back."
4103 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
4104 (org-table-fedit-convert-buffer
4105 (if org-table-buffer-is-an
4106 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
4107 (message "Reference type switched to %s"
4108 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
4110 (defun org-table-fedit-ref-up ()
4111 "Shift the reference at point one row/hline up."
4113 (org-table-fedit-shift-reference 'up
))
4114 (defun org-table-fedit-ref-down ()
4115 "Shift the reference at point one row/hline down."
4117 (org-table-fedit-shift-reference 'down
))
4118 (defun org-table-fedit-ref-left ()
4119 "Shift the reference at point one field to the left."
4121 (org-table-fedit-shift-reference 'left
))
4122 (defun org-table-fedit-ref-right ()
4123 "Shift the reference at point one field to the right."
4125 (org-table-fedit-shift-reference 'right
))
4127 (defun org-table-fedit-shift-reference (dir)
4129 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
4130 (if (memq dir
'(left right
))
4131 (org-rematch-and-replace 1 (eq dir
'left
))
4132 (user-error "Cannot shift reference in this direction")))
4133 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
4134 ;; A B3-like reference
4135 (if (memq dir
'(up down
))
4136 (org-rematch-and-replace 2 (eq dir
'up
))
4137 (org-rematch-and-replace 1 (eq dir
'left
))))
4139 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
4140 ;; An internal reference
4141 (if (memq dir
'(up down
))
4142 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
4143 (org-rematch-and-replace 5 (eq dir
'left
))))))
4145 (defun org-rematch-and-replace (n &optional decr hline
)
4146 "Re-match the group N, and replace it with the shifted reference."
4147 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
4148 (goto-char (match-beginning n
))
4149 (and (looking-at (regexp-quote (match-string n
)))
4150 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
4153 (defun org-table-shift-refpart (ref &optional decr hline
)
4154 "Shift a reference part REF.
4155 If DECR is set, decrease the references row/column, else increase.
4156 If HLINE is set, this may be a hline reference, it certainly is not
4157 a translation reference."
4159 (let* ((sign (string-match "^[-+]" ref
)) n
)
4161 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
4163 ((and hline
(string-match "^I+" ref
))
4164 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
4165 (setq n
(+ n
(if decr -
1 1)))
4166 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
4168 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
4170 (concat sign
(make-string n ?I
)))
4172 ((string-match "^[0-9]+" ref
)
4173 (setq n
(string-to-number (concat sign ref
)))
4174 (setq n
(+ n
(if decr -
1 1)))
4176 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
4177 (number-to-string (max 1 n
))))
4179 ((string-match "^[a-zA-Z]+" ref
)
4180 (org-number-to-letters
4181 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
4183 (t (user-error "Cannot shift reference"))))))
4185 (defun org-table-fedit-toggle-coordinates ()
4186 "Toggle the display of coordinates in the referenced table."
4188 (let ((pos (marker-position org-pos
)))
4189 (with-current-buffer (marker-buffer org-pos
)
4192 (org-table-toggle-coordinate-overlays)))))
4194 (defun org-table-fedit-finish (&optional arg
)
4195 "Parse the buffer for formula definitions and install them.
4196 With prefix ARG, apply the new formulas to the table."
4198 (org-table-remove-rectangle-highlight)
4199 (when org-table-use-standard-references
4200 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
4201 (setq org-table-buffer-is-an nil
))
4203 (sel-win org-selected-window
)
4204 (source org-table--fedit-source
)
4206 (goto-char (point-min))
4207 (while (re-search-forward
4208 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
4210 (let ((var (match-string 1))
4211 (form (org-trim (match-string 3))))
4212 (unless (equal form
"")
4213 (while (string-match "[ \t]*\n[ \t]*" form
)
4214 (setq form
(replace-match " " t t form
)))
4215 (when (assoc var eql
)
4216 (user-error "Double formulas for %s" var
))
4217 (push (cons var form
) eql
))))
4218 (set-window-configuration org-window-configuration
)
4219 (select-window sel-win
)
4221 (org-table-store-formulas eql
)
4222 (set-marker pos nil
)
4223 (set-marker source nil
)
4224 (kill-buffer "*Edit Formulas*")
4226 (org-table-recalculate 'all
)
4227 (message "New formulas installed - press C-u C-c C-c to apply."))))
4229 (defun org-table-fedit-abort ()
4230 "Abort editing formulas, without installing the changes."
4232 (org-table-remove-rectangle-highlight)
4233 (let ((pos org-pos
) (sel-win org-selected-window
))
4234 (set-window-configuration org-window-configuration
)
4235 (select-window sel-win
)
4237 (move-marker pos nil
)
4238 (message "Formula editing aborted without installing changes")))
4240 (defun org-table-fedit-lisp-indent ()
4241 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
4243 (let ((pos (point)) beg end ind
)
4244 (beginning-of-line 1)
4246 ((looking-at "[ \t]")
4248 (call-interactively 'lisp-indent-line
))
4249 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
4250 ((not (fboundp 'pp-buffer
))
4251 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
4252 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
4253 (goto-char (- (match-end 0) 2))
4255 (setq ind
(make-string (current-column) ?\
))
4256 (condition-case nil
(forward-sexp 1)
4258 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
4261 (narrow-to-region beg end
)
4262 (if (eq last-command this-command
)
4264 (goto-char (point-min))
4265 (setq this-command nil
)
4266 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
4267 (replace-match " ")))
4269 (untabify (point-min) (point-max))
4270 (goto-char (1+ (point-min)))
4271 (while (re-search-forward "^." nil t
)
4272 (beginning-of-line 1)
4274 (goto-char (point-max))
4275 (org-delete-backward-char 1)))
4279 (defvar org-show-positions nil
)
4281 (defun org-table-show-reference (&optional local
)
4282 "Show the location/value of the $ expression at point.
4283 When LOCAL is non-nil, show references for the table at point."
4285 (org-table-remove-rectangle-highlight)
4286 (when local
(org-table-analyze))
4288 (let ((pos (if local
(point) org-pos
))
4290 (org-inhibit-highlight-removal t
)
4291 (win (selected-window))
4292 (org-show-positions nil
)
4293 var name e what match dest
)
4295 ((org-in-regexp "^@[0-9]+[ \t=]")
4296 (setq match
(concat (substring (match-string 0) 0 -
1)
4298 (substring (match-string 0) 0 -
1)
4301 ((or (org-in-regexp org-table-range-regexp2
)
4302 (org-in-regexp org-table-translate-regexp
)
4303 (org-in-regexp org-table-range-regexp
))
4306 (org-table-convert-refs-to-rc (match-string 0))))
4308 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
4309 ((org-in-regexp "\\$[0-9]+") 'column
)
4311 (t (user-error "No reference at point")))
4312 match
(and what
(or match
(match-string 0))))
4313 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
4314 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
4315 'secondary-selection
))
4316 (add-hook 'before-change-functions
4317 #'org-table-remove-rectangle-highlight
)
4318 (when (eq what
'name
) (setq var
(substring match
1)))
4319 (when (eq what
'range
)
4320 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
4321 (setq match
(org-table-formula-substitute-names match
)))
4325 (re-search-backward "^\\S-" nil t
)
4327 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4328 \\([0-9]+\\|&\\)\\) *=")
4331 (org-table-convert-refs-to-rc (match-string 1))))
4332 (org-table-add-rectangle-overlay
4333 (match-beginning 1) (match-end 1) face2
))))
4334 (if (and (markerp pos
) (marker-buffer pos
))
4335 (if (get-buffer-window (marker-buffer pos
))
4336 (select-window (get-buffer-window (marker-buffer pos
)))
4337 (org-switch-to-buffer-other-window (get-buffer-window
4338 (marker-buffer pos
)))))
4340 (org-table-force-dataline)
4342 (if local org-table-current-begin-pos
(org-table-begin))))
4344 (setq name
(substring dest
1))
4346 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
4347 (org-table-goto-field dest
))
4348 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4350 (org-table-goto-field dest
))
4351 (t (org-table-goto-column (string-to-number name
))))
4352 (move-marker pos
(point))
4353 (org-table-highlight-rectangle nil nil face2
))
4355 ((equal dest match
))
4358 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
4359 ((setq e
(assoc var org-table-named-field-locations
))
4360 (org-table-goto-field var
)
4361 (org-table-highlight-rectangle)
4362 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
4363 ((setq e
(assoc var org-table-column-names
))
4364 (org-table-goto-column (string-to-number (cdr e
)))
4365 (org-table-highlight-rectangle)
4366 (goto-char table-start
)
4367 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
4370 (goto-char (match-beginning 1))
4371 (org-table-highlight-rectangle)
4372 (message "Named column (column %s)" (cdr e
)))
4373 (user-error "Column name not found")))
4376 (org-table-goto-column (string-to-number (substring match
1)))
4377 (org-table-highlight-rectangle)
4378 (message "Column %s" (substring match
1)))
4379 ((setq e
(assoc var org-table-local-parameters
))
4380 (goto-char table-start
)
4381 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
4383 (goto-char (match-beginning 1))
4384 (org-table-highlight-rectangle)
4385 (message "Local parameter."))
4386 (user-error "Parameter not found")))
4387 ((not var
) (user-error "No reference at point"))
4388 ((setq e
(assoc var org-table-formula-constants-local
))
4389 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4391 ((setq e
(assoc var org-table-formula-constants
))
4392 (message "Constant: $%s=%s in `org-table-formula-constants'."
4394 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4395 (message "Constant: $%s=%s, from `constants.el'%s."
4396 var e
(format " (%s units)" constants-unit-system
)))
4397 (t (user-error "Undefined name $%s" var
)))
4399 (when (and org-show-positions
4400 (not (memq this-command
'(org-table-fedit-scroll
4401 org-table-fedit-scroll-down
))))
4402 (push pos org-show-positions
)
4403 (push table-start org-show-positions
)
4404 (let ((min (apply 'min org-show-positions
))
4405 (max (apply 'max org-show-positions
)))
4406 (set-window-start (selected-window) min
)
4408 (or (pos-visible-in-window-p max
)
4409 (set-window-start (selected-window) max
)))))
4410 (select-window win
))))
4412 (defun org-table-force-dataline ()
4413 "Make sure the cursor is in a dataline in a table."
4414 (unless (save-excursion
4415 (beginning-of-line 1)
4416 (looking-at org-table-dataline-regexp
))
4417 (let* ((re org-table-dataline-regexp
)
4418 (p1 (save-excursion (re-search-forward re nil
'move
)))
4419 (p2 (save-excursion (re-search-backward re nil
'move
))))
4421 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4423 ((or p1 p2
) (goto-char (or p1 p2
)))
4424 (t (user-error "No table dataline around here"))))))
4426 (defun org-table-fedit-line-up ()
4427 "Move cursor one line up in the window showing the table."
4429 (org-table-fedit-move 'previous-line
))
4431 (defun org-table-fedit-line-down ()
4432 "Move cursor one line down in the window showing the table."
4434 (org-table-fedit-move 'next-line
))
4436 (defun org-table-fedit-move (command)
4437 "Move the cursor in the window showing the table.
4438 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4439 (let ((org-table-allow-automatic-line-recalculation nil
)
4440 (pos org-pos
) (win (selected-window)) p
)
4441 (select-window (get-buffer-window (marker-buffer org-pos
)))
4443 (call-interactively command
)
4444 (while (and (org-at-table-p)
4445 (org-at-table-hline-p))
4446 (call-interactively command
))
4447 (or (org-at-table-p) (goto-char p
))
4448 (move-marker pos
(point))
4449 (select-window win
)))
4451 (defun org-table-fedit-scroll (N)
4453 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4454 (scroll-other-window N
)))
4456 (defun org-table-fedit-scroll-down (N)
4458 (org-table-fedit-scroll (- N
)))
4460 (defvar org-table-rectangle-overlays nil
)
4462 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4463 "Add a new overlay."
4464 (let ((ov (make-overlay beg end
)))
4465 (overlay-put ov
'face
(or face
'secondary-selection
))
4466 (push ov org-table-rectangle-overlays
)))
4468 (defun org-table-highlight-rectangle (&optional beg end face
)
4469 "Highlight rectangular region in a table.
4470 When buffer positions BEG and END are provided, use them to
4471 delimit the region to highlight. Otherwise, refer to point. Use
4472 FACE, when non-nil, for the highlight."
4473 (let* ((beg (or beg
(point)))
4474 (end (or end
(point)))
4480 (cons (line-beginning-position) (org-table-current-column))))
4484 (cons (line-beginning-position) (org-table-current-column)))))
4485 (when (boundp 'org-show-positions
)
4486 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4487 (goto-char (car start-coordinates
))
4488 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
4489 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
4490 (last-row (car end-coordinates
)))
4491 (while (<= (point) last-row
)
4492 (when (looking-at org-table-dataline-regexp
)
4493 (org-table-goto-column column-start
)
4494 (skip-chars-backward "^|\n")
4496 (org-table-goto-column column-end
)
4497 (skip-chars-forward "^|\n")
4498 (org-table-add-rectangle-overlay p
(point) face
)))
4500 (goto-char (car start-coordinates
)))
4501 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
4503 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
4504 "Remove the rectangle overlays."
4505 (unless org-inhibit-highlight-removal
4506 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4507 (mapc 'delete-overlay org-table-rectangle-overlays
)
4508 (setq org-table-rectangle-overlays nil
)))
4510 (defvar-local org-table-coordinate-overlays nil
4511 "Collects the coordinate grid overlays, so that they can be removed.")
4513 (defun org-table-overlay-coordinates ()
4514 "Add overlays to the table at point, to show row/column coordinates."
4516 (mapc 'delete-overlay org-table-coordinate-overlays
)
4517 (setq org-table-coordinate-overlays nil
)
4519 (let ((id 0) (ih 0) hline eol str ov
)
4520 (goto-char (org-table-begin))
4521 (while (org-at-table-p)
4522 (setq eol
(point-at-eol))
4523 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4524 (push ov org-table-coordinate-overlays
)
4525 (setq hline
(looking-at org-table-hline-regexp
))
4526 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4527 (format "%4d" (setq id
(1+ id
)))))
4528 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4531 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4533 (let* ((beg (1+ (match-beginning 0)))
4534 (s1 (format "$%d" ic
))
4535 (s2 (org-number-to-letters ic
))
4536 (str (if (eq t org-table-use-standard-references
) s2 s1
))
4537 (ov (make-overlay beg
(+ beg
(length str
)))))
4538 (push ov org-table-coordinate-overlays
)
4539 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))))
4543 (defun org-table-toggle-coordinate-overlays ()
4544 "Toggle the display of Row/Column numbers in tables."
4546 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4547 (message "Tables Row/Column numbers display turned %s"
4548 (if org-table-overlay-coordinates
"on" "off"))
4549 (when (and (org-at-table-p) org-table-overlay-coordinates
)
4551 (unless org-table-overlay-coordinates
4552 (mapc 'delete-overlay org-table-coordinate-overlays
)
4553 (setq org-table-coordinate-overlays nil
)))
4556 (defun org-table-toggle-formula-debugger ()
4557 "Toggle the formula debugger in tables."
4559 (setq org-table-formula-debug
(not org-table-formula-debug
))
4560 (message "Formula debugging has been turned %s"
4561 (if org-table-formula-debug
"on" "off")))
4563 ;;; The orgtbl minor mode
4565 ;; Define a minor mode which can be used in other modes in order to
4566 ;; integrate the Org table editor.
4568 ;; This is really a hack, because the Org table editor uses several
4569 ;; keys which normally belong to the major mode, for example the TAB
4570 ;; and RET keys. Here is how it works: The minor mode defines all the
4571 ;; keys necessary to operate the table editor, but wraps the commands
4572 ;; into a function which tests if the cursor is currently inside
4573 ;; a table. If that is the case, the table editor command is
4574 ;; executed. However, when any of those keys is used outside a table,
4575 ;; the function uses `key-binding' to look up if the key has an
4576 ;; associated command in another currently active keymap (minor modes,
4577 ;; major mode, global), and executes that command. There might be
4578 ;; problems if any of the keys used by the table editor is otherwise
4579 ;; used as a prefix key.
4581 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4582 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4583 ;; addresses this by checking explicitly for both bindings.
4585 ;; The optimized version (see variable `orgtbl-optimized') takes over
4586 ;; all keys which are bound to `self-insert-command' in the *global map*.
4587 ;; Some modes bind other commands to simple characters, for example
4588 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4589 ;; active, this binding is ignored inside tables and replaced with a
4590 ;; modified self-insert.
4593 (defvar orgtbl-mode-map
(make-keymap)
4594 "Keymap for `orgtbl-mode'.")
4596 (defvar org-old-auto-fill-inhibit-regexp nil
4597 "Local variable used by `orgtbl-mode'.")
4599 (defconst orgtbl-line-start-regexp
4600 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4601 "Matches a line belonging to an orgtbl.")
4603 (defconst orgtbl-extra-font-lock-keywords
4604 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4605 0 (quote 'org-table
) 'prepend
))
4606 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4608 ;; Install it as a minor mode.
4609 (put 'orgtbl-mode
:included t
)
4610 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4613 (define-minor-mode orgtbl-mode
4614 "The `org-mode' table editor as a minor mode for use in other modes."
4615 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4616 (org-load-modules-maybe)
4618 ((derived-mode-p 'org-mode
)
4619 ;; Exit without error, in case some hook functions calls this
4620 ;; by accident in org-mode.
4621 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4623 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4624 ;; Make sure we are first in minor-mode-map-alist
4625 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4626 ;; FIXME: maybe it should use emulation-mode-map-alists?
4627 (and c
(setq minor-mode-map-alist
4628 (cons c
(delq c minor-mode-map-alist
)))))
4629 (setq-local org-table-may-need-update t
)
4630 (add-hook 'before-change-functions
'org-before-change-function
4632 (setq-local org-old-auto-fill-inhibit-regexp
4633 auto-fill-inhibit-regexp
)
4634 (setq-local auto-fill-inhibit-regexp
4635 (if auto-fill-inhibit-regexp
4636 (concat orgtbl-line-start-regexp
"\\|"
4637 auto-fill-inhibit-regexp
)
4638 orgtbl-line-start-regexp
))
4639 (when (fboundp 'font-lock-add-keywords
)
4640 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4641 (org-restart-font-lock))
4642 (easy-menu-add orgtbl-mode-menu
))
4644 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4645 (remove-hook 'before-change-functions
'org-before-change-function t
)
4646 (when (fboundp 'font-lock-remove-keywords
)
4647 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4648 (org-restart-font-lock))
4649 (easy-menu-remove orgtbl-mode-menu
)
4650 (force-mode-line-update 'all
))))
4652 (defun orgtbl-make-binding (fun n
&rest keys
)
4653 "Create a function for binding in the table minor mode.
4654 FUN is the command to call inside a table. N is used to create a unique
4655 command name. KEYS are keys that should be checked in for a command
4656 to execute outside of tables."
4659 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4661 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4662 "Outside of tables, run the binding of `"
4663 (mapconcat #'key-description keys
"' or `")
4668 (list 'call-interactively
(list 'quote fun
))
4669 (list 'let
'(orgtbl-mode)
4670 (list 'call-interactively
4673 (list 'key-binding k
))
4675 '('orgtbl-error
))))))))
4677 (defun orgtbl-error ()
4678 "Error when there is no default binding for a table key."
4680 (user-error "This key has no function outside tables"))
4682 (defun orgtbl-setup ()
4683 "Setup orgtbl keymaps."
4686 '(([(meta shift left
)] org-table-delete-column
)
4687 ([(meta left
)] org-table-move-column-left
)
4688 ([(meta right
)] org-table-move-column-right
)
4689 ([(meta shift right
)] org-table-insert-column
)
4690 ([(meta shift up
)] org-table-kill-row
)
4691 ([(meta shift down
)] org-table-insert-row
)
4692 ([(meta up
)] org-table-move-row-up
)
4693 ([(meta down
)] org-table-move-row-down
)
4694 ("\C-c\C-w" org-table-cut-region
)
4695 ("\C-c\M-w" org-table-copy-region
)
4696 ("\C-c\C-y" org-table-paste-rectangle
)
4697 ("\C-c\C-w" org-table-wrap-region
)
4698 ("\C-c-" org-table-insert-hline
)
4699 ("\C-c}" org-table-toggle-coordinate-overlays
)
4700 ("\C-c{" org-table-toggle-formula-debugger
)
4701 ("\C-m" org-table-next-row
)
4702 ([(shift return
)] org-table-copy-down
)
4703 ("\C-c?" org-table-field-info
)
4704 ("\C-c " org-table-blank-field
)
4705 ("\C-c+" org-table-sum
)
4706 ("\C-c=" org-table-eval-formula
)
4707 ("\C-c'" org-table-edit-formulas
)
4708 ("\C-c`" org-table-edit-field
)
4709 ("\C-c*" org-table-recalculate
)
4710 ("\C-c^" org-table-sort-lines
)
4711 ("\M-a" org-table-beginning-of-field
)
4712 ("\M-e" org-table-end-of-field
)
4713 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4715 (while (setq elt
(pop bindings
))
4716 (setq nfunc
(1+ nfunc
))
4717 (setq key
(org-key (car elt
))
4719 cmd
(orgtbl-make-binding fun nfunc key
))
4720 (org-defkey orgtbl-mode-map key cmd
))
4722 ;; Special treatment needed for TAB, RET and DEL
4723 (org-defkey orgtbl-mode-map
[(return)]
4724 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4725 (org-defkey orgtbl-mode-map
"\C-m"
4726 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4727 (org-defkey orgtbl-mode-map
[(tab)]
4728 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4729 (org-defkey orgtbl-mode-map
"\C-i"
4730 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4731 (org-defkey orgtbl-mode-map
[(shift tab
)]
4732 (orgtbl-make-binding 'org-table-previous-field
104
4733 [(shift tab
)] [(tab)] "\C-i"))
4734 (org-defkey orgtbl-mode-map
[backspace]
4735 (orgtbl-make-binding 'org-delete-backward-char 109
4736 [backspace] (kbd "DEL")))
4738 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4739 (orgtbl-make-binding 'org-table-previous-field
107
4740 [S-iso-lefttab
] [backtab] [(shift tab)]
4743 (org-defkey orgtbl-mode-map [backtab]
4744 (orgtbl-make-binding 'org-table-previous-field
108
4745 [backtab] [S-iso-lefttab] [(shift tab)]
4748 (org-defkey orgtbl-mode-map "\M-\C-m"
4749 (orgtbl-make-binding 'org-table-wrap-region 105
4750 "\M-\C-m" [(meta return)]))
4751 (org-defkey orgtbl-mode-map [(meta return)]
4752 (orgtbl-make-binding 'org-table-wrap-region 106
4753 [(meta return)] "\M-\C-m"))
4755 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4756 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4758 (when orgtbl-optimized
4759 ;; If the user wants maximum table support, we need to hijack
4760 ;; some standard editing functions
4761 (org-remap orgtbl-mode-map
4762 'self-insert-command 'orgtbl-self-insert-command
4763 'delete-char 'org-delete-char
4764 'delete-backward-char 'org-delete-backward-char)
4765 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4766 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4768 ["Create or convert" org-table-create-or-convert-from-region
4769 :active (not (org-at-table-p)) :keys "C-c |" ]
4771 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4772 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4773 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4774 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4776 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4777 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4778 ["Copy Field from Above"
4779 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4782 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4783 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4784 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4785 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4787 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4788 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4789 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4790 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4791 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4793 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4795 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4796 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4797 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4798 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4801 ["Insert table template" orgtbl-insert-radio-table
4802 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
4803 ["Comment/uncomment table" orgtbl-toggle-comment t])
4805 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4806 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4807 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4808 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4809 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4810 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4811 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4812 ["Sum Column/Rectangle" org-table-sum
4813 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4814 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4816 org-table-toggle-formula-debugger :active (org-at-table-p)
4818 :style toggle :selected org-table-formula-debug]
4819 ["Show Col/Row Numbers"
4820 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4822 :style toggle :selected org-table-overlay-coordinates]
4825 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4826 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4829 (defun orgtbl-ctrl-c-ctrl-c (arg)
4830 "If the cursor is inside a table, realign the table.
4831 If it is a table to be sent away to a receiver, do it.
4832 With prefix arg, also recompute table."
4834 (let ((case-fold-search t) (pos (point)) action)
4836 (beginning-of-line 1)
4838 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4839 ((looking-at "[ \t]*|") pos)
4840 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4844 (org-table-maybe-eval-formula)
4846 (call-interactively 'org-table-recalculate)
4847 (org-table-maybe-recalculate-line))
4848 (call-interactively 'org-table-align)
4849 (when (orgtbl-send-table 'maybe)
4850 (run-hooks 'orgtbl-after-send-table-hook)))
4851 ((eq action 'recalc)
4853 (beginning-of-line 1)
4854 (skip-chars-backward " \r\n\t")
4855 (if (org-at-table-p)
4856 (org-call-with-arg 'org-table-recalculate t))))
4857 (t (let (orgtbl-mode)
4858 (call-interactively (key-binding "\C-c\C-c")))))))
4860 (defun orgtbl-create-or-convert-from-region (_arg)
4861 "Create table or convert region to table, if no conflicting binding.
4862 This installs the table binding `C-c |', but only if there is no
4863 conflicting binding to this key outside orgtbl-mode."
4865 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4867 (call-interactively cmd)
4868 (call-interactively 'org-table-create-or-convert-from-region))))
4870 (defun orgtbl-tab (arg)
4871 "Justification and field motion for `orgtbl-mode'."
4873 (if arg (org-table-edit-field t)
4874 (org-table-justify-field-maybe)
4875 (org-table-next-field)))
4877 (defun orgtbl-ret ()
4878 "Justification and field motion for `orgtbl-mode'."
4882 (org-table-justify-field-maybe)
4883 (org-table-next-row)))
4885 (defun orgtbl-self-insert-command (N)
4886 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4887 If the cursor is in a table looking at whitespace, the whitespace is
4888 overwritten, and the table is not marked as requiring realignment."
4890 (if (and (org-at-table-p)
4892 (and org-table-auto-blank-field
4893 (member last-command
4894 '(orgtbl-hijacker-command-100
4895 orgtbl-hijacker-command-101
4896 orgtbl-hijacker-command-102
4897 orgtbl-hijacker-command-103
4898 orgtbl-hijacker-command-104
4899 orgtbl-hijacker-command-105
4901 (org-table-blank-field))
4904 (looking-at "[^|\n]* \\( \\)|"))
4905 (let (org-table-may-need-update)
4906 (delete-region (match-beginning 1) (match-end 1))
4907 (self-insert-command N))
4908 (setq org-table-may-need-update t)
4911 (cmd (or (key-binding
4912 (or (and (listp function-key-map)
4913 (setq a (assoc last-input-event function-key-map))
4915 (vector last-input-event)))
4916 'self-insert-command)))
4917 (call-interactively cmd)
4918 (if (and org-self-insert-cluster-for-undo
4919 (eq cmd 'self-insert-command))
4920 (if (not (eq last-command 'orgtbl-self-insert-command))
4921 (setq org-self-insert-command-undo-counter 1)
4922 (if (>= org-self-insert-command-undo-counter 20)
4923 (setq org-self-insert-command-undo-counter 1)
4924 (and (> org-self-insert-command-undo-counter 0)
4926 (not (cadr buffer-undo-list)) ; remove nil entry
4927 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4928 (setq org-self-insert-command-undo-counter
4929 (1+ org-self-insert-command-undo-counter))))))))
4932 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4933 "Regular expression matching exponentials as produced by calc.")
4935 (defun orgtbl-gather-send-defs ()
4936 "Gather a plist of :name, :transform, :params for each destination before
4939 (goto-char (org-table-begin))
4941 (beginning-of-line 0)
4942 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4943 (let ((name (org-no-properties (match-string 1)))
4944 (transform (intern (match-string 2)))
4945 (params (if (match-end 3)
4946 (read (concat "(" (match-string 3) ")")))))
4947 (push (list :name name :transform transform :params params)
4949 (beginning-of-line 0)))
4952 (defun orgtbl-send-replace-tbl (name text)
4953 "Find and replace table NAME with TEXT."
4955 (goto-char (point-min))
4956 (let* ((location-flag nil)
4957 (name (regexp-quote name))
4958 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4959 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4960 (while (re-search-forward begin-re nil t)
4961 (unless location-flag (setq location-flag t))
4962 (let ((beg (line-beginning-position 2)))
4963 (unless (re-search-forward end-re nil t)
4964 (user-error "Cannot find end of receiver location at %d" beg))
4966 (delete-region beg (point))
4967 (insert text "\n")))
4968 (unless location-flag
4969 (user-error "No valid receiver location found in the buffer")))))
4972 (defun org-table-to-lisp (&optional txt)
4973 "Convert the table at point to a Lisp structure.
4974 The structure will be a list. Each item is either the symbol `hline'
4975 for a horizontal separator line, or a list of field values as strings.
4976 The table is taken from the parameter TXT, or from the buffer at point."
4977 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4979 (buffer-substring-no-properties (org-table-begin)
4982 (if (string-match org-table-hline-regexp x) 'hline
4983 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4984 (org-split-string txt "[ \t]*\n[ \t]*"))))
4986 (defun orgtbl-send-table (&optional maybe)
4987 "Send a transformed version of table at point to the receiver position.
4988 With argument MAYBE, fail quietly if no transformation is defined
4992 (unless (org-at-table-p) (user-error "Not at a table"))
4993 ;; when non-interactive, we assume align has just happened.
4994 (when (called-interactively-p 'any) (org-table-align))
4995 (let ((dests (orgtbl-gather-send-defs))
4996 (table (org-table-to-lisp
4997 (buffer-substring-no-properties (org-table-begin)
5001 (if maybe (throw 'exit nil)
5002 (user-error "Don't know how to transform this table")))
5003 (dolist (dest dests)
5004 (let ((name (plist-get dest :name))
5005 (transform (plist-get dest :transform))
5006 (params (plist-get dest :params)))
5007 (unless (fboundp transform)
5008 (user-error "No such transformation function %s" transform))
5009 (orgtbl-send-replace-tbl name (funcall transform table params)))
5011 (message "Table converted and installed at %d receiver location%s"
5012 ntbl (if (> ntbl 1) "s" ""))
5013 (and (> ntbl 0) ntbl))))
5015 (defun org-remove-by-index (list indices &optional i0)
5016 "Remove the elements in LIST with indices in INDICES.
5017 First element has index 0, or I0 if given."
5020 (if (integerp indices) (setq indices (list indices)))
5021 (setq i0 (1- (or i0 0)))
5022 (delq :rm (mapcar (lambda (x)
5024 (if (memq i0 indices) :rm x))
5027 (defun orgtbl-toggle-comment ()
5028 "Comment or uncomment the orgtbl at point."
5030 (let* ((case-fold-search t)
5031 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
5032 (re2 (concat "^" orgtbl-line-start-regexp))
5033 (commented (save-excursion (beginning-of-line 1)
5034 (cond ((looking-at re1) t)
5035 ((looking-at re2) nil)
5036 (t (user-error "Not at an org table")))))
5037 (re (if commented re1 re2))
5040 (beginning-of-line 1)
5041 (while (looking-at re) (beginning-of-line 0))
5042 (beginning-of-line 2)
5044 (while (looking-at re) (beginning-of-line 2))
5046 (comment-region beg end (if commented '(4) nil))))
5048 (defun orgtbl-insert-radio-table ()
5049 "Insert a radio table template appropriate for this major mode."
5051 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
5054 (unless e (user-error "No radio table setup defined for %s" major-mode))
5055 (setq name (read-string "Table name: "))
5056 (while (string-match "%n" txt)
5057 (setq txt (replace-match name t t txt)))
5058 (or (bolp) (insert "\n"))
5064 (defun orgtbl-to-generic (table params)
5065 "Convert the orgtbl-mode TABLE to some other format.
5067 This generic routine can be used for many standard cases.
5069 TABLE is a list, each entry either the symbol `hline' for
5070 a horizontal separator line, or a list of fields for that
5071 line. PARAMS is a property list of parameters that can
5072 influence the conversion.
5074 Valid parameters are:
5078 Export back-end used as a basis to transcode elements of the
5079 table, when no specific parameter applies to it. It is also
5080 used to translate cells contents. You can prevent this by
5081 setting :raw property to a non-nil value.
5085 When non-nil, only convert rows, not the table itself. This is
5086 equivalent to setting to the empty string both :tstart
5087 and :tend, which see.
5091 When set to an integer N, skip the first N lines of the table.
5092 Horizontal separation lines do count for this parameter!
5096 List of columns that should be skipped. If the table has
5097 a column with calculation marks, that column is automatically
5098 discarded beforehand.
5102 String to be inserted on horizontal separation lines. May be
5103 nil to ignore these lines altogether.
5107 Separator between two fields, as a string.
5109 Each in the following group may be either a string or a function
5110 of no arguments returning a string:
5114 Strings to start and end the table. Ignored when :splice is t.
5118 Strings to start and end a new table line.
5122 Strings to start and end the last table line. Default,
5123 respectively, to :lstart and :lend.
5125 Each in the following group may be a string or a function of one
5126 argument (either the cells in the current row, as a list of
5127 strings, or the current cell) returning a string:
5131 Format string for an entire row, with enough %s to capture all
5132 fields. When non-nil, :lstart, :lend, and :sep are ignored.
5136 Format for the entire last line, defaults to :lfmt.
5140 A format to be used to wrap the field, should contain %s for
5141 the original field value. For example, to wrap everything in
5142 dollars, you could use :fmt \"$%s$\". This may also be
5143 a property list with column numbers and format strings, or
5146 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
5148 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
5150 Same as above, specific for the header lines in the table.
5151 All lines before the first hline are treated as header. If
5152 any of these is not present, the data line value is used.
5154 This may be either a string or a function of two arguments:
5158 Use this format to print numbers with exponential. The format
5159 should have %s twice for inserting mantissa and exponent, for
5160 example \"%s\\\\times10^{%s}\". This may also be a property
5161 list with column numbers and format strings or functions.
5162 :fmt will still be applied after :efmt."
5163 ;; Make sure `org-export-create-backend' is available.
5165 (let* ((backend (plist-get params :backend))
5167 ;; Build a custom back-end according to PARAMS. Before
5168 ;; defining a translator, check if there is anything to do.
5169 ;; When there isn't, let BACKEND handle the element.
5170 (org-export-create-backend
5171 :parent (or backend 'org)
5173 `((table . ,(org-table--to-generic-table params))
5174 (table-row . ,(org-table--to-generic-row params))
5175 (table-cell . ,(org-table--to-generic-cell params))
5176 ;; Macros are not going to be expanded. However, no
5177 ;; regular back-end has a transcoder for them. We
5178 ;; provide one so they are not ignored, but displayed
5180 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
5182 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
5183 ;; Initialize communication channel in INFO.
5185 (let ((org-inhibit-startup t)) (org-mode))
5186 (let ((standard-output (current-buffer))
5187 (org-element-use-cache nil))
5189 (cond ((eq e 'hline) (princ "|--\n"))
5191 (princ "| ") (dolist (c e) (princ c) (princ " |"))
5193 ;; Add back-end specific filters, but not user-defined ones. In
5194 ;; particular, make sure to call parse-tree filters on the
5197 (let ((org-export-filters-alist nil))
5198 (org-export-install-filters
5200 (org-export-get-environment backend nil params)
5201 `(:back-end ,(org-export-get-backend backend))))))
5203 (org-export-filter-apply-functions
5204 (plist-get info :filter-parse-tree)
5205 (org-element-map (org-element-parse-buffer) 'table
5208 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
5209 (user-error "Unknown :backend value"))
5210 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
5211 ;; Handle :skip parameter.
5212 (let ((skip (plist-get info :skip)))
5214 (unless (wholenump skip) (user-error "Wrong :skip value"))
5216 (org-element-map data 'table-row
5219 (org-element-extract-element row)
5223 ;; Handle :skipcols parameter.
5224 (let ((skipcols (plist-get info :skipcols)))
5226 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
5227 (org-element-map data 'table
5229 (let ((specialp (org-export-table-has-special-column-p table)))
5230 (dolist (row (org-element-contents table))
5231 (when (eq (org-element-property :type row) 'standard)
5233 (dolist (cell (nthcdr (if specialp 1 0)
5234 (org-element-contents row)))
5235 (when (memq c skipcols)
5236 (org-element-extract-element cell))
5237 (cl-incf c))))))))))
5238 ;; Since we are going to export using a low-level mechanism,
5239 ;; ignore special column and special rows manually.
5240 (let ((special? (org-export-table-has-special-column-p data))
5242 (org-element-map data (if special? '(table-cell table-row) 'table-row)
5244 (when (if (eq (org-element-type datum) 'table-row)
5245 (org-export-table-row-is-special-p datum nil)
5246 (org-export-first-sibling-p datum nil))
5247 (push datum ignore))))
5248 (setq info (plist-put info :ignore-list ignore)))
5249 ;; We use a low-level mechanism to export DATA so as to skip all
5250 ;; usual pre-processing and post-processing, i.e., hooks, Babel
5251 ;; code evaluation, include keywords and macro expansion. Only
5252 ;; back-end specific filters are retained.
5253 (let ((output (org-export-data-with-backend data custom-backend info)))
5254 ;; Remove final newline.
5255 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
5257 (defun org-table--generic-apply (value name &optional with-cons &rest args)
5258 (cond ((null value) nil)
5259 ((functionp value) `(funcall ',value ,@args))
5261 (cond ((consp (car args)) `(apply #'format ,value ,@args))
5262 (args `(format ,value ,@args))
5264 ((and with-cons (consp value))
5265 `(let ((val (cadr (memq column ',value))))
5266 (cond ((null val) contents)
5267 ((stringp val) (format val ,@args))
5268 ((functionp val) (funcall val ,@args))
5269 (t (user-error "Wrong %s value" ,name)))))
5270 (t (user-error "Wrong %s value" name))))
5272 (defun org-table--to-generic-table (params)
5273 "Return custom table transcoder according to PARAMS.
5274 PARAMS is a plist. See `orgtbl-to-generic' for more
5276 (let ((backend (plist-get params :backend))
5277 (splice (plist-get params :splice))
5278 (tstart (plist-get params :tstart))
5279 (tend (plist-get params :tend)))
5280 `(lambda (table contents info)
5282 ,(and tstart (not splice)
5283 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
5284 ,(if (or (not backend) tstart tend splice) 'contents
5285 `(org-export-with-backend ',backend table contents info))
5286 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
5288 (defun org-table--to-generic-row (params)
5289 "Return custom table row transcoder according to PARAMS.
5290 PARAMS is a plist. See `orgtbl-to-generic' for more
5292 (let* ((backend (plist-get params :backend))
5293 (lstart (plist-get params :lstart))
5294 (llstart (plist-get params :llstart))
5295 (hlstart (plist-get params :hlstart))
5296 (hllstart (plist-get params :hllstart))
5297 (lend (plist-get params :lend))
5298 (llend (plist-get params :llend))
5299 (hlend (plist-get params :hlend))
5300 (hllend (plist-get params :hllend))
5301 (lfmt (plist-get params :lfmt))
5302 (llfmt (plist-get params :llfmt))
5303 (hlfmt (plist-get params :hlfmt))
5304 (hllfmt (plist-get params :hllfmt)))
5305 `(lambda (row contents info)
5306 (if (eq (org-element-property :type row) 'rule)
5308 ((plist-member params :hline)
5309 (org-table--generic-apply (plist-get params :hline) ":hline"))
5310 (backend `(org-export-with-backend ',backend row nil info)))
5311 (let ((headerp ,(and (or hlfmt hlstart hlend)
5312 '(org-export-table-row-in-header-p row info)))
5314 ,(and (or hllfmt hllstart hllend)
5315 '(org-export-table-row-ends-header-p row info)))
5316 (lastp (not (org-export-get-next-element row info))))
5318 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5319 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5320 ;; `:lstart', `:lend' and their relatives.
5322 '(org-element-map row 'table-cell
5324 ;; Export all cells, without separators.
5326 ;; Use `org-export-data-with-backend'
5327 ;; instead of `org-export-data' to eschew
5328 ;; cached values, which
5329 ;; ignore :orgtbl-ignore-sep parameter.
5330 (org-export-data-with-backend
5332 (plist-get info :back-end)
5333 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5337 `(last-header-p ,(org-table--generic-apply
5338 hllfmt ":hllfmt" nil cells)))
5340 `(headerp ,(org-table--generic-apply
5341 hlfmt ":hlfmt" nil cells)))
5343 `(lastp ,(org-table--generic-apply
5344 llfmt ":llfmt" nil cells)))
5346 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5350 (or hllstart hllend)
5353 ,(org-table--generic-apply hllstart ":hllstart")
5355 ,(org-table--generic-apply hllend ":hllend"))))
5360 ,(org-table--generic-apply hlstart ":hlstart")
5362 ,(org-table--generic-apply hlend ":hlend"))))
5367 ,(org-table--generic-apply llstart ":llstart")
5369 ,(org-table--generic-apply llend ":llend"))))
5374 ,(org-table--generic-apply lstart ":lstart")
5376 ,(org-table--generic-apply lend ":lend")))
5378 `(org-export-with-backend
5379 ',backend row contents info))
5380 (t 'contents)))))))))))))))
5382 (defun org-table--to-generic-cell (params)
5383 "Return custom table cell transcoder according to PARAMS.
5384 PARAMS is a plist. See `orgtbl-to-generic' for more
5386 (let* ((backend (plist-get params :backend))
5387 (efmt (plist-get params :efmt))
5388 (fmt (plist-get params :fmt))
5389 (hfmt (plist-get params :hfmt))
5390 (sep (plist-get params :sep))
5391 (hsep (plist-get params :hsep)))
5392 `(lambda (cell contents info)
5393 ;; Make sure that contents are exported as Org data when :raw
5394 ;; parameter is non-nil.
5395 ,(when (and backend (plist-get params :raw))
5397 ;; Since we don't know what are the pseudo object
5398 ;; types defined in backend, we cannot pass them to
5399 ;; `org-element-interpret-data'. As a consequence,
5400 ;; they will be treated as pseudo elements, and will
5401 ;; have newlines appended instead of spaces.
5402 ;; Therefore, we must make sure :post-blank value is
5403 ;; really turned into spaces.
5404 (replace-regexp-in-string
5407 (org-element-interpret-data
5408 (org-element-contents cell))))))
5410 (let ((headerp ,(and (or hfmt hsep)
5411 '(org-export-table-row-in-header-p
5412 (org-export-get-parent-element cell) info)))
5414 ;; Call costly `org-export-table-cell-address' only if
5415 ;; absolutely necessary, i.e., if one
5416 ;; of :fmt :efmt :hmft has a "plist type" value.
5417 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5418 (list efmt hfmt fmt))
5419 '(1+ (cdr (org-export-table-cell-address cell info))))))
5421 ;; Check if we can apply `:efmt' on CONTENTS.
5423 `(when (string-match orgtbl-exp-regexp contents)
5424 (let ((mantissa (match-string 1 contents))
5425 (exponent (match-string 2 contents)))
5426 (setq contents ,(org-table--generic-apply
5427 efmt ":efmt" t 'mantissa 'exponent)))))
5428 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5430 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5431 hfmt ":hfmt" t 'contents))))
5432 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5433 fmt ":fmt" t 'contents))))))
5434 ;; If a separator is provided, use it instead of BACKEND's.
5435 ;; Separators are ignored when LFMT (or equivalent) is
5439 `(if (or ,(and (not sep) '(not headerp))
5440 (plist-get info :orgtbl-ignore-sep)
5441 (not (org-export-get-next-element cell info)))
5442 ,(if (not backend) 'contents
5443 `(org-export-with-backend ',backend cell contents info))
5445 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5447 (backend `(org-export-with-backend ',backend cell contents info))
5451 (defun orgtbl-to-tsv (table params)
5452 "Convert the orgtbl-mode table to TAB separated material."
5453 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5456 (defun orgtbl-to-csv (table params)
5457 "Convert the orgtbl-mode table to CSV material.
5458 This does take care of the proper quoting of fields with comma or quotes."
5459 (orgtbl-to-generic table
5460 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5464 (defun orgtbl-to-latex (table params)
5465 "Convert the orgtbl-mode TABLE to LaTeX.
5467 TABLE is a list, each entry either the symbol `hline' for
5468 a horizontal separator line, or a list of fields for that line.
5469 PARAMS is a property list of parameters that can influence the
5470 conversion. All parameters from `orgtbl-to-generic' are
5471 supported. It is also possible to use the following ones:
5475 When non-nil, use formal \"booktabs\" style.
5479 Specify environment to use, as a string. If you use
5480 \"longtable\", you may also want to specify :language property,
5481 as a string, to get proper continuation strings."
5486 ;; Provide sane default values.
5487 (list :backend 'latex
5488 :latex-default-table-mode 'table
5489 :latex-tables-centered nil
5490 :latex-tables-booktabs (plist-get params :booktabs)
5491 :latex-table-scientific-notation nil
5492 :latex-default-table-environment
5493 (or (plist-get params :environment) "tabular"))
5497 (defun orgtbl-to-html (table params)
5498 "Convert the orgtbl-mode TABLE to HTML.
5500 TABLE is a list, each entry either the symbol `hline' for
5501 a horizontal separator line, or a list of fields for that line.
5502 PARAMS is a property list of parameters that can influence the
5503 conversion. All parameters from `orgtbl-to-generic' are
5504 supported. It is also possible to use the following one:
5508 Attributes and values, as a plist, which will be used in
5514 ;; Provide sane default values.
5515 (list :backend 'html
5516 :html-table-data-tags '("<td%s>" . "</td>")
5517 :html-table-use-header-tags-for-first-column nil
5518 :html-table-align-individual-fields t
5519 :html-table-row-tags '("<tr>" . "</tr>")
5520 :html-table-attributes
5521 (if (plist-member params :attributes)
5522 (plist-get params :attributes)
5523 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5528 (defun orgtbl-to-texinfo (table params)
5529 "Convert the orgtbl-mode TABLE to Texinfo.
5531 TABLE is a list, each entry either the symbol `hline' for
5532 a horizontal separator line, or a list of fields for that line.
5533 PARAMS is a property list of parameters that can influence the
5534 conversion. All parameters from `orgtbl-to-generic' are
5535 supported. It is also possible to use the following one:
5539 Column widths, as a string. When providing column fractions,
5540 \"@columnfractions\" command can be omitted."
5541 (require 'ox-texinfo)
5546 (list :backend 'texinfo
5547 :texinfo-tables-verbatim nil
5548 :texinfo-table-scientific-notation nil)
5550 (columns (let ((w (plist-get params :columns)))
5552 ((string-match-p "{\\|@columnfractions " w) w)
5553 (t (concat "@columnfractions " w))))))
5554 (if (not columns) output
5555 (replace-regexp-in-string
5556 "@multitable \\(.*\\)" columns output t nil 1))))
5559 (defun orgtbl-to-orgtbl (table params)
5560 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5562 TABLE is a list, each entry either the symbol `hline' for
5563 a horizontal separator line, or a list of fields for that line.
5564 PARAMS is a property list of parameters that can influence the
5565 conversion. All parameters from `orgtbl-to-generic' are
5568 Useful when slicing one table into many. The :hline, :sep,
5569 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5570 be set to provide ORGTBL directives for the generated table."
5572 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5574 (defun orgtbl-to-table.el (table params)
5575 "Convert the orgtbl-mode TABLE into a table.el table.
5576 TABLE is a list, each entry either the symbol `hline' for
5577 a horizontal separator line, or a list of fields for that line.
5578 PARAMS is a property list of parameters that can influence the
5579 conversion. All parameters from `orgtbl-to-generic' are
5582 (insert (orgtbl-to-orgtbl table params))
5584 (replace-regexp-in-string
5586 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5588 (defun orgtbl-to-unicode (table params)
5589 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5591 TABLE is a list, each entry either the symbol `hline' for
5592 a horizontal separator line, or a list of fields for that line.
5593 PARAMS is a property list of parameters that can influence the
5594 conversion. All parameters from `orgtbl-to-generic' are
5595 supported. It is also possible to use the following ones:
5599 When non-nil, use \"ascii-art-to-unicode\" package to translate
5600 the table. You can download it here:
5601 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5605 When non-nil, narrow columns width than provided width cookie,
5606 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5611 (list :backend 'ascii
5612 :ascii-charset 'utf-8
5613 :ascii-table-widen-columns (not (plist-get params :narrow))
5614 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5617 ;; Put the cursor in a column containing numerical values
5620 ;; A new column is added with a bar plot.
5621 ;; When the table is refreshed (C-u C-c *),
5622 ;; the plot is updated to reflect the new values.
5624 (defun orgtbl-ascii-draw (value min max &optional width characters)
5625 "Draw an ascii bar in a table.
5626 VALUE is the value to plot, it determines the width of the bar to draw.
5627 MIN is the value that will be displayed as empty (zero width bar).
5628 MAX is the value that will draw a bar filling all the WIDTH.
5629 WIDTH is the span in characters from MIN to MAX.
5630 CHARACTERS is a string that will compose the bar, with shades of grey
5631 from pure white to pure black. It defaults to a 10 characters string
5632 of regular ascii characters."
5633 (let* ((width (ceiling (or width 12)))
5634 (characters (or characters " .:;c!lhVHW"))
5635 (len (1- (length characters)))
5636 (value (float (if (numberp value)
5637 value (string-to-number value))))
5638 (relative (/ (- value min) (- max min)))
5639 (steps (round (* relative width len))))
5640 (cond ((< steps 0) "too small")
5641 ((> steps (* width len)) "too large")
5642 (t (let* ((int-division (/ steps len))
5643 (remainder (- steps (* int-division len))))
5644 (concat (make-string int-division (elt characters len))
5645 (string (elt characters remainder))))))))
5648 (defun orgtbl-ascii-plot (&optional ask)
5649 "Draw an ASCII bar plot in a column.
5651 With cursor in a column containing numerical values, this function
5652 will draw a plot in a new column.
5654 ASK, if given, is a numeric prefix to override the default 12
5655 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5657 which will prompt for the width."
5659 (let ((col (org-table-current-column))
5660 (min 1e999) ; 1e999 will be converted to infinity
5661 (max -1e999) ; which is the desired result
5662 (table (org-table-to-lisp))
5665 (read-number "Length of column " 12))
5668 ;; Skip any hline a the top of table.
5669 (while (eq (car table) 'hline) (setq table (cdr table)))
5670 ;; Skip table header if any.
5671 (dolist (x (or (cdr (memq 'hline table)) table))
5673 (setq x (nth (1- col) x))
5675 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5677 (setq x (string-to-number x))
5678 (when (> min x) (setq min x))
5679 (when (< max x) (setq max x)))))
5680 (org-table-insert-column)
5681 (org-table-move-column-right)
5682 (org-table-store-formulas
5685 (concat "$" (number-to-string (1+ col)))
5686 (format "'(%s $%s %s %s %s)"
5687 "orgtbl-ascii-draw" col min max length))
5688 (org-table-get-stored-formulas)))
5689 (org-table-recalculate t)))
5691 ;; Example of extension: unicode characters
5692 ;; Here are two examples of different styles.
5694 ;; Unicode block characters are used to give a smooth effect.
5695 ;; See http://en.wikipedia.org/wiki/Block_Elements
5696 ;; Use one of those drawing functions
5697 ;; - orgtbl-ascii-draw (the default ascii)
5698 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5699 ;; - orgtbl-uc-draw-cont (smooth unicode)
5701 ;; This is best viewed with the "DejaVu Sans Mono" font
5702 ;; (use M-x set-default-font).
5704 (defun orgtbl-uc-draw-grid (value min max &optional width)
5705 "Draw a bar in a table using block unicode characters.
5706 It is a variant of orgtbl-ascii-draw with Unicode block
5707 characters, for a smooth display. Bars appear as grids (to the
5708 extent the font allows)."
5709 ;; http://en.wikipedia.org/wiki/Block_Elements
5710 ;; best viewed with the "DejaVu Sans Mono" font.
5711 (orgtbl-ascii-draw value min max width
5712 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5714 (defun orgtbl-uc-draw-cont (value min max &optional width)
5715 "Draw a bar in a table using block unicode characters.
5716 It is a variant of orgtbl-ascii-draw with Unicode block
5717 characters, for a smooth display. Bars are solid (to the extent
5719 (orgtbl-ascii-draw value min max width
5720 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5722 (defun org-table-get-remote-range (name-or-id form)
5723 "Get a field value or a list of values in a range from table at ID.
5725 NAME-OR-ID may be the name of a table in the current file as set
5726 by a \"#+NAME:\" directive. The first table following this line
5727 will then be used. Alternatively, it may be an ID referring to
5728 any entry, also in a different file. In this case, the first
5729 table in that entry will be referenced.
5730 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5731 \"@I$2..@II$2\". All the references must be absolute, not relative.
5733 The return value is either a single string for a single field, or a
5734 list of the fields in the rectangle."
5736 (let ((case-fold-search t) (id-loc nil)
5737 ;; Protect a bunch of variables from being overwritten by
5738 ;; the context of the remote table.
5739 org-table-column-names org-table-column-name-regexp
5740 org-table-local-parameters org-table-named-field-locations
5741 org-table-current-line-types
5742 org-table-current-begin-pos org-table-dlines
5743 org-table-current-ncol
5744 org-table-hlines org-table-last-alignment
5745 org-table-last-column-widths org-table-last-alignment
5746 org-table-last-column-widths
5748 (setq form (org-table-convert-refs-to-rc form))
5749 (org-with-wide-buffer
5750 (goto-char (point-min))
5751 (if (re-search-forward
5752 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5753 (regexp-quote name-or-id) "[ \t]*$")
5755 (setq buffer (current-buffer) loc (match-beginning 0))
5756 (setq id-loc (org-id-find name-or-id 'marker))
5757 (unless (and id-loc (markerp id-loc))
5758 (user-error "Can't find remote table \"%s\"" name-or-id))
5759 (setq buffer (marker-buffer id-loc)
5760 loc (marker-position id-loc))
5761 (move-marker id-loc nil))
5762 (with-current-buffer buffer
5763 (org-with-wide-buffer
5766 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5767 (not (match-beginning 1)))
5768 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5770 (setq form (org-table-formula-substitute-names
5771 (org-table-formula-handle-first/last-rc form)))
5772 (if (and (string-match org-table-range-regexp form)
5773 (> (length (match-string 0 form)) 1))
5774 (org-table-get-range
5775 (match-string 0 form) org-table-current-begin-pos 1)
5778 (defun org-table-remote-reference-indirection (form)
5779 "Return formula with table remote references substituted by indirection.
5780 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5781 This indirection works only with the format @ROW$COLUMN. The
5782 format \"B3\" is not supported because it can not be
5783 distinguished from a plain table name or ID."
5785 ;; Same as in `org-table-eval-formula'.
5786 (concat "\\<remote([ \t]*\\("
5787 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5789 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5790 (replace-regexp-in-string
5794 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5795 (org-table-get-range
5796 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5801 (defmacro org-define-lookup-function (mode)
5802 (let ((mode-str (symbol-name mode))
5803 (first-p (eq mode 'first))
5804 (all-p (eq mode 'all)))
5805 (let ((plural-str (if all-p "s" "")))
5806 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5807 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5808 If R-LIST is nil, return matching element%s of S-LIST.
5809 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5810 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5811 This function is generated by a call to the macro `org-define-lookup-function'."
5812 mode-str plural-str plural-str plural-str)
5813 (let ,(let ((lvars '((p (or predicate 'equal))
5815 (rl (or r-list s-list))
5817 (if first-p (cons '(match-p nil) lvars) lvars))
5818 (while ,(if first-p '(and (not match-p) sl) 'sl)
5819 (when (funcall p val (car sl))
5820 ,(when first-p '(setq match-p t))
5821 (let ((rval (car rl)))
5822 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5823 (setq sl (cdr sl) rl (cdr rl)))
5826 (org-define-lookup-function first)
5827 (org-define-lookup-function last)
5828 (org-define-lookup-function all)
5830 (provide 'org-table)
5833 ;; generated-autoload-file: "org-loaddefs.el"
5836 ;;; org-table.el ends here