1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
40 (declare-function org-element-at-point
"org-element" ())
41 (declare-function org-element-contents
"org-element" (element))
42 (declare-function org-element-extract-element
"org-element" (element))
43 (declare-function org-element-interpret-data
"org-element" (data))
44 (declare-function org-element-lineage
"org-element"
45 (blob &optional types with-self
))
46 (declare-function org-element-map
"org-element"
48 &optional info first-match no-recursion with-affiliated
))
49 (declare-function org-element-parse-buffer
"org-element"
50 (&optional granularity visible-only
))
51 (declare-function org-element-property
"org-element" (property element
))
52 (declare-function org-element-type
"org-element" (element))
54 (declare-function org-export-create-backend
"ox" (&rest rest
) t
)
55 (declare-function org-export-data-with-backend
"ox" (data backend info
))
56 (declare-function org-export-filter-apply-functions
"ox"
58 (declare-function org-export-first-sibling-p
"ox" (blob info
))
59 (declare-function org-export-get-backend
"ox" (name))
60 (declare-function org-export-get-environment
"ox"
61 (&optional backend subtreep ext-plist
))
62 (declare-function org-export-install-filters
"ox" (info))
63 (declare-function org-export-table-has-special-column-p
"ox" (table))
64 (declare-function org-export-table-row-is-special-p
"ox" (table-row info
))
66 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
68 (defvar constants-unit-system
)
69 (defvar org-element-use-cache
)
70 (defvar org-export-filters-alist
)
71 (defvar org-table-follow-field-mode
)
72 (defvar orgtbl-mode
) ; defined below
73 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
74 (defvar sort-fold-case
)
76 (defvar orgtbl-after-send-table-hook nil
77 "Hook for functions attaching to `C-c C-c', if the table is sent.
78 This can be used to add additional functionality after the table is sent
79 to the receiver position, otherwise, if table is not sent, the functions
82 (defvar org-table-TBLFM-begin-regexp
"^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
84 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
85 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
86 In the optimized version, the table editor takes over all simple keys that
87 normally just insert a character. In tables, the characters are inserted
88 in a way to minimize disturbing the table structure (i.e. in overwrite mode
89 for empty fields). Outside tables, the correct binding of the keys is
92 The default for this option is t if the optimized version is also used in
93 Org mode. See the variable `org-enable-table-editor' for details. Changing
94 this variable requires a restart of Emacs to become effective."
98 (defcustom orgtbl-radio-table-templates
99 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
100 % END RECEIVE ORGTBL %n
102 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
105 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
106 @c END RECEIVE ORGTBL %n
108 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
111 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
112 <!-- END RECEIVE ORGTBL %n -->
114 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
117 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
118 #+ END RECEIVE ORGTBL %n
120 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
123 "Templates for radio tables in different major modes.
124 Each template must define lines that will be treated as a comment and that
125 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
126 lines where \"%n\" will be replaced with the name of the table during
127 insertion of the template. The transformed table will later be inserted
130 The template should also contain a minimal table in a multiline comment.
131 If multiline comments are not possible in the buffer language,
132 you can pack it into a string that will not be used when the code
133 is compiled or executed. Above the table will you need a line with
134 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
135 convert the table into a data structure useful in the
136 language of the buffer. Check the manual for the section on
137 \"Translator functions\", and more generally check out
138 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
140 All occurrences of %n in a template will be replaced with the name of the
141 table, obtained by prompting the user."
144 (list (symbol :tag
"Major mode")
145 (string :tag
"Format"))))
147 (defgroup org-table-settings nil
148 "Settings for tables in Org mode."
149 :tag
"Org Table Settings"
152 (defcustom org-table-default-size
"5x2"
153 "The default size for newly created tables, Columns x Rows."
154 :group
'org-table-settings
157 (defcustom org-table-number-regexp
158 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
159 "Regular expression for recognizing numbers in table columns.
160 If a table column contains mostly numbers, it will be aligned to the
161 right. If not, it will be aligned to the left.
163 The default value of this option is a regular expression which allows
164 anything which looks remotely like a number as used in scientific
165 context. For example, all of the following will be considered a
167 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
169 Other options offered by the customize interface are more restrictive."
170 :group
'org-table-settings
172 (const :tag
"Positive Integers"
174 (const :tag
"Integers"
176 (const :tag
"Floating Point Numbers"
177 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
178 (const :tag
"Floating Point Number or Integer"
179 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
180 (const :tag
"Exponential, Floating point, Integer"
181 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
182 (const :tag
"Very General Number-Like, including hex and Calc radix"
183 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
184 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
185 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
186 (string :tag
"Regexp:")))
188 (defcustom org-table-number-fraction
0.5
189 "Fraction of numbers in a column required to make the column align right.
190 In a column all non-white fields are considered. If at least
191 this fraction of fields is matched by `org-table-number-regexp',
192 alignment to the right border applies."
193 :group
'org-table-settings
196 (defgroup org-table-editing nil
197 "Behavior of tables during editing in Org mode."
198 :tag
"Org Table Editing"
201 (defcustom org-table-automatic-realign t
202 "Non-nil means automatically re-align table when pressing TAB or RETURN.
203 When nil, aligning is only done with `\\[org-table-align]', or after column
205 :group
'org-table-editing
208 (defcustom org-table-auto-blank-field t
209 "Non-nil means automatically blank table field when starting to type into it.
210 This only happens when typing immediately after a field motion
211 command (TAB, S-TAB or RET).
212 Only relevant when `org-enable-table-editor' is equal to `optimized'."
213 :group
'org-table-editing
216 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
217 "Non-nil means automatically exit the follow mode.
218 When nil, the follow mode will stay on and be active in any table
219 the cursor enters. Since the table follow filed mode messes with the
220 window configuration, it is not recommended to set this variable to nil,
221 except maybe locally in a special file that has mostly tables with long
227 (defcustom org-table-fix-formulas-confirm nil
228 "Whether the user should confirm when Org fixes formulas."
229 :group
'org-table-editing
232 (const :tag
"with yes-or-no" yes-or-no-p
)
233 (const :tag
"with y-or-n" y-or-n-p
)
234 (const :tag
"no confirmation" nil
)))
235 (put 'org-table-fix-formulas-confirm
237 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
239 (defcustom org-table-tab-jumps-over-hlines t
240 "Non-nil means tab in the last column of a table with jump over a hline.
241 If a horizontal separator line is following the current line,
242 `org-table-next-field' can either create a new row before that line, or jump
243 over the line. When this option is nil, a new line will be created before
245 :group
'org-table-editing
248 (defgroup org-table-calculation nil
249 "Options concerning tables in Org mode."
250 :tag
"Org Table Calculation"
253 (defcustom org-table-use-standard-references
'from
254 "Non-nil means using table references like B3 instead of @3$2.
257 from accept as input, do not present for editing
258 t accept as input and present for editing"
259 :group
'org-table-calculation
261 (const :tag
"Never, don't even check user input for them" nil
)
262 (const :tag
"Always, both as user input, and when editing" t
)
263 (const :tag
"Convert user input, don't offer during editing" from
)))
265 (defcustom org-table-copy-increment t
266 "Non-nil means increment when copying current field with \
267 `\\[org-table-copy-down]'."
268 :group
'org-table-calculation
270 :package-version
'(Org .
"8.3")
272 (const :tag
"Use the difference between the current and the above fields" t
)
273 (integer :tag
"Use a number" 1)
274 (const :tag
"Don't increment the value when copying a field" nil
)))
276 (defcustom org-calc-default-modes
277 '(calc-internal-prec 12
278 calc-float-format
(float 8)
281 calc-symbolic-mode nil
282 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
283 calc-display-working-message t
285 "List with Calc mode settings for use in `calc-eval' for table formulas.
286 The list must contain alternating symbols (Calc modes variables and values).
287 Don't remove any of the default settings, just change the values. Org mode
288 relies on the variables to be present in the list."
289 :group
'org-table-calculation
292 (defcustom org-table-duration-custom-format
'hours
293 "Format for the output of calc computations like $1+$2;t.
294 The default value is `hours', and will output the results as a
295 number of hours. Other allowed values are `seconds', `minutes' and
296 `days', and the output will be a fraction of seconds, minutes or
298 :group
'org-table-calculation
300 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
301 (symbol :tag
"Minutes" 'minutes
)
302 (symbol :tag
"Hours " 'hours
)
303 (symbol :tag
"Days " 'days
)))
305 (defcustom org-table-formula-field-format
"%s"
306 "Format for fields which contain the result of a formula.
307 For example, using \"~%s~\" will display the result within tilde
308 characters. Beware that modifying the display can prevent the
309 field from being used in another formula."
310 :group
'org-table-settings
314 (defcustom org-table-formula-evaluate-inline t
315 "Non-nil means TAB and RET evaluate a formula in current table field.
316 If the current field starts with an equal sign, it is assumed to be a formula
317 which should be evaluated as described in the manual and in the documentation
318 string of the command `org-table-eval-formula'. This feature requires the
320 When this variable is nil, formula calculation is only available through
321 the command `\\[org-table-eval-formula]'."
322 :group
'org-table-calculation
325 (defcustom org-table-formula-use-constants t
326 "Non-nil means interpret constants in formulas in tables.
327 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
328 by the value given in `org-table-formula-constants', or by a value obtained
329 from the `constants.el' package."
330 :group
'org-table-calculation
333 (defcustom org-table-formula-constants nil
334 "Alist with constant names and values, for use in table formulas.
335 The car of each element is a name of a constant, without the `$' before it.
336 The cdr is the value as a string. For example, if you'd like to use the
337 speed of light in a formula, you would configure
339 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
341 and then use it in an equation like `$1*$c'.
343 Constants can also be defined on a per-file basis using a line like
345 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
346 :group
'org-table-calculation
348 (cons (string :tag
"name")
349 (string :tag
"value"))))
351 (defcustom org-table-allow-automatic-line-recalculation t
352 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
354 Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
355 are pressed in the line."
356 :group
'org-table-calculation
359 (defcustom org-table-relative-ref-may-cross-hline t
360 "Non-nil means relative formula references may cross hlines.
361 Here are the allowed values:
363 nil Relative references may not cross hlines. They will reference the
364 field next to the hline instead. Coming from below, the reference
365 will be to the field below the hline. Coming from above, it will be
367 t Relative references may cross hlines.
368 error An attempt to cross a hline will throw an error.
370 It is probably good to never set this variable to nil, for the sake of
371 portability of tables."
372 :group
'org-table-calculation
374 (const :tag
"Allow to cross" t
)
375 (const :tag
"Stick to hline" nil
)
376 (const :tag
"Error on attempt to cross" error
)))
378 (defcustom org-table-formula-create-columns nil
379 "Non-nil means that evaluation of a field formula can add new
380 columns if an out-of-bounds field is being set."
381 :group
'org-table-calculation
383 :package-version
'(Org .
"8.3")
385 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
386 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
387 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
388 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
390 (defgroup org-table-import-export nil
391 "Options concerning table import and export in Org mode."
392 :tag
"Org Table Import Export"
395 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
396 "Default export parameters for `org-table-export'.
397 These can be overridden for a specific table by setting the
398 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
399 radio tables for the different export transformations and
400 available parameters."
401 :group
'org-table-import-export
404 (defcustom org-table-convert-region-max-lines
999
405 "Max lines that `org-table-convert-region' will attempt to process.
407 The function can be slow on larger regions; this safety feature
408 prevents it from hanging emacs."
409 :group
'org-table-import-export
412 :package-version
'(Org .
"8.3"))
414 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
415 "Regexp matching a line marked for automatic recalculation.")
417 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
418 "Regexp matching a line marked for recalculation.")
420 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
421 "Regexp matching a line marked for calculation.")
423 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
424 "Regexp matching any line outside an Org table.")
426 (defvar org-table-last-highlighted-reference nil
)
428 (defvar org-table-formula-history nil
)
430 (defvar org-table-column-names nil
431 "Alist with column names, derived from the `!' line.
432 This variable is initialized with `org-table-analyze'.")
434 (defvar org-table-column-name-regexp nil
435 "Regular expression matching the current column names.
436 This variable is initialized with `org-table-analyze'.")
438 (defvar org-table-local-parameters nil
439 "Alist with parameter names, derived from the `$' line.
440 This variable is initialized with `org-table-analyze'.")
442 (defvar org-table-named-field-locations nil
443 "Alist with locations of named fields.
444 Associations follow the pattern (NAME LINE COLUMN) where
445 NAME is the name of the field as a string,
446 LINE is the number of lines from the beginning of the table,
447 COLUMN is the column of the field, as an integer.
448 This variable is initialized with `org-table-analyze'.")
450 (defvar org-table-current-line-types nil
451 "Table row types in current table.
452 This variable is initialized with `org-table-analyze'.")
454 (defvar org-table-current-begin-pos nil
455 "Current table begin position, as a marker.
456 This variable is initialized with `org-table-analyze'.")
458 (defvar org-table-current-ncol nil
459 "Number of columns in current table.
460 This variable is initialized with `org-table-analyze'.")
462 (defvar org-table-dlines nil
463 "Vector of data line line numbers in the current table.
464 Line numbers are counted from the beginning of the table. This
465 variable is initialized with `org-table-analyze'.")
467 (defvar org-table-hlines nil
468 "Vector of hline line numbers in the current table.
469 Line numbers are counted from the beginning of the table. This
470 variable is initialized with `org-table-analyze'.")
472 (defconst org-table-range-regexp
473 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
475 "Regular expression for matching ranges in formulas.")
477 (defconst org-table-range-regexp2
479 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
481 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
482 "Match a range for reference display.")
484 (defconst org-table-translate-regexp
485 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
486 "Match a reference that needs translation, for reference display.")
488 (defmacro org-table-save-field
(&rest body
)
489 "Save current field; execute BODY; restore field.
490 Field is restored even in case of abnormal exit."
491 (declare (debug (body)))
492 (org-with-gensyms (line column
)
493 `(let ((,line
(copy-marker (line-beginning-position)))
494 (,column
(org-table-current-column)))
498 (org-table-goto-column ,column
)
499 (set-marker ,line nil
)))))
502 (defun org-table-create-with-table.el
()
503 "Use the table.el package to insert a new table.
504 If there is already a table at point, convert between Org tables
505 and table.el tables."
510 (if (y-or-n-p "Convert table to Org table? ")
511 (org-table-convert)))
513 (when (y-or-n-p "Convert table to table.el table? ")
515 (org-table-convert)))
516 (t (call-interactively 'table-insert
))))
519 (defun org-table-create-or-convert-from-region (arg)
520 "Convert region to table, or create an empty table.
521 If there is an active region, convert it to a table, using the function
522 `org-table-convert-region'. See the documentation of that function
523 to learn how the prefix argument is interpreted to determine the field
525 If there is no such region, create an empty table with `org-table-create'."
527 (if (org-region-active-p)
528 (org-table-convert-region (region-beginning) (region-end) arg
)
529 (org-table-create arg
)))
532 (defun org-table-create (&optional size
)
533 "Query for a size and insert a table skeleton.
534 SIZE is a string Columns x Rows like for example \"3x2\"."
537 (setq size
(read-string
538 (concat "Table size Columns x Rows [e.g. "
539 org-table-default-size
"]: ")
540 "" nil org-table-default-size
)))
543 (indent (make-string (current-column) ?\
))
544 (split (org-split-string size
" *x *"))
545 (rows (string-to-number (nth 1 split
)))
546 (columns (string-to-number (car split
)))
547 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
549 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
550 (point-at-bol) (point)))
551 (beginning-of-line 1)
553 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
554 (dotimes (_ rows
) (insert line
))
557 ;; Insert a hline after the first row.
565 (defun org-table-convert-region (beg0 end0
&optional separator
)
566 "Convert region to a table.
568 The region goes from BEG0 to END0, but these borders will be moved
569 slightly, to make sure a beginning of line in the first line is included.
571 SEPARATOR specifies the field separator in the lines. It can have the
574 (4) Use the comma as a field separator
575 (16) Use a TAB as field separator
576 (64) Prompt for a regular expression as field separator
577 integer When a number, use that many spaces, or a TAB, as field separator
578 regexp When a regular expression, use it to match the separator
579 nil When nil, the command tries to be smart and figure out the
580 separator in the following way:
581 - when each line contains a TAB, assume TAB-separated material
582 - when each line contains a comma, assume CSV material
583 - else, assume one or more SPACE characters as separator."
585 (let* ((beg (min beg0 end0
))
586 (end (max beg0 end0
))
588 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
589 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
590 org-table-convert-region-max-lines
)
591 (if (equal separator
'(64))
592 (setq separator
(read-regexp "Regexp for field separator")))
594 (beginning-of-line 1)
595 (setq beg
(point-marker))
597 (if (bolp) (backward-char 1) (end-of-line 1))
598 (setq end
(point-marker))
599 ;; Get the right field separator
604 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
605 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
608 (if (equal separator
'(4))
609 (while (< (point) end
)
610 ;; parse the csv stuff
612 ((looking-at "^") (insert "| "))
613 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
614 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
615 (replace-match "\\1")
616 (if (looking-at "\"") (insert "\"")))
617 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
618 ((looking-at "[ \t]*,") (replace-match " | "))
619 (t (beginning-of-line 2))))
621 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
622 ((equal separator
'(16)) "^\\|\t")
623 ((integerp separator
)
625 (user-error "Number of spaces in separator must be >= 1")
626 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
628 (format "^ *\\|%s" separator
))
629 (t (error "This should not happen"))))
630 (while (re-search-forward re end t
)
631 (replace-match "| " t t
)))
636 (defun org-table-import (file arg
)
637 "Import FILE as a table.
638 The file is assumed to be tab-separated. Such files can be produced by most
639 spreadsheet and database applications. If no tabs (at least one per line)
640 are found, lines will be split on whitespace into fields."
642 (or (bolp) (newline))
645 (insert-file-contents file
)
646 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
650 (defun org-table-export (&optional file format
)
651 "Export table to a file, with configurable format.
652 Such a file can be imported into usual spreadsheet programs.
654 FILE can be the output file name. If not given, it will be taken
655 from a TABLE_EXPORT_FILE property in the current entry or higher
656 up in the hierarchy, or the user will be prompted for a file
657 name. FORMAT can be an export format, of the same kind as it
658 used when `orgtbl-mode' sends a table in a different format.
660 The command suggests a format depending on TABLE_EXPORT_FORMAT,
661 whether it is set locally or up in the hierarchy, then on the
662 extension of the given file name, and finally on the variable
663 `org-table-export-default-format'."
665 (unless (org-at-table-p) (user-error "No table at point"))
666 (org-table-align) ; Make sure we have everything we need.
667 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
669 (setq file
(read-file-name "Export table to: "))
670 (unless (or (not (file-exists-p file
))
671 (y-or-n-p (format "Overwrite file %s? " file
)))
672 (user-error "File not written")))
673 (when (file-directory-p file
)
674 (user-error "This is a directory path, not a file"))
675 (when (and (buffer-file-name (buffer-base-buffer))
678 (file-truename (buffer-file-name (buffer-base-buffer)))))
679 (user-error "Please specify a file name that is different from current"))
680 (let ((fileext (concat (file-name-extension file
) "$"))
681 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
683 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
684 "orgtbl-to-html" "orgtbl-to-generic"
685 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
686 "orgtbl-to-unicode"))
688 (replace-regexp-in-string
690 (replace-regexp-in-string
695 (and (string-match-p fileext f
) f
))
697 org-table-export-default-format
)
701 "Format: " formats nil nil deffmt-readable
))))
702 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
703 (let ((transform (intern (match-string 1 format
)))
704 (params (and (match-end 2)
705 (read (concat "(" (match-string 2 format
) ")"))))
706 (table (org-table-to-lisp
707 (buffer-substring-no-properties
708 (org-table-begin) (org-table-end)))))
709 (unless (fboundp transform
)
710 (user-error "No such transformation function %s" transform
))
712 (with-current-buffer (find-file-noselect file
)
713 (setq buf
(current-buffer))
716 (insert (funcall transform table params
) "\n")
719 (message "Export done."))
720 (user-error "TABLE_EXPORT_FORMAT invalid")))))
722 (defvar org-table-aligned-begin-marker
(make-marker)
723 "Marker at the beginning of the table last aligned.
724 Used to check if cursor still is in that table, to minimize realignment.")
725 (defvar org-table-aligned-end-marker
(make-marker)
726 "Marker at the end of the table last aligned.
727 Used to check if cursor still is in that table, to minimize realignment.")
728 (defvar org-table-last-alignment nil
729 "List of flags for flushright alignment, from the last re-alignment.
730 This is being used to correctly align a single field after TAB or RET.")
731 (defvar org-table-last-column-widths nil
732 "List of max width of fields in each column.
733 This is being used to correctly align a single field after TAB or RET.")
734 (defvar-local org-table-formula-debug nil
735 "Non-nil means debug table formulas.
736 When nil, simply write \"#ERROR\" in corrupted fields.")
737 (defvar-local org-table-overlay-coordinates nil
738 "Overlay coordinates after each align of a table.")
740 (defvar org-last-recalc-line nil
)
741 (defvar org-table-do-narrow t
) ; for dynamic scoping
742 (defconst org-narrow-column-arrow
"=>"
743 "Used as display property in narrowed table columns.")
746 (defun org-table-align ()
747 "Align the table at point by aligning all vertical bars."
749 (let* ((beg (org-table-begin))
750 (end (copy-marker (org-table-end))))
751 (org-table-save-field
752 ;; Make sure invisible characters in the table are at the right
753 ;; place since column widths take them into account.
754 (font-lock-fontify-region beg end
)
755 (move-marker org-table-aligned-begin-marker beg
)
756 (move-marker org-table-aligned-end-marker end
)
758 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
759 ;; Table's rows. Separators are replaced by nil. Trailing
760 ;; spaces are also removed.
761 (lines (mapcar (lambda (l)
762 (and (not (string-match-p "\\`[ \t]*|-" l
))
763 (let ((l (org-trim l
)))
764 (remove-text-properties
765 0 (length l
) '(display t org-cwidth t
) l
)
767 (org-split-string (buffer-substring beg end
) "\n")))
768 ;; Get the data fields by splitting the lines.
769 (fields (mapcar (lambda (l) (org-split-string l
" *| *"))
771 ;; Compute number of fields in the longest line. If the
772 ;; table contains no field, create a default table.
773 (maxfields (if fields
(apply #'max
(mapcar #'length fields
))
774 (kill-region beg end
)
775 (org-table-create org-table-default-size
)
776 (user-error "Empty table - created default table")))
777 ;; A list of empty strings to fill any short rows on output.
778 (emptycells (make-list maxfields
""))
780 ;; Check for special formatting.
781 (dotimes (i maxfields
)
782 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) fields
))
784 ;; Look for an explicit width or alignment.
785 (when (save-excursion
786 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t
)
787 (and org-table-do-narrow
789 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t
))))
791 (dolist (cell column
)
792 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell
)
793 (when (match-end 1) (setq falign
(match-string 1 cell
)))
794 (when (and org-table-do-narrow
(match-end 2))
795 (setq fmax
(string-to-number (match-string 2 cell
))))
796 (when (or falign fmax
) (throw :exit nil
)))))
797 ;; Find fields that are wider than FMAX, and shorten them.
800 (when (> (org-string-width x
) fmax
)
804 "Clipped table field, use `\\[org-table-edit-field]' to \
805 edit. Full value is:\n"
806 (substring-no-properties x
)))
809 (or (string-match org-bracket-link-regexp x
)
814 "Cannot narrow field starting with wide link \"%s\""
816 (if (= (org-string-width x
) l
) (setq f2 f1
)
818 (while (< (org-string-width (substring x
0 f2
)) f1
)
820 (add-text-properties f2 l
(list 'org-cwidth t
) x
)
822 (if (>= (string-width (substring x
(1- f2
) f2
)) 2) (1- f2
)
825 (list 'display org-narrow-column-arrow
)
827 ;; Get the maximum width for each column
828 (push (apply #'max
(or fmax
1) 1 (mapcar #'org-string-width column
))
830 ;; Get the fraction of numbers among non-empty cells to
831 ;; decide about alignment of the column.
832 (if falign
(push (equal (downcase falign
) "r") typenums
)
839 (if (string-match-p org-table-number-regexp x
)
843 (push (>= frac org-table-number-fraction
) typenums
)))))
844 (setq lengths
(nreverse lengths
))
845 (setq typenums
(nreverse typenums
))
846 ;; Store alignment of this table, for later editing of single
848 (setq org-table-last-alignment typenums
)
849 (setq org-table-last-column-widths lengths
)
850 ;; With invisible characters, `format' does not get the field
851 ;; width right So we need to make these fields wide by hand.
852 ;; Invisible characters may be introduced by fontified links,
853 ;; emphasis, macros or sub/superscripts.
854 (when (or (text-property-any beg end
'invisible
'org-link
)
855 (text-property-any beg end
'invisible t
))
856 (dotimes (i maxfields
)
857 (let ((len (nth i lengths
)))
858 (dotimes (j (length fields
))
859 (let* ((c (nthcdr i
(nth j fields
)))
863 (let ((l (length cell
)))
864 (or (text-property-any 0 l
'invisible
'org-link cell
)
865 (text-property-any beg end
'invisible t
)))
866 (< (org-string-width cell
) len
))
867 (let ((s (make-string (- len
(org-string-width cell
)) ?\s
)))
868 (setcar c
(if (nth i typenums
) (concat s cell
)
869 (concat cell s
))))))))))
871 ;; Compute the formats needed for output of the table.
872 (let ((hfmt (concat indent
"|"))
873 (rfmt (concat indent
"|"))
876 (dolist (l lengths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
877 (let ((ty (if (pop typenums
) "" "-"))) ; Flush numbers right.
878 (setq rfmt
(concat rfmt
(format rfmt1 ty l
)))
879 (setq hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
))))))
880 ;; Replace modified lines only. Check not only contents, but
881 ;; also columns' width.
884 (if l
(apply #'format rfmt
(append (pop fields
) emptycells
))
886 (previous (buffer-substring (point) (line-end-position))))
887 (if (and (equal previous line
)
891 (setq a
(next-single-property-change
892 a
'org-cwidth previous
))
893 (setq b
(next-single-property-change
894 b
'org-cwidth line
)))
899 (delete-region (point) (line-beginning-position 2))))))
900 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
901 (goto-char org-table-aligned-begin-marker
)
902 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
904 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
905 (setq org-table-may-need-update nil
)))))
908 (defun org-table-begin (&optional table-type
)
909 "Find the beginning of the table and return its position.
910 With a non-nil optional argument TABLE-TYPE, return the beginning
911 of a table.el-type table. This function assumes point is on
914 (org-element-property :post-affiliated
(org-element-at-point)))
916 (and (re-search-backward org-table-border-regexp nil t
)
917 (line-beginning-position 2))))
921 (defun org-table-end (&optional table-type
)
922 "Find the end of the table and return its position.
923 With a non-nil optional argument TABLE-TYPE, return the end of
924 a table.el-type table. This function assumes point is on
928 (goto-char (org-element-property :end
(org-element-at-point)))
929 (skip-chars-backward " \t\n")
930 (line-beginning-position 2))
931 ((re-search-forward org-table-border-regexp nil t
)
933 ;; When the line right after the table is the last line in
934 ;; the buffer with trailing spaces but no final newline
935 ;; character, be sure to catch the correct ending at its
936 ;; beginning. In any other case, ending is expected to be
938 (t (goto-char (point-max))
939 (skip-chars-backward " \t")
940 (if (bolp) (point) (line-end-position))))))
943 (defun org-table-justify-field-maybe (&optional new
)
944 "Justify the current field, text to left, number to right.
945 Optional argument NEW may specify text to replace the current field content."
947 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
948 ((org-at-table-hline-p))
950 (or (not (eq (marker-buffer org-table-aligned-begin-marker
)
952 (< (point) org-table-aligned-begin-marker
)
953 (>= (point) org-table-aligned-end-marker
)))
954 ;; This is not the same table, force a full re-align.
955 (setq org-table-may-need-update t
))
957 ;; Realign the current field, based on previous full realign.
959 (col (org-table-current-column)))
961 (skip-chars-backward "^|")
962 (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
963 (setq org-table-may-need-update t
)
964 (let* ((numbers?
(nth (1- col
) org-table-last-alignment
))
965 (cell (match-string 0))
966 (field (match-string 1))
967 (len (max 1 (- (org-string-width cell
) 3)))
968 (properly-closed?
(/= (match-beginning 2) (match-end 2)))
969 (fmt (format (if numbers?
" %%%ds %s" " %%-%ds %s")
971 (if properly-closed?
"|"
972 (setq org-table-may-need-update t
)
975 (cond ((not new
) (format fmt field
))
976 ((<= (org-string-width new
) len
) (format fmt new
))
978 (setq org-table-may-need-update t
)
979 (format " %s |" new
)))))
980 (unless (equal new-cell cell
)
981 (let (org-table-may-need-update)
982 (replace-match new-cell t t
)))
983 (goto-char pos
))))))))
986 (defun org-table-next-field ()
987 "Go to the next field in the current table, creating new lines as needed.
988 Before doing so, re-align the table if necessary."
990 (org-table-maybe-eval-formula)
991 (org-table-maybe-recalculate-line)
992 (if (and org-table-automatic-realign
993 org-table-may-need-update
)
995 (let ((end (org-table-end)))
996 (if (org-at-table-hline-p)
1000 (re-search-forward "|" end
)
1001 (if (looking-at "[ \t]*$")
1002 (re-search-forward "|" end
))
1003 (if (and (looking-at "-")
1004 org-table-tab-jumps-over-hlines
1005 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1006 (goto-char (match-beginning 1)))
1007 (if (looking-at "-")
1009 (beginning-of-line 0)
1010 (org-table-insert-row 'below
))
1011 (if (looking-at " ") (forward-char 1))))
1013 (org-table-insert-row 'below
)))))
1016 (defun org-table-previous-field ()
1017 "Go to the previous field in the table.
1018 Before doing so, re-align the table if necessary."
1020 (org-table-justify-field-maybe)
1021 (org-table-maybe-recalculate-line)
1022 (if (and org-table-automatic-realign
1023 org-table-may-need-update
)
1025 (if (org-at-table-hline-p)
1029 (re-search-backward "|" (org-table-begin))
1030 (re-search-backward "|" (org-table-begin)))
1031 (error (user-error "Cannot move to previous table field")))
1032 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1033 (re-search-backward "|" (org-table-begin)))
1034 (if (looking-at "| ?")
1035 (goto-char (match-end 0))))
1037 (defun org-table-beginning-of-field (&optional n
)
1038 "Move to the beginning of the current table field.
1039 If already at or before the beginning, move to the beginning of the
1041 With numeric argument N, move N-1 fields backward first."
1043 (let ((pos (point)))
1046 (org-table-previous-field))
1047 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1048 (user-error "No more table fields before the current")
1049 (goto-char (match-end 0))
1050 (and (looking-at " ") (forward-char 1)))
1051 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1053 (defun org-table-end-of-field (&optional n
)
1054 "Move to the end of the current table field.
1055 If already at or after the end, move to the end of the next table field.
1056 With numeric argument N, move N-1 fields forward first."
1058 (let ((pos (point)))
1061 (org-table-next-field))
1062 (when (re-search-forward "|" (point-at-eol 1) t
)
1064 (skip-chars-backward " ")
1065 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1067 (if (<= (point) pos
) (org-table-end-of-field 2))))
1070 (defun org-table-next-row ()
1071 "Go to the next row (same column) in the current table.
1072 Before doing so, re-align the table if necessary."
1074 (org-table-maybe-eval-formula)
1075 (org-table-maybe-recalculate-line)
1076 (if (or (looking-at "[ \t]*$")
1077 (save-excursion (skip-chars-backward " \t") (bolp)))
1079 (if (and org-table-automatic-realign
1080 org-table-may-need-update
)
1082 (let ((col (org-table-current-column)))
1083 (beginning-of-line 2)
1084 (if (or (not (org-at-table-p))
1085 (org-at-table-hline-p))
1087 (beginning-of-line 0)
1088 (org-table-insert-row 'below
)))
1089 (org-table-goto-column col
)
1090 (skip-chars-backward "^|\n\r")
1091 (if (looking-at " ") (forward-char 1)))))
1094 (defun org-table-copy-down (n)
1095 "Copy the value of the current field one row below.
1097 If the field at the cursor is empty, copy the content of the
1098 nearest non-empty field above. With argument N, use the Nth
1101 If the current field is not empty, it is copied down to the next
1102 row, and the cursor is moved with it. Therefore, repeating this
1103 command causes the column to be filled row-by-row.
1105 If the variable `org-table-copy-increment' is non-nil and the
1106 field is an integer or a timestamp, it will be incremented while
1107 copying. By default, increment by the difference between the
1108 value in the current field and the one in the field above. To
1109 increment using a fixed integer, set `org-table-copy-increment'
1110 to a number. In the case of a timestamp, increment by days."
1112 (let* ((colpos (org-table-current-column))
1113 (col (current-column))
1114 (field (save-excursion (org-table-get-field)))
1115 (field-up (or (save-excursion
1116 (org-table-get (1- (org-table-current-line))
1117 (org-table-current-column))) ""))
1118 (non-empty (string-match "[^ \t]" field
))
1119 (non-empty-up (string-match "[^ \t]" field-up
))
1120 (beg (org-table-begin))
1123 (org-table-check-inside-data-field)
1128 (while (progn (beginning-of-line 1)
1129 (re-search-backward org-table-dataline-regexp
1131 (org-table-goto-column colpos t
)
1132 (if (and (looking-at
1133 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1134 (<= (setq n
(1- n
)) 0))
1135 (throw 'exit
(match-string 1))))))
1138 (while (progn (beginning-of-line 1)
1139 (re-search-backward org-table-dataline-regexp
1141 (org-table-goto-column colpos t
)
1142 (if (and (looking-at
1143 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1144 (<= (setq n
(1- n
)) 0))
1145 (throw 'exit
(match-string 1))))))
1146 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1147 ;; Above field was not empty, go down to the next row
1148 (setq txt
(org-trim field
))
1149 (org-table-next-row)
1150 (org-table-blank-field))
1151 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1153 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1154 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1155 (string-match org-ts-regexp3 txt
))
1156 (- (org-time-string-to-absolute txt
)
1157 (org-time-string-to-absolute txt-up
)))
1158 ((string-match org-ts-regexp3 txt
) 1)
1159 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1160 (- (string-to-number txt
)
1161 (string-to-number (match-string 0 txt-up
))))
1165 (user-error "No non-empty field found")
1166 (if (and org-table-copy-increment
1167 (not (equal orig-n
0))
1168 (string-match-p "^[-+^/*0-9eE.]+$" txt
)
1169 (< (string-to-number txt
) 100000000))
1170 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1172 (org-move-to-column col
)
1173 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1174 (org-timestamp-up-day inc
)
1175 (org-table-maybe-recalculate-line))
1177 (org-move-to-column col
))))
1179 (defun org-table-check-inside-data-field (&optional noerror
)
1180 "Is point inside a table data field?
1181 I.e. not on a hline or before the first or after the last column?
1182 This actually throws an error, so it aborts the current command."
1183 (cond ((and (org-at-table-p)
1184 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1185 (not (org-at-table-hline-p))
1186 (not (looking-at "[ \t]*$"))))
1188 (t (user-error "Not in table data field"))))
1190 (defvar org-table-clip nil
1191 "Clipboard for table regions.")
1193 (defun org-table-get (line column
)
1194 "Get the field in table line LINE, column COLUMN.
1195 If LINE is larger than the number of data lines in the table, the function
1196 returns nil. However, if COLUMN is too large, we will simply return an
1198 If LINE is nil, use the current line.
1199 If COLUMN is nil, use the current column."
1200 (setq column
(or column
(org-table-current-column)))
1202 (and (or (not line
) (org-table-goto-line line
))
1203 (org-trim (org-table-get-field column
)))))
1205 (defun org-table-put (line column value
&optional align
)
1206 "Put VALUE into line LINE, column COLUMN.
1207 When ALIGN is set, also realign the table."
1208 (setq column
(or column
(org-table-current-column)))
1209 (prog1 (save-excursion
1210 (and (or (not line
) (org-table-goto-line line
))
1211 (progn (org-table-goto-column column nil
'force
) t
)
1212 (org-table-get-field column value
)))
1213 (and align
(org-table-align))))
1215 (defun org-table-current-line ()
1216 "Return the index of the current data line."
1217 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1219 (goto-char (org-table-begin))
1220 (while (and (re-search-forward org-table-dataline-regexp end t
)
1222 (< (point-at-eol) pos
))))
1225 (defun org-table-goto-line (N)
1226 "Go to the Nth data line in the current table.
1227 Return t when the line exists, nil if it does not exist."
1228 (goto-char (org-table-begin))
1229 (let ((end (org-table-end)) (cnt 0))
1230 (while (and (re-search-forward org-table-dataline-regexp end t
)
1231 (< (setq cnt
(1+ cnt
)) N
)))
1235 (defun org-table-blank-field ()
1236 "Blank the current table field or active region."
1238 (org-table-check-inside-data-field)
1239 (if (and (called-interactively-p 'any
) (org-region-active-p))
1240 (let (org-table-clip)
1241 (org-table-cut-region (region-beginning) (region-end)))
1242 (skip-chars-backward "^|")
1244 (if (looking-at "|[^|\n]+")
1245 (let* ((pos (match-beginning 0))
1246 (match (match-string 0))
1247 (len (org-string-width match
)))
1248 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1249 (goto-char (+ 2 pos
))
1250 (substring match
1)))))
1252 (defun org-table-get-field (&optional n replace
)
1253 "Return the value of the field in column N of current row.
1254 N defaults to current field.
1255 If REPLACE is a string, replace field with this value. The return value
1256 is always the old value."
1257 (and n
(org-table-goto-column n
))
1258 (skip-chars-backward "^|\n")
1260 (if (looking-at "|[^|\r\n]*")
1261 (let* ((pos (match-beginning 0))
1262 (val (buffer-substring (1+ pos
) (match-end 0))))
1264 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1266 (goto-char (min (point-at-eol) (+ 2 pos
)))
1268 (forward-char 1) ""))
1271 (defun org-table-field-info (_arg)
1272 "Show info about the current field, and highlight any reference at point."
1274 (unless (org-at-table-p) (user-error "Not at a table"))
1277 (let* ((pos (point))
1278 (col (org-table-current-column))
1279 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1280 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1281 (line-beginning-position))
1283 org-table-named-field-locations
)))
1284 (eql (org-table-expand-lhs-ranges
1287 (cons (org-table-formula-handle-first/last-rc
(car e
))
1289 (org-table-get-stored-formulas))))
1290 (dline (org-table-current-dline))
1291 (ref (format "@%d$%d" dline col
))
1292 (ref1 (org-table-convert-refs-to-an ref
))
1293 ;; Prioritize field formulas over column formulas.
1294 (fequation (or (assoc name eql
) (assoc ref eql
)))
1295 (cequation (assoc (format "$%d" col
) eql
))
1296 (eqn (or fequation cequation
)))
1297 (let ((p (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))))
1298 (when p
(setq eqn p
)))
1300 (ignore-errors (org-table-show-reference 'local
))
1301 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1303 (if cname
(concat " or $" cname
) "")
1305 (if name
(concat " or $" name
) "")
1306 ;; FIXME: formula info not correct if special table line
1308 (concat ", formula: "
1309 (org-table-formula-to-user
1311 (if (or (string-prefix-p "$" (car eqn
))
1312 (string-prefix-p "@" (car eqn
)))
1315 (car eqn
) "=" (cdr eqn
))))
1318 (defun org-table-current-column ()
1319 "Find out which column we are in."
1321 (let ((column 0) (pos (point)))
1323 (while (search-forward "|" pos t
) (cl-incf column
))
1326 (defun org-table-current-dline ()
1327 "Find out what table data line we are in.
1328 Only data lines count for this."
1332 (goto-char (org-table-begin))
1333 (while (<= (point) pos
)
1334 (when (looking-at org-table-dataline-regexp
) (cl-incf c
))
1339 (defun org-table-goto-column (n &optional on-delim force
)
1340 "Move the cursor to the Nth column in the current table line.
1341 With optional argument ON-DELIM, stop with point before the left delimiter
1343 If there are less than N fields, just go to after the last delimiter.
1344 However, when FORCE is non-nil, create new columns if necessary."
1346 (beginning-of-line 1)
1348 (while (and (> (setq n
(1- n
)) -
1)
1349 (or (search-forward "|" (point-at-eol) t
)
1351 (progn (end-of-line 1)
1352 (skip-chars-backward "^|")
1355 (when (and force
(not (looking-at ".*|")))
1356 (save-excursion (end-of-line 1) (insert " | ")))
1359 (if (looking-at " ") (forward-char 1)))))
1362 (defun org-table-insert-column ()
1363 "Insert a new column into the table."
1365 (unless (org-at-table-p) (user-error "Not at a table"))
1366 (org-table-find-dataline)
1367 (let* ((col (max 1 (org-table-current-column)))
1368 (beg (org-table-begin))
1369 (end (copy-marker (org-table-end))))
1370 (org-table-save-field
1372 (while (< (point) end
)
1373 (unless (org-at-table-hline-p)
1374 (org-table-goto-column col t
)
1377 (set-marker end nil
)
1379 (when (or (not org-table-fix-formulas-confirm
)
1380 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1381 (org-table-fix-formulas "$" nil
(1- col
) 1)
1382 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1384 (defun org-table-find-dataline ()
1385 "Find a data line in the current table, which is needed for column commands."
1386 (if (and (org-at-table-p)
1387 (not (org-at-table-hline-p)))
1389 (let ((col (current-column))
1390 (end (org-table-end)))
1391 (org-move-to-column col
)
1392 (while (and (< (point) end
)
1393 (or (not (= (current-column) col
))
1394 (org-at-table-hline-p)))
1395 (beginning-of-line 2)
1396 (org-move-to-column col
))
1397 (if (and (org-at-table-p)
1398 (not (org-at-table-hline-p)))
1401 "Please position cursor in a data line for column operations")))))
1403 (defun org-table-line-to-dline (line &optional above
)
1404 "Turn a buffer line number into a data line number.
1406 If there is no data line in this line, return nil.
1408 If there is no matching dline (most likely the reference was
1409 a hline), the first dline below it is used. When ABOVE is
1410 non-nil, the one above is used."
1412 (max (1- (length org-table-dlines
))))
1413 (cond ((or (> (aref org-table-dlines min
) line
)
1414 (< (aref org-table-dlines max
) line
))
1416 ((= (aref org-table-dlines max
) line
) max
)
1418 (while (> (- max min
) 1)
1419 (let* ((mean (/ (+ max min
) 2))
1420 (v (aref org-table-dlines mean
)))
1421 (cond ((= v line
) (throw 'exit mean
))
1422 ((> v line
) (setq max mean
))
1423 (t (setq min mean
)))))
1424 (if above min max
))))))
1427 (defun org-table-delete-column ()
1428 "Delete a column from the table."
1430 (unless (org-at-table-p) (user-error "Not at a table"))
1431 (org-table-find-dataline)
1432 (org-table-check-inside-data-field)
1433 (let ((col (org-table-current-column))
1434 (beg (org-table-begin))
1435 (end (copy-marker (org-table-end))))
1436 (org-table-save-field
1438 (while (< (point) end
)
1439 (if (org-at-table-hline-p)
1441 (org-table-goto-column col t
)
1442 (and (looking-at "|[^|\n]+|")
1443 (replace-match "|")))
1445 (set-marker end nil
)
1446 (org-table-goto-column (max 1 (1- col
)))
1448 (when (or (not org-table-fix-formulas-confirm
)
1449 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1450 (org-table-fix-formulas
1451 "$" (list (cons (number-to-string col
) "INVALID")) col -
1 col
)
1452 (org-table-fix-formulas
1453 "$LR" (list (cons (number-to-string col
) "INVALID")) col -
1 col
))))
1456 (defun org-table-move-column-right ()
1457 "Move column to the right."
1459 (org-table-move-column nil
))
1461 (defun org-table-move-column-left ()
1462 "Move column to the left."
1464 (org-table-move-column 'left
))
1467 (defun org-table-move-column (&optional left
)
1468 "Move the current column to the right. With arg LEFT, move to the left."
1470 (unless (org-at-table-p) (user-error "Not at a table"))
1471 (org-table-find-dataline)
1472 (org-table-check-inside-data-field)
1473 (let* ((col (org-table-current-column))
1474 (col1 (if left
(1- col
) col
))
1475 (colpos (if left
(1- col
) (1+ col
)))
1476 (beg (org-table-begin))
1477 (end (copy-marker (org-table-end))))
1478 (when (and left
(= col
1))
1479 (user-error "Cannot move column further left"))
1480 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1481 (user-error "Cannot move column further right"))
1482 (org-table-save-field
1484 (while (< (point) end
)
1485 (unless (org-at-table-hline-p)
1486 (org-table-goto-column col1 t
)
1487 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1488 (replace-match "|\\2|\\1|")))
1490 (set-marker end nil
)
1491 (org-table-goto-column colpos
)
1493 (when (or (not org-table-fix-formulas-confirm
)
1494 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1495 (org-table-fix-formulas
1496 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1497 (cons (number-to-string colpos
) (number-to-string col
))))
1498 (org-table-fix-formulas
1499 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1500 (cons (number-to-string colpos
) (number-to-string col
)))))))
1503 (defun org-table-move-row-down ()
1504 "Move table row down."
1506 (org-table-move-row nil
))
1508 (defun org-table-move-row-up ()
1509 "Move table row up."
1511 (org-table-move-row 'up
))
1514 (defun org-table-move-row (&optional up
)
1515 "Move the current table line down. With arg UP, move it up."
1517 (let* ((col (current-column))
1519 (hline1p (save-excursion (beginning-of-line 1)
1520 (looking-at org-table-hline-regexp
)))
1521 (dline1 (org-table-current-dline))
1522 (dline2 (+ dline1
(if up -
1 1)))
1525 (beginning-of-line tonew
)
1526 (unless (org-at-table-p)
1528 (user-error "Cannot move row further"))
1529 (setq hline2p
(looking-at org-table-hline-regexp
))
1531 (beginning-of-line 1)
1533 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1534 (delete-region (point) (1+ (point-at-eol)))
1535 (beginning-of-line tonew
)
1537 (beginning-of-line 0)
1538 (org-move-to-column col
)
1539 (unless (or hline1p hline2p
1540 (not (or (not org-table-fix-formulas-confirm
)
1541 (funcall org-table-fix-formulas-confirm
1542 "Fix formulas? "))))
1543 (org-table-fix-formulas
1544 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1545 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1548 (defun org-table-insert-row (&optional arg
)
1549 "Insert a new row above the current line into the table.
1550 With prefix ARG, insert below the current line."
1552 (unless (org-at-table-p) (user-error "Not at a table"))
1553 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1554 (new (org-table-clean-line line
)))
1555 ;; Fix the first field if necessary
1556 (if (string-match "^[ \t]*| *[#$] *|" line
)
1557 (setq new
(replace-match (match-string 0 line
) t t new
)))
1558 (beginning-of-line (if arg
2 1))
1559 ;; Buffer may not end of a newline character, so ensure
1560 ;; (beginning-of-line 2) moves point to a new line.
1561 (unless (bolp) (insert "\n"))
1562 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1563 (beginning-of-line 0)
1564 (re-search-forward "| ?" (line-end-position) t
)
1565 (when (or org-table-may-need-update org-table-overlay-coordinates
)
1567 (when (or (not org-table-fix-formulas-confirm
)
1568 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1569 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1572 (defun org-table-insert-hline (&optional above
)
1573 "Insert a horizontal-line below the current line into the table.
1574 With prefix ABOVE, insert above the current line."
1576 (if (not (org-at-table-p))
1577 (user-error "Not at a table"))
1578 (when (eobp) (insert "\n") (backward-char 1))
1579 (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
1581 (let ((line (org-table-clean-line
1582 (buffer-substring (point-at-bol) (point-at-eol))))
1583 (col (current-column)))
1584 (while (string-match "|\\( +\\)|" line
)
1585 (setq line
(replace-match
1586 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1587 ?-
) "|") t t line
)))
1588 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1589 (beginning-of-line (if above
1 2))
1591 (beginning-of-line (if above
1 -
1))
1592 (org-move-to-column col
)
1593 (and org-table-overlay-coordinates
(org-table-align))))
1596 (defun org-table-hline-and-move (&optional same-column
)
1597 "Insert a hline and move to the row below that line."
1599 (let ((col (org-table-current-column)))
1600 (org-table-maybe-eval-formula)
1601 (org-table-maybe-recalculate-line)
1602 (org-table-insert-hline)
1604 (if (looking-at "\n[ \t]*|-")
1605 (progn (insert "\n|") (org-table-align))
1606 (org-table-next-field))
1607 (if same-column
(org-table-goto-column col
))))
1609 (defun org-table-clean-line (s)
1610 "Convert a table line S into a string with only \"|\" and space.
1611 In particular, this does handle wide and invisible characters."
1612 (if (string-match "^[ \t]*|-" s
)
1613 ;; It's a hline, just map the characters
1614 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1615 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1616 (setq s
(replace-match
1617 (concat "|" (make-string (org-string-width (match-string 1 s
))
1623 (defun org-table-kill-row ()
1624 "Delete the current row or horizontal line from the table."
1626 (if (not (org-at-table-p))
1627 (user-error "Not at a table"))
1628 (let ((col (current-column))
1629 (dline (org-table-current-dline)))
1630 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1631 (if (not (org-at-table-p)) (beginning-of-line 0))
1632 (org-move-to-column col
)
1633 (when (or (not org-table-fix-formulas-confirm
)
1634 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1635 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1639 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func
)
1640 "Sort table lines according to the column at point.
1642 The position of point indicates the column to be used for
1643 sorting, and the range of lines is the range between the nearest
1644 horizontal separator lines, or the entire table of no such lines
1645 exist. If point is before the first column, you will be prompted
1646 for the sorting column. If there is an active region, the mark
1647 specifies the first line and the sorting column, while point
1648 should be in the last line to be included into the sorting.
1650 The command then prompts for the sorting type which can be
1651 alphabetically, numerically, or by time (as given in a time stamp
1652 in the field, or as a HH:MM value). Sorting in reverse order is
1655 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1657 If SORTING-TYPE is specified when this function is called from a Lisp
1658 program, no prompting will take place. SORTING-TYPE must be a character,
1659 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1660 sorting should be done in reverse order.
1662 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1663 a function to be called to extract the key. It must return either
1664 a string or a number that should serve as the sorting key for that
1665 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1666 is specified interactively, the comparison will be either a string or
1667 numeric compare based on the type of the first key in the table."
1669 (when (org-region-active-p) (goto-char (region-beginning)))
1670 ;; Point must be either within a field or before a data line.
1672 (skip-chars-backward " \t")
1673 (when (bolp) (search-forward "|" (line-end-position) t
))
1674 (org-table-check-inside-data-field))
1675 ;; Set appropriate case sensitivity and column used for sorting.
1676 (let ((column (let ((c (org-table-current-column)))
1678 ((called-interactively-p 'any
)
1679 (read-number "Use column N for sorting: "))
1683 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
1684 \[t]ime, [f]unc. A/N/T/F means reversed: "))))
1686 ;; Narrow buffer to appropriate sorting area.
1687 (if (org-region-active-p)
1688 (progn (goto-char (region-beginning))
1691 (save-excursion (goto-char (region-end))
1692 (line-beginning-position 2))))
1693 (let ((start (org-table-begin))
1694 (end (org-table-end)))
1697 (if (re-search-backward org-table-hline-regexp start t
)
1698 (line-beginning-position 2)
1700 (if (save-excursion (re-search-forward org-table-hline-regexp end t
))
1703 ;; Determine arguments for `sort-subr'. Also record original
1704 ;; position. `org-table-save-field' cannot help here since
1705 ;; sorting is too much destructive.
1706 (let* ((sort-fold-case (not with-case
))
1708 (cons (count-lines (point-min) (line-beginning-position))
1710 (extract-key-from-field
1711 ;; Function to be called on the contents of the field
1712 ;; used for sorting in the current row.
1713 (cl-case sorting-type
1714 ((?n ?N
) #'string-to-number
)
1715 ((?a ?A
) #'org-sort-remove-invisible
)
1718 (cond ((string-match org-ts-regexp-both f
)
1720 (org-time-string-to-time (match-string 0 f
))))
1721 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" f
)
1722 (org-hh:mm-string-to-minutes f
))
1726 (and (called-interactively-p 'any
)
1728 (completing-read "Sort using function: "
1729 obarray
#'fboundp t
)))
1730 (error "Missing key extractor to sort rows")))
1731 (t (user-error "Invalid sorting type `%c'" sorting-type
))))
1733 (cl-case sorting-type
1736 ((?f ?F
) compare-func
))))
1737 (goto-char (point-min))
1738 (sort-subr (memq sorting-type
'(?A ?N ?T ?F
))
1741 (while (and (not (eobp))
1742 (not (looking-at org-table-dataline-regexp
)))
1746 (funcall extract-key-from-field
1747 (org-trim (org-table-get-field column
))))
1750 ;; Move back to initial field.
1751 (forward-line (car coordinates
))
1752 (move-to-column (cdr coordinates
))))))
1755 (defun org-table-cut-region (beg end
)
1756 "Copy region in table to the clipboard and blank all relevant fields.
1757 If there is no active region, use just the field at point."
1759 (if (org-region-active-p) (region-beginning) (point))
1760 (if (org-region-active-p) (region-end) (point))))
1761 (org-table-copy-region beg end
'cut
))
1764 (defun org-table-copy-region (beg end
&optional cut
)
1765 "Copy rectangular region in table to clipboard.
1766 A special clipboard is used which can only be accessed
1767 with `org-table-paste-rectangle'."
1769 (if (org-region-active-p) (region-beginning) (point))
1770 (if (org-region-active-p) (region-end) (point))
1771 current-prefix-arg
))
1772 (goto-char (min beg end
))
1773 (org-table-check-inside-data-field)
1774 (let ((beg (line-beginning-position))
1775 (c01 (org-table-current-column))
1777 (goto-char (max beg end
))
1778 (org-table-check-inside-data-field)
1779 (let* ((end (copy-marker (line-end-position)))
1780 (c02 (org-table-current-column))
1781 (column-start (min c01 c02
))
1782 (column-end (max c01 c02
))
1783 (column-number (1+ (- column-end column-start
)))
1784 (rpl (and cut
" ")))
1786 (while (< (point) end
)
1787 (unless (org-at-table-hline-p)
1788 ;; Collect every cell between COLUMN-START and COLUMN-END.
1790 (dotimes (c column-number
)
1791 (push (org-table-get-field (+ c column-start
) rpl
) cols
))
1792 (push (nreverse cols
) region
)))
1794 (set-marker end nil
))
1795 (when cut
(org-table-align))
1796 (setq org-table-clip
(nreverse region
))))
1799 (defun org-table-paste-rectangle ()
1800 "Paste a rectangular region into a table.
1801 The upper right corner ends up in the current field. All involved fields
1802 will be overwritten. If the rectangle does not fit into the present table,
1803 the table is enlarged as needed. The process ignores horizontal separator
1806 (unless (consp org-table-clip
)
1807 (user-error "First cut/copy a region to paste!"))
1808 (org-table-check-inside-data-field)
1809 (let* ((column (org-table-current-column))
1810 (org-enable-table-editor t
)
1811 (org-table-automatic-realign nil
))
1812 (org-table-save-field
1813 (dolist (row org-table-clip
)
1814 (while (org-at-table-hline-p) (forward-line))
1815 ;; If we left the table, create a new row.
1816 (when (and (bolp) (not (looking-at "[ \t]*|")))
1818 (org-table-next-field))
1821 (org-table-goto-column c nil
'force
)
1822 (org-table-get-field nil field
)
1828 (defun org-table-convert ()
1829 "Convert from `org-mode' table to table.el and back.
1830 Obviously, this only works within limits. When an Org table is converted
1831 to table.el, all horizontal separator lines get lost, because table.el uses
1832 these as cell boundaries and has no notion of horizontal lines. A table.el
1833 table can be converted to an Org table only if it does not do row or column
1834 spanning. Multiline cells will become multiple cells. Beware, Org mode
1835 does not test if the table can be successfully converted - it blindly
1836 applies a recipe that works for simple tables."
1839 (if (org-at-table.el-p
)
1840 ;; convert to Org table
1841 (let ((beg (copy-marker (org-table-begin t
)))
1842 (end (copy-marker (org-table-end t
))))
1843 (table-unrecognize-region beg end
)
1845 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1848 (if (org-at-table-p)
1849 ;; convert to table.el table
1850 (let ((beg (copy-marker (org-table-begin)))
1851 (end (copy-marker (org-table-end))))
1852 ;; first, get rid of all horizontal lines
1854 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1856 ;; insert a hline before first
1858 (org-table-insert-hline 'above
)
1859 (beginning-of-line -
1)
1860 ;; insert a hline after each line
1861 (while (progn (beginning-of-line 3) (< (point) end
))
1862 (org-table-insert-hline))
1864 (setq end
(move-marker end
(org-table-end)))
1865 ;; replace "+" at beginning and ending of hlines
1866 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1867 (replace-match "\\1+-"))
1869 (while (re-search-forward "-|[ \t]*$" end t
)
1870 (replace-match "-+"))
1873 (defun org-table-transpose-table-at-point ()
1874 "Transpose Org table at point and eliminate hlines.
1882 will be transposed as
1889 Note that horizontal lines disappear."
1891 (let* ((table (delete 'hline
(org-table-to-lisp)))
1892 (dline_old (org-table-current-line))
1893 (col_old (org-table-current-column))
1894 (contents (mapcar (lambda (_)
1900 (setq tp
(cdr tp
))))
1903 (goto-char (org-table-begin))
1904 (re-search-forward "|")
1906 (delete-region (point) (org-table-end))
1909 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1911 (org-table-goto-line col_old
)
1912 (org-table-goto-column dline_old
))
1916 (defun org-table-wrap-region (arg)
1917 "Wrap several fields in a column like a paragraph.
1918 This is useful if you'd like to spread the contents of a field over several
1919 lines, in order to keep the table compact.
1921 If there is an active region, and both point and mark are in the same column,
1922 the text in the column is wrapped to minimum width for the given number of
1923 lines. Generally, this makes the table more compact. A prefix ARG may be
1924 used to change the number of desired lines. For example, \
1925 `C-2 \\[org-table-wrap-region]'
1926 formats the selected text to two lines. If the region was longer than two
1927 lines, the remaining lines remain empty. A negative prefix argument reduces
1928 the current number of lines by that amount. The wrapped text is pasted back
1929 into the table. If you formatted it to more lines than it was before, fields
1930 further down in the table get overwritten - so you might need to make space in
1933 If there is no region, the current field is split at the cursor position and
1934 the text fragment to the right of the cursor is prepended to the field one
1937 If there is no region, but you specify a prefix ARG, the current field gets
1938 blank, and the content is appended to the field above."
1940 (org-table-check-inside-data-field)
1941 (if (org-region-active-p)
1942 ;; There is a region: fill as a paragraph.
1943 (let ((start (region-beginning)))
1944 (org-table-cut-region (region-beginning) (region-end))
1945 (when (> (length (car org-table-clip
)) 1)
1946 (user-error "Region must be limited to single column"))
1947 (let ((nlines (cond ((not arg
) (length org-table-clip
))
1948 ((< arg
1) (+ (length org-table-clip
) arg
))
1950 (setq org-table-clip
1952 (org-wrap (mapconcat #'car org-table-clip
" ")
1956 (org-table-paste-rectangle))
1957 ;; No region, split the current field at point.
1958 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1959 (skip-chars-forward "^\r\n|"))
1961 (arg ; Combine with field above.
1962 (let ((s (org-table-blank-field))
1963 (col (org-table-current-column)))
1965 (while (org-at-table-hline-p) (forward-line -
1))
1966 (org-table-goto-column col
)
1967 (skip-chars-forward "^|")
1968 (skip-chars-backward " ")
1969 (insert " " (org-trim s
))
1971 ((looking-at "\\([^|]+\\)+|") ; Split field.
1972 (let ((s (match-string 1)))
1973 (replace-match " |")
1974 (goto-char (match-beginning 0))
1975 (org-table-next-row)
1976 (insert (org-trim s
) " ")
1978 (t (org-table-next-row)))))
1980 (defvar org-field-marker nil
)
1983 (defun org-table-edit-field (arg)
1984 "Edit table field in a different window.
1985 This is mainly useful for fields that contain hidden parts.
1987 When called with a `\\[universal-argument]' prefix, just make the full field
1988 visible so that it can be edited in place.
1990 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
1991 toggle `org-table-follow-field-mode'."
1993 (unless (org-at-table-p) (user-error "Not at a table"))
1996 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1998 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1999 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2000 (remove-text-properties b e
'(org-cwidth t invisible t
2001 display t intangible t
))
2002 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2003 (font-lock-fontify-block))))
2005 (let ((pos (point-marker))
2007 (if (eq org-table-use-standard-references t
)
2008 (concat (org-number-to-letters (org-table-current-column))
2009 (int-to-string (org-table-current-dline)))
2010 (concat "@" (int-to-string (org-table-current-dline))
2011 "$" (int-to-string (org-table-current-column)))))
2012 (field (org-table-get-field))
2013 (cw (current-window-configuration))
2016 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2017 (when (and (local-variable-p 'org-field-marker
)
2018 (markerp org-field-marker
))
2019 (move-marker org-field-marker nil
))
2021 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2022 (let ((org-inhibit-startup t
)) (org-mode))
2024 (setq truncate-lines nil
)
2026 (goto-char (setq p
(point-max)))
2027 (insert (org-trim field
))
2028 (remove-text-properties p
(point-max)
2029 '(invisible t org-cwidth t display t
2032 (setq-local org-finish-function
'org-table-finish-edit-field
)
2033 (setq-local org-window-configuration cw
)
2034 (setq-local org-field-marker pos
)
2035 (message "Edit and finish with C-c C-c")))))
2037 (defun org-table-finish-edit-field ()
2038 "Finish editing a table data field.
2039 Remove all newline characters, insert the result into the table, realign
2040 the table and kill the editing buffer."
2041 (let ((pos org-field-marker
)
2042 (cw org-window-configuration
)
2043 (cb (current-buffer))
2045 (goto-char (point-min))
2046 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2047 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2048 (replace-match " "))
2049 (setq text
(org-trim (buffer-string)))
2050 (set-window-configuration cw
)
2052 (select-window (get-buffer-window (marker-buffer pos
)))
2054 (move-marker pos nil
)
2055 (org-table-check-inside-data-field)
2056 (org-table-get-field nil text
)
2058 (message "New field value inserted")))
2060 (define-minor-mode org-table-follow-field-mode
2061 "Minor mode to make the table field editor window follow the cursor.
2062 When this mode is active, the field editor window will always show the
2063 current field. The mode exits automatically when the cursor leaves the
2064 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2065 nil
" TblFollow" nil
2066 (if org-table-follow-field-mode
2067 (add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2069 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2070 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2071 (win (and buf
(get-buffer-window buf
))))
2072 (when win
(delete-window win
))
2074 (with-current-buffer buf
2075 (move-marker org-field-marker nil
))
2076 (kill-buffer buf
)))))
2078 (defun org-table-follow-fields-with-editor ()
2079 (if (and org-table-exit-follow-field-mode-when-leaving-table
2080 (not (org-at-table-p)))
2081 ;; We have left the table, exit the follow mode
2082 (org-table-follow-field-mode -
1)
2083 (when (org-table-check-inside-data-field 'noerror
)
2084 (let ((win (selected-window)))
2085 (org-table-edit-field nil
)
2086 (org-fit-window-to-buffer)
2087 (select-window win
)))))
2089 (defvar org-timecnt
) ; dynamically scoped parameter
2092 (defun org-table-sum (&optional beg end nlast
)
2093 "Sum numbers in region of current table column.
2094 The result will be displayed in the echo area, and will be available
2095 as kill to be inserted with \\[yank].
2097 If there is an active region, it is interpreted as a rectangle and all
2098 numbers in that rectangle will be summed. If there is no active
2099 region and point is located in a table column, sum all numbers in that
2102 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2103 numbers are assumed to be times as well (in decimal hours) and the
2104 numbers are added as such.
2106 If NLAST is a number, only the NLAST fields will actually be summed."
2109 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2111 ((and beg end
)) ; beg and end given explicitly
2112 ((org-region-active-p)
2113 (setq beg
(region-beginning) end
(region-end)))
2115 (setq col
(org-table-current-column))
2116 (goto-char (org-table-begin))
2117 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2118 (user-error "No table data"))
2119 (org-table-goto-column col
)
2121 (goto-char (org-table-end))
2122 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2123 (user-error "No table data"))
2124 (org-table-goto-column col
)
2125 (setq end
(point))))
2126 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2127 (items1 (cond ((not nlast
) items
)
2128 ((>= nlast
(length items
)) items
)
2129 (t (setq items
(reverse items
))
2130 (setcdr (nthcdr (1- nlast
) items
) nil
)
2132 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2134 (res (apply '+ numbers
))
2135 (sres (if (= org-timecnt
0)
2136 (number-to-string res
)
2137 (setq diff
(* 3600 res
)
2138 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2139 m
(floor (/ diff
60)) diff
(mod diff
60)
2141 (format "%.0f:%02.0f:%02.0f" h m s
))))
2143 (when (called-interactively-p 'interactive
)
2144 (message "%s" (substitute-command-keys
2145 (format "Sum of %d items: %-20s \
2146 \(\\[yank] will insert result into buffer)" (length numbers
) sres
))))
2149 (defun org-table-get-number-for-summing (s)
2151 (if (string-match "^ *|? *" s
)
2152 (setq s
(replace-match "" nil nil s
)))
2153 (if (string-match " *|? *$" s
)
2154 (setq s
(replace-match "" nil nil s
)))
2155 (setq n
(string-to-number s
))
2157 ((and (string-match "0" s
)
2158 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2159 ((string-match "\\`[ \t]+\\'" s
) nil
)
2160 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2161 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2162 (m (string-to-number (or (match-string 2 s
) "0")))
2163 (s (string-to-number (or (match-string 4 s
) "0"))))
2164 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2165 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2169 (defun org-table-current-field-formula (&optional key noerror
)
2170 "Return the formula active for the current field.
2172 Assumes that table is already analyzed. If KEY is given, return
2173 the key to this formula. Otherwise return the formula preceded
2174 with \"=\" or \":=\"."
2175 (let* ((line (count-lines org-table-current-begin-pos
2176 (line-beginning-position)))
2177 (row (org-table-line-to-dline line
)))
2180 (let* ((col (org-table-current-column))
2181 (name (car (rassoc (list line col
)
2182 org-table-named-field-locations
)))
2183 (scol (format "$%d" col
))
2184 (ref (format "@%d$%d" (org-table-current-dline) col
))
2185 (stored-list (org-table-get-stored-formulas noerror
))
2186 (ass (or (assoc name stored-list
)
2187 (assoc ref stored-list
)
2188 (assoc scol stored-list
))))
2189 (cond (key (car ass
))
2190 (ass (concat (if (string-match-p "^[0-9]+$" (car ass
)) "=" ":=")
2193 (t (error "No formula active for the current field")))))
2195 (defun org-table-get-formula (&optional equation named
)
2196 "Read a formula from the minibuffer, offer stored formula as default.
2197 When NAMED is non-nil, look for a named equation."
2198 (let* ((stored-list (org-table-get-stored-formulas))
2199 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2200 (line-beginning-position))
2201 (org-table-current-column))
2202 org-table-named-field-locations
)))
2203 (ref (format "@%d$%d"
2204 (org-table-current-dline)
2205 (org-table-current-column)))
2207 ((not named
) (format "$%d" (org-table-current-column)))
2208 ((and name
(not (string-match "\\`LR[0-9]+\\'" name
))) name
)
2210 (name (or name ref
))
2211 (org-table-may-need-update nil
)
2212 (stored (cdr (assoc scol stored-list
)))
2214 ((and stored equation
(string-match-p "^ *=? *$" equation
))
2218 (t (org-table-formula-from-user
2220 (org-table-formula-to-user
2221 (format "%s formula %s="
2222 (if named
"Field" "Column")
2224 (if stored
(org-table-formula-to-user stored
) "")
2225 'org-table-formula-history
2228 (when (not (string-match "\\S-" eq
))
2230 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2231 (org-table-store-formulas stored-list
)
2232 (user-error "Formula removed"))
2233 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2234 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2235 (if (and name
(not named
))
2236 ;; We set the column equation, delete the named one.
2237 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2240 (setcdr (assoc scol stored-list
) eq
)
2241 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2242 (if (or mustsave
(not (equal stored eq
)))
2243 (org-table-store-formulas stored-list
))
2246 (defun org-table-store-formulas (alist &optional location
)
2247 "Store the list of formulas below the current table.
2248 If optional argument LOCATION is a buffer position, insert it at
2252 (progn (goto-char location
) (beginning-of-line))
2253 (goto-char (org-table-end)))
2254 (let ((case-fold-search t
))
2255 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2257 ;; Don't overwrite TBLFM, we might use text properties to
2259 (goto-char (match-beginning 3))
2260 (delete-region (match-beginning 3) (match-end 0)))
2262 (insert (or (match-string 2) "#+TBLFM:")))
2264 (mapconcat (lambda (x) (concat (car x
) "=" (cdr x
)))
2265 (sort alist
#'org-table-formula-less-p
)
2269 (defsubst org-table-formula-make-cmp-string
(a)
2270 (when (string-match "\\`$[<>]" a
)
2271 (let ((arrow (string-to-char (substring a
1))))
2272 ;; Fake a high number to make sure this is sorted at the end.
2273 (setq a
(org-table-formula-handle-first/last-rc a
))
2274 (setq a
(format "$%d" (+ 10000
2275 (if (= arrow ?
<) -
1000 0)
2276 (string-to-number (substring a
1)))))))
2278 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2282 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2284 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2286 (concat "@@" (match-string 5 a
))))))
2288 (defun org-table-formula-less-p (a b
)
2289 "Compare two formulas for sorting."
2290 (let ((as (org-table-formula-make-cmp-string (car a
)))
2291 (bs (org-table-formula-make-cmp-string (car b
))))
2292 (and as bs
(string< as bs
))))
2295 (defun org-table-get-stored-formulas (&optional noerror location
)
2296 "Return an alist with the stored formulas directly after current table.
2297 By default, only return active formulas, i.e., formulas located
2298 on the first line after the table. However, if optional argument
2299 LOCATION is a buffer position, consider the formulas there."
2302 (progn (goto-char location
) (beginning-of-line))
2303 (goto-char (org-table-end)))
2304 (let ((case-fold-search t
))
2305 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2306 (let ((strings (org-split-string (match-string-no-properties 2)
2309 (dolist (string strings
(nreverse eq-alist
))
2310 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2311 [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2314 (let ((m (match-string 1 string
)))
2316 ((not (match-end 2)) m
)
2317 ;; Is it a column reference?
2318 ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m
) m
)
2319 ;; Since named columns are not possible in
2320 ;; LHS, assume this is a named field.
2321 (t (match-string 2 string
)))))
2322 (rhs (match-string 3 string
)))
2323 (push (cons lhs rhs
) eq-alist
)
2325 ((not (member lhs seen
)) (push lhs seen
))
2328 "Double definition `%s=' in TBLFM line, please fix by hand"
2334 "Double definition `%s=' in TBLFM line, please fix by hand"
2337 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2338 "Modify the equations after the table structure has been edited.
2339 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2340 For all numbers larger than LIMIT, shift them by DELTA."
2342 (goto-char (org-table-end))
2343 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2344 (let ((msg "The formulas in #+TBLFM have been updated")
2345 (re (concat key
"\\([0-9]+\\)"))
2348 (if (or (equal key
"$") (equal key
"$LR"))
2349 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2350 (regexp-quote key
) remove
)
2351 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2354 (while (re-search-forward re2
(point-at-eol) t
)
2355 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2356 (if (equal (char-before (match-beginning 0)) ?.
)
2358 "Change makes TBLFM term %s invalid, use undo to recover"
2360 (replace-match "")))))
2361 (while (re-search-forward re
(point-at-eol) t
)
2362 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2363 (setq s
(match-string 1) n
(string-to-number s
))
2365 ((setq a
(assoc s replace
))
2366 (replace-match (concat key
(cdr a
)) t t
)
2368 ((and limit
(> n limit
))
2369 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2374 (defun org-table-maybe-eval-formula ()
2375 "Check if the current field starts with \"=\" or \":=\".
2376 If yes, store the formula and apply it."
2377 ;; We already know we are in a table. Get field will only return a formula
2378 ;; when appropriate. It might return a separator line, but no problem.
2379 (when org-table-formula-evaluate-inline
2380 (let* ((field (org-trim (or (org-table-get-field) "")))
2382 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2383 (setq named
(equal (string-to-char field
) ?
:)
2384 eq
(match-string 1 field
))
2385 (org-table-eval-formula (and named
'(4))
2386 (org-table-formula-from-user eq
))))))
2388 (defvar org-recalc-commands nil
2389 "List of commands triggering the recalculation of a line.
2390 Will be filled automatically during use.")
2392 (defvar org-recalc-marks
2393 '((" " .
"Unmarked: no special line, no automatic recalculation")
2394 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2395 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2396 ("!" .
"Column name definition line. Reference in formula as $name.")
2397 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2398 ("_" .
"Names for values in row below this one.")
2399 ("^" .
"Names for values in row above this one.")))
2402 (defun org-table-rotate-recalc-marks (&optional newchar
)
2403 "Rotate the recalculation mark in the first column.
2404 If in any row, the first field is not consistent with a mark,
2405 insert a new column for the markers.
2406 When there is an active region, change all the lines in the region,
2407 after prompting for the marking character.
2408 After each change, a message will be displayed indicating the meaning
2411 (unless (org-at-table-p) (user-error "Not at a table"))
2412 (let* ((region (org-region-active-p))
2414 (save-excursion (goto-char (region-beginning))
2415 (copy-marker (line-beginning-position)))))
2417 (save-excursion (goto-char (region-end))
2418 (copy-marker (line-beginning-position)))))
2419 (l (copy-marker (line-beginning-position)))
2420 (col (org-table-current-column))
2423 (read-char-exclusive
2424 "Change region to what mark? Type # * ! $ or SPC: "))
2428 (goto-char (org-table-begin))
2430 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2431 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2432 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2434 (when l1
(goto-char l1
))
2437 (unless (looking-at org-table-dataline-regexp
)
2438 (user-error "Not at a table data line")))
2439 (when no-special-column
2440 (org-table-goto-column 1)
2441 (org-table-insert-column))
2442 (let ((previous-line-end (line-end-position))
2446 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2448 (t (cadr (member (match-string 1)
2449 (append (mapcar #'car org-recalc-marks
)
2451 ;; Rotate mark in first row.
2452 (org-table-get-field 1 (format " %s " newchar
))
2453 ;; Rotate marks in additional rows if a region is active.
2457 (while (<= (point) l2
)
2458 (when (looking-at org-table-dataline-regexp
)
2459 (org-table-get-field 1 (format " %s " newchar
)))
2461 ;; Only align if rotation actually changed lines' length.
2462 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2464 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2465 (when l1
(set-marker l1 nil
))
2466 (when l2
(set-marker l2 nil
))
2468 (when (called-interactively-p 'interactive
)
2469 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2472 (defun org-table-analyze ()
2473 "Analyze table at point and store results.
2475 This function sets up the following dynamically scoped variables:
2477 `org-table-column-name-regexp',
2478 `org-table-column-names',
2479 `org-table-current-begin-pos',
2480 `org-table-current-line-types',
2481 `org-table-current-ncol',
2484 `org-table-local-parameters',
2485 `org-table-named-field-locations'."
2486 (let ((beg (org-table-begin))
2487 (end (org-table-end)))
2490 ;; Extract column names.
2491 (setq org-table-column-names nil
)
2492 (when (save-excursion
2493 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
2495 (dolist (name (org-split-string (match-string 1) " *| *"))
2497 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
2498 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
2499 (setq org-table-column-names
(nreverse org-table-column-names
))
2500 (setq org-table-column-name-regexp
2501 (format "\\$\\(%s\\)\\>"
2502 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
2503 ;; Extract local parameters.
2504 (setq org-table-local-parameters nil
)
2506 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2507 (dolist (field (org-split-string (match-string 1) " *| *"))
2509 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2510 (push (cons (match-string 1 field
) (match-string 2 field
))
2511 org-table-local-parameters
)))))
2512 ;; Update named fields locations. We minimize `count-lines'
2513 ;; processing by storing last known number of lines in LAST.
2514 (setq org-table-named-field-locations nil
)
2516 (let ((last (cons (point) 0)))
2517 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2518 (let ((c (match-string 1))
2519 (fields (org-split-string (match-string 2) " *| *")))
2521 (forward-line (if (equal c
"_") 1 -
1))
2523 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2524 (org-split-string (match-string 1) " *| *")))
2525 (line (cl-incf (cdr last
) (count-lines (car last
) (point))))
2527 (setcar last
(point)) ; Update last known position.
2528 (while (and fields fields1
)
2529 (let ((field (pop fields
))
2532 (when (and (stringp field
)
2534 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2536 (push (cons field v
) org-table-local-parameters
)
2537 (push (list field line col
)
2538 org-table-named-field-locations
))))))))))
2539 ;; Re-use existing markers when possible.
2540 (if (markerp org-table-current-begin-pos
)
2541 (move-marker org-table-current-begin-pos
(point))
2542 (setq org-table-current-begin-pos
(point-marker)))
2543 ;; Analyze the line types.
2544 (let ((l 0) hlines dlines types
)
2545 (while (looking-at "[ \t]*|\\(-\\)?")
2546 (push (if (match-end 1) 'hline
'dline
) types
)
2547 (if (match-end 1) (push l hlines
) (push l dlines
))
2550 (push 'hline types
) ; Add an imaginary extra hline to the end.
2551 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
2552 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
2553 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
)))))
2554 ;; Get the number of columns from the first data line in table.
2556 (forward-line (aref org-table-dlines
1))
2559 (buffer-substring (line-beginning-position) (line-end-position))
2561 (nfields (length fields
))
2563 (setq org-table-current-ncol nfields
)
2565 (aref org-table-dlines
(1- (length org-table-dlines
)))))
2566 (dotimes (i nfields
)
2567 (let ((column (1+ i
)))
2568 (push (list (format "LR%d" column
) last-dline column
) al
)
2569 (push (cons (format "LR%d" column
) (nth i fields
)) al2
))))
2570 (setq org-table-named-field-locations
2571 (append org-table-named-field-locations al
))
2572 (setq org-table-local-parameters
2573 (append org-table-local-parameters al2
))))))
2575 (defun org-table-goto-field (ref &optional create-column-p
)
2576 "Move point to a specific field in the current table.
2578 REF is either the name of a field its absolute reference, as
2579 a string. No column is created unless CREATE-COLUMN-P is
2580 non-nil. If it is a function, it is called with the column
2581 number as its argument as is used as a predicate to know if the
2582 column can be created.
2584 This function assumes the table is already analyzed (i.e., using
2585 `org-table-analyze')."
2588 ((cdr (assoc ref org-table-named-field-locations
)))
2589 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
2590 (list (condition-case nil
2591 (aref org-table-dlines
2592 (string-to-number (match-string 1 ref
)))
2593 (error (user-error "Invalid row number in %s" ref
)))
2594 (string-to-number (match-string 2 ref
))))
2595 (t (user-error "Unknown field: %s" ref
))))
2596 (line (car coordinates
))
2597 (column (nth 1 coordinates
))
2598 (create-new-column (if (functionp create-column-p
)
2599 (funcall create-column-p column
)
2602 (goto-char org-table-current-begin-pos
)
2604 (org-table-goto-column column nil create-new-column
))))
2607 (defun org-table-maybe-recalculate-line ()
2608 "Recompute the current line if marked for it, and if we haven't just done it."
2610 (and org-table-allow-automatic-line-recalculation
2611 (not (and (memq last-command org-recalc-commands
)
2612 (eq org-last-recalc-line
(line-beginning-position))))
2613 (save-excursion (beginning-of-line 1)
2614 (looking-at org-table-auto-recalculate-regexp
))
2615 (org-table-recalculate) t
))
2617 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2618 (defsubst org-set-calc-mode
(var &optional value
)
2620 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2621 ("R" calc-angle-mode rad
)
2622 ("F" calc-prefer-frac t
)
2623 ("S" calc-symbolic-mode t
)))
2624 value
(nth 2 var
) var
(nth 1 var
)))
2625 (if (memq var org-tbl-calc-modes
)
2626 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2627 (cons var
(cons value org-tbl-calc-modes
)))
2631 (defun org-table-eval-formula (&optional arg equation
2632 suppress-align suppress-const
2633 suppress-store suppress-analysis
)
2634 "Replace the table field value at the cursor by the result of a calculation.
2636 In a table, this command replaces the value in the current field with the
2637 result of a formula. It also installs the formula as the \"current\" column
2638 formula, by storing it in a special line below the table. When called
2639 with a `\\[universal-argument]' prefix the formula is installed as a \
2642 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2643 insert the active equation for the field
2644 back into the current field, so that it can be edited there. This is \
2646 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2647 check the referenced fields.
2649 When called, the command first prompts for a formula, which is read in
2650 the minibuffer. Previously entered formulas are available through the
2651 history list, and the last used formula is offered as a default.
2652 These stored formulas are adapted correctly when moving, inserting, or
2653 deleting columns with the corresponding commands.
2655 The formula can be any algebraic expression understood by the Calc package.
2656 For details, see the Org mode manual.
2658 This function can also be called from Lisp programs and offers
2659 additional arguments: EQUATION can be the formula to apply. If this
2660 argument is given, the user will not be prompted.
2662 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2665 SUPPRESS-CONST suppresses the interpretation of constants in the
2666 formula, assuming that this has been done already outside the
2669 SUPPRESS-STORE means the formula should not be stored, either
2670 because it is already stored, or because it is a modified
2671 equation that should not overwrite the stored one.
2673 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2676 (unless suppress-analysis
2677 (org-table-check-inside-data-field)
2678 (org-table-analyze))
2679 (if (equal arg
'(16))
2680 (let ((eq (org-table-current-field-formula)))
2681 (org-table-get-field nil eq
)
2683 (setq org-table-may-need-update t
))
2685 (ndown (if (integerp arg
) arg
1))
2686 (org-table-automatic-realign nil
)
2687 (case-fold-search nil
)
2689 (formula (if (and equation suppress-store
)
2691 (org-table-get-formula equation
(equal arg
'(4)))))
2692 (n0 (org-table-current-column))
2693 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2694 (numbers nil
) ; was a variable, now fixed default
2696 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2697 duration duration-output-format
)
2698 ;; Parse the format string. Since we have a lot of modes, this is
2699 ;; a lot of work. However, I think calc still uses most of the time.
2700 (if (string-match ";" formula
)
2701 (let ((tmp (org-split-string formula
";")))
2702 (setq formula
(car tmp
)
2703 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2705 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2706 (setq c
(string-to-char (match-string 1 fmt
))
2707 n
(string-to-number (match-string 2 fmt
)))
2709 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2710 (setq org-tbl-calc-modes
2713 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2714 (?s . sci
) (?e . eng
))))
2716 (setq fmt
(replace-match "" t t fmt
)))
2717 (if (string-match "T" fmt
)
2718 (setq duration t numbers t
2719 duration-output-format nil
2720 fmt
(replace-match "" t t fmt
)))
2721 (if (string-match "t" fmt
)
2723 duration-output-format org-table-duration-custom-format
2725 fmt
(replace-match "" t t fmt
)))
2726 (if (string-match "N" fmt
)
2728 fmt
(replace-match "" t t fmt
)))
2729 (if (string-match "L" fmt
)
2731 fmt
(replace-match "" t t fmt
)))
2732 (if (string-match "E" fmt
)
2734 fmt
(replace-match "" t t fmt
)))
2735 (while (string-match "[DRFS]" fmt
)
2736 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2737 (setq fmt
(replace-match "" t t fmt
)))
2738 (unless (string-match "\\S-" fmt
)
2740 (when (and (not suppress-const
) org-table-formula-use-constants
)
2741 (setq formula
(org-table-formula-substitute-names formula
)))
2742 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2743 (setq formula
(org-table-formula-handle-first/last-rc formula
))
2745 (setq fields
(org-split-string
2747 (buffer-substring-no-properties
2748 (line-beginning-position) (line-end-position)))
2750 ;; replace fields with duration values if relevant
2753 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2756 (setq fields
(mapcar
2758 (if (string-match "\\S-" x
)
2759 (number-to-string (string-to-number x
))
2762 (setq ndown
(1- ndown
))
2763 (setq form
(copy-sequence formula
)
2764 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2765 (if (and lispp literal
) (setq lispp
'literal
))
2767 ;; Insert row and column number of formula result field
2768 (while (string-match "[@$]#" form
)
2773 (if (equal (substring form
(match-beginning 0)
2774 (1+ (match-beginning 0)))
2776 (org-table-current-dline)
2777 (org-table-current-column))))
2780 ;; Check for old vertical references
2781 (org-table--error-on-old-row-references form
)
2782 ;; Insert remote references
2783 (setq form
(org-table-remote-reference-indirection form
))
2784 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2788 (org-table-make-reference
2789 (let ((rmtrng (org-table-get-remote-range
2790 (match-string 1 form
) (match-string 2 form
))))
2793 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2794 (org-table-time-string-to-seconds rmtrng
))
2796 keep-empty numbers lispp
))
2798 ;; Insert complex ranges
2799 (while (and (string-match org-table-range-regexp form
)
2800 (> (length (match-string 0 form
)) 1))
2803 (org-table-get-range
2804 (match-string 0 form
) org-table-current-begin-pos n0
)))
2807 (org-table-make-reference
2808 ;; possibly handle durations
2811 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2812 (org-table-time-string-to-seconds formrg
))
2814 keep-empty numbers lispp
)))
2815 (if (not (save-match-data
2816 (string-match (regexp-quote form
) formrpl
)))
2817 (setq form
(replace-match formrpl t t form
))
2818 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2819 ;; Insert simple ranges, i.e. included in the current row.
2820 (while (string-match
2821 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2826 (org-table-make-reference
2828 (+ (if (match-end 2) n0
0)
2829 (string-to-number (match-string 1 form
))
2831 (+ (if (match-end 4) n0
0)
2832 (string-to-number (match-string 3 form
))))
2833 keep-empty numbers lispp
))
2836 ;; Insert the references to fields in same row
2837 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2838 (setq n
(+ (string-to-number (match-string 1 form
))
2839 (if (match-end 2) n0
0))
2840 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2841 formrpl
(save-match-data
2842 (org-table-make-reference
2843 x keep-empty numbers lispp
)))
2846 (string-match (regexp-quote formula
) formrpl
)))
2847 (user-error "Invalid field specifier \"%s\""
2848 (match-string 0 form
)))
2849 (setq form
(replace-match formrpl t t form
)))
2852 (setq ev
(condition-case nil
2853 (eval (eval (read form
)))
2855 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2856 ev
(if duration
(org-table-time-seconds-to-string
2857 (string-to-number ev
)
2858 duration-output-format
) ev
))
2860 ;; Use <...> time-stamps so that Calc can handle them.
2862 (replace-regexp-in-string org-ts-regexp-inactive
"<\\1>" form
))
2863 ;; Internationalize local time-stamps by setting locale to
2866 (replace-regexp-in-string
2869 (let ((system-time-locale "C"))
2871 (org-time-stamp-format
2872 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2873 (apply #'encode-time
2874 (save-match-data (org-parse-time-string ts
))))))
2877 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2879 (calc-eval (cons form org-tbl-calc-modes
)
2880 (when (and (not keep-empty
) numbers
) 'num
)))
2881 ev
(if duration
(org-table-time-seconds-to-string
2882 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2883 (string-to-number (org-table-time-string-to-seconds ev
))
2884 (string-to-number ev
))
2885 duration-output-format
)
2888 (when org-table-formula-debug
2889 (with-output-to-temp-buffer "*Substitution History*"
2890 (princ (format "Substitution history of formula
2894 $1-> %s\n" orig formula form0 form
))
2896 (princ (format " %s^\nError: %s"
2897 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2898 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2900 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2901 (setq bw
(get-buffer-window "*Substitution History*"))
2902 (org-fit-window-to-buffer bw
)
2903 (unless (and (called-interactively-p 'any
) (not ndown
))
2904 (unless (let (inhibit-redisplay)
2905 (y-or-n-p "Debugging Formula. Continue to next? "))
2907 (user-error "Abort"))
2910 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2911 (org-table-justify-field-maybe
2912 (format org-table-formula-field-format
2914 ((not (stringp ev
)) ev
)
2915 (fmt (format fmt
(string-to-number ev
)))
2916 ;; Replace any active time stamp in the result with
2917 ;; an inactive one. Dates in tables are likely
2918 ;; piece of regular data, not meant to appear in the
2920 (t (replace-regexp-in-string org-ts-regexp
"[\\1]" ev
)))))
2921 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2922 (call-interactively 'org-return
)
2924 (and down
(org-table-maybe-recalculate-line))
2925 (or suppress-align
(and org-table-may-need-update
2926 (org-table-align))))))
2928 (defun org-table-put-field-property (prop value
)
2930 (put-text-property (progn (skip-chars-backward "^|") (point))
2931 (progn (skip-chars-forward "^|") (point))
2934 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2935 "Get a calc vector from a column, according to descriptor DESC.
2937 Optional arguments TBEG and COL can give the beginning of the table and
2938 the current column, to avoid unnecessary parsing.
2940 HIGHLIGHT means just highlight the range.
2942 When CORNERS-ONLY is set, only return the corners of the range as
2943 a list (line1 column1 line2 column2) where line1 and line2 are
2944 line numbers relative to beginning of table, or TBEG, and column1
2945 and column2 are table column numbers."
2946 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc
)
2947 (replace-regexp-in-string "\\$" "@0$" desc
)
2949 (col (or col
(org-table-current-column)))
2950 (tbeg (or tbeg
(org-table-begin)))
2951 (thisline (count-lines tbeg
(line-beginning-position))))
2952 (unless (string-match org-table-range-regexp desc
)
2953 (user-error "Invalid table range specifier `%s'" desc
))
2954 (let ((rangep (match-end 3))
2955 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2956 (or (save-match-data
2957 (and (org-string-nw-p r
)
2958 (org-table--descriptor-line r thisline
)))
2960 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
2961 (or (save-match-data
2962 (and (org-string-nw-p r
)
2963 (org-table--descriptor-line r thisline
)))
2965 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
2966 (if (or (not c
) (= (string-to-number c
) 0)) col
2967 (+ (string-to-number c
)
2968 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
2969 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
2970 (if (or (not c
) (= (string-to-number c
) 0)) col
2971 (+ (string-to-number c
)
2972 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
2974 (if (and (not corners-only
)
2975 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2978 (forward-line (- r1 thisline
))
2979 (while (not (looking-at org-table-dataline-regexp
))
2981 (prog1 (org-trim (org-table-get-field c1
))
2982 (when highlight
(org-table-highlight-rectangle))))
2983 ;; A range, return a vector. First sort the numbers to get
2984 ;; a regular rectangle.
2985 (let ((first-row (min r1 r2
))
2986 (last-row (max r1 r2
))
2987 (first-column (min c1 c2
))
2988 (last-column (max c1 c2
)))
2989 (if corners-only
(list first-row first-column last-row last-column
)
2990 ;; Copy the range values into a list.
2991 (forward-line (- first-row thisline
))
2992 (while (not (looking-at org-table-dataline-regexp
))
2994 (cl-incf first-row
))
2995 (org-table-goto-column first-column
)
2996 (let ((beg (point)))
2997 (forward-line (- last-row first-row
))
2998 (while (not (looking-at org-table-dataline-regexp
))
3000 (org-table-goto-column last-column
)
3001 (let ((end (point)))
3003 (org-table-highlight-rectangle
3004 beg
(progn (skip-chars-forward "^|\n") (point))))
3005 ;; Return string representation of calc vector.
3008 (org-table-copy-region beg end
))))))))))))
3010 (defun org-table--descriptor-line (desc cline
)
3011 "Return relative line number corresponding to descriptor DESC.
3012 The cursor is currently in relative line number CLINE."
3013 (if (string-match "\\`[0-9]+\\'" desc
)
3014 (aref org-table-dlines
(string-to-number desc
))
3015 (when (or (not (string-match
3016 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
3019 (and (not (match-end 3)) (not (match-end 6)))
3020 (and (match-end 3) (match-end 6) (not (match-end 5))))
3021 (user-error "Invalid row descriptor `%s'" desc
))
3022 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
3023 (hdir (match-string 2 desc
))
3024 (odir (match-string 5 desc
))
3025 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
3026 (rel (and (match-end 6)
3027 (or (and (match-end 1) (not (match-end 3)))
3029 (when (and hn
(not hdir
))
3032 (when (eq (aref org-table-current-line-types
0) 'hline
) (cl-decf hn
)))
3033 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
3036 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
3039 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
3042 (defun org-table--row-type (type n i backwards relative desc
)
3043 "Return relative line of Nth row with type TYPE.
3044 Search starts from relative line I. When BACKWARDS in non-nil,
3045 look before I. When RELATIVE is non-nil, the reference is
3046 relative. DESC is the original descriptor that started the
3047 search, as a string."
3048 (let ((l (length org-table-current-line-types
)))
3051 (while (and (cl-incf i
(if backwards -
1 1))
3054 (not (eq (aref org-table-current-line-types i
) type
))
3055 ;; We are going to cross a hline. Check if this is
3056 ;; an authorized move.
3059 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
3060 ((eq org-table-relative-ref-may-cross-hline t
))
3061 ((eq org-table-relative-ref-may-cross-hline
'error
)
3062 (user-error "Row descriptor %s crosses hline" desc
))
3063 (t (cl-decf i
(if backwards -
1 1)) ; Step back.
3064 (throw :exit nil
)))))))
3065 (cond ((or (< i
0) (>= i l
))
3066 (user-error "Row descriptor %s leads outside table" desc
))
3067 ;; The last hline doesn't exist. Instead, point to last row
3069 ((= i
(1- l
)) (1- i
))
3072 (defun org-table--error-on-old-row-references (s)
3073 (when (string-match "&[-+0-9I]" s
)
3074 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3076 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3077 "Convert list ELEMENTS to something appropriate to insert into formula.
3078 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3079 NUMBERS indicates that everything should be converted to numbers.
3080 LISPP non-nil means to return something appropriate for a Lisp
3081 list, `literal' is for the format specifier L."
3082 ;; Calc nan (not a number) is used for the conversion of the empty
3083 ;; field to a reference for several reasons: (i) It is accepted in a
3084 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3085 ;; (ii) In a single field (not in range) it can be distinguished
3086 ;; from "(nan)" which is the reference made from a single field
3087 ;; containing "nan".
3088 (if (stringp elements
)
3091 (if (eq lispp
'literal
)
3093 (if (and (eq elements
"") (not keep-empty
))
3096 (if numbers
(string-to-number elements
) elements
))))
3097 (if (string-match "\\S-" elements
)
3099 (when numbers
(setq elements
(number-to-string
3100 (string-to-number elements
))))
3101 (concat "(" elements
")"))
3102 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3107 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3109 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3113 (if (eq lispp
'literal
)
3115 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3117 (concat "[" (mapconcat
3119 (if (string-match "\\S-" x
)
3121 (number-to-string (string-to-number x
))
3123 (if (or (not keep-empty
) numbers
) "0" "nan")))
3127 (defun org-table-message-once-per-second (t1 &rest args
)
3128 "If there has been more than one second since T1, display message.
3129 ARGS are passed as arguments to the `message' function. Returns
3130 current time if a message is printed, otherwise returns T1. If
3131 T1 is nil, always messages."
3132 (let ((curtime (current-time)))
3133 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3134 (progn (apply 'message args
)
3139 (defun org-table-recalculate (&optional all noalign
)
3140 "Recalculate the current table line by applying all stored formulas.
3142 With prefix arg ALL, do this for all lines in the table.
3144 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
3145 if ALL is the symbol `iterate',
3146 recompute the table until it no longer changes.
3148 If NOALIGN is not nil, do not re-align the table after the computations
3149 are done. This is typically used internally to save time, if it is
3150 known that the table will be realigned a little later anyway."
3152 (unless (memq this-command org-recalc-commands
)
3153 (push this-command org-recalc-commands
))
3154 (unless (org-at-table-p) (user-error "Not at a table"))
3155 (if (or (eq all
'iterate
) (equal all
'(16)))
3158 (let* ((eqlist (sort (org-table-get-stored-formulas)
3159 (lambda (a b
) (string< (car a
) (car b
)))))
3160 (inhibit-redisplay (not debug-on-error
))
3161 (line-re org-table-dataline-regexp
)
3162 (log-first-time (current-time))
3163 (log-last-time log-first-time
)
3165 beg end eqlcol eqlfield
)
3166 ;; Insert constants in all formulas.
3168 (org-table-save-field
3169 ;; Expand equations, then split the equation list between
3170 ;; column formulas and field formulas.
3172 (let* ((rhs (org-table-formula-substitute-names
3173 (org-table-formula-handle-first/last-rc
(cdr eq
))))
3176 (org-table-formula-handle-first/last-rc
3178 ((string-match "\\`@-?I+" old-lhs
)
3179 (user-error "Can't assign to hline relative reference"))
3180 ((string-match "\\`$[<>]" old-lhs
)
3181 (let ((new (org-table-formula-handle-first/last-rc
3183 (when (assoc new eqlist
)
3184 (user-error "\"%s=\" formula tries to overwrite \
3185 existing formula for column %s"
3190 (if (string-match-p "\\`\\$[0-9]+\\'" lhs
)
3191 (push (cons lhs rhs
) eqlcol
)
3192 (push (cons lhs rhs
) eqlfield
))))
3193 (setq eqlcol
(nreverse eqlcol
))
3194 ;; Expand ranges in lhs of formulas
3195 (setq eqlfield
(org-table-expand-lhs-ranges (nreverse eqlfield
)))
3196 ;; Get the correct line range to process.
3199 (setq end
(copy-marker (org-table-end)))
3200 (goto-char (setq beg org-table-current-begin-pos
))
3202 ((re-search-forward org-table-calculate-mark-regexp end t
)
3203 ;; This is a table with marked lines, compute selected
3205 (setq line-re org-table-recalculate-regexp
))
3206 ;; Move forward to the first non-header line.
3207 ((and (re-search-forward org-table-dataline-regexp end t
)
3208 (re-search-forward org-table-hline-regexp end t
)
3209 (re-search-forward org-table-dataline-regexp end t
))
3210 (setq beg
(match-beginning 0)))
3211 ;; Just leave BEG at the start of the table.
3213 (setq beg
(line-beginning-position)
3214 end
(copy-marker (line-beginning-position 2))))
3216 ;; Mark named fields untouchable. Also check if several
3217 ;; field/range formulas try to set the same field.
3218 (remove-text-properties beg end
'(org-untouchable t
))
3219 (let ((current-line (count-lines org-table-current-begin-pos
3220 (line-beginning-position)))
3222 (dolist (eq eqlfield
)
3223 (let* ((name (car eq
))
3224 (location (assoc name org-table-named-field-locations
))
3225 (eq-line (or (nth 1 location
)
3226 (and (string-match "\\`@\\([0-9]+\\)" name
)
3227 (aref org-table-dlines
3229 (match-string 1 name
))))))
3232 ;; Turn field coordinates associated to NAME
3233 ;; into an absolute reference.
3235 (org-table-line-to-dline eq-line
)
3238 (when (member reference seen-fields
)
3239 (user-error "Several field/range formulas try to set %s"
3241 (push reference seen-fields
)
3242 (when (or all
(eq eq-line current-line
))
3243 (org-table-goto-field name
)
3244 (org-table-put-field-property :org-untouchable t
)))))
3245 ;; Evaluate the column formulas, but skip fields covered by
3248 (while (re-search-forward line-re end t
)
3249 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3250 ;; Unprotected line, recalculate.
3254 (org-table-message-once-per-second
3256 "Re-applying formulas to full table...(line %d)" cnt
)))
3257 (if (markerp org-last-recalc-line
)
3258 (move-marker org-last-recalc-line
(line-beginning-position))
3259 (setq org-last-recalc-line
3260 (copy-marker (line-beginning-position))))
3261 (dolist (entry eqlcol
)
3262 (goto-char org-last-recalc-line
)
3263 (org-table-goto-column
3264 (string-to-number (substring (car entry
) 1)) nil
'force
)
3265 (unless (get-text-property (point) :org-untouchable
)
3266 (org-table-eval-formula
3267 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
3268 ;; Evaluate the field formulas.
3269 (dolist (eq eqlfield
)
3270 (let ((reference (car eq
))
3273 (org-table-message-once-per-second
3274 (and all log-last-time
)
3275 "Re-applying formula to field: %s" (car eq
)))
3276 (org-table-goto-field
3278 ;; Possibly create a new column, as long as
3279 ;; `org-table-formula-create-columns' allows it.
3280 (let ((column-count (progn (end-of-line)
3281 (1- (org-table-current-column)))))
3283 (when (> column
1000)
3284 (user-error "Formula column target too large"))
3285 (and (> column column-count
)
3286 (or (eq org-table-formula-create-columns t
)
3287 (and (eq org-table-formula-create-columns
'warn
)
3289 (org-display-warning
3290 "Out-of-bounds formula added columns")
3292 (and (eq org-table-formula-create-columns
'prompt
)
3294 "Out-of-bounds formula. Add columns? ")))))))
3295 (org-table-eval-formula nil formula t t t t
))))
3296 ;; Clean up markers and internal text property.
3297 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3298 (set-marker end nil
)
3300 (when org-table-may-need-update
(org-table-align))
3302 (org-table-message-once-per-second
3303 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
3304 (org-table-message-once-per-second
3305 (and all log-first-time
) "Re-applying formulas... done")))))
3308 (defun org-table-iterate (&optional arg
)
3309 "Recalculate the table until it does not change anymore.
3310 The maximum number of iterations is 10, but you can choose a different value
3311 with the prefix ARG."
3313 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3315 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3320 (org-table-recalculate 'all
)
3321 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3322 (if (not (string= lasttbl thistbl
))
3323 (setq lasttbl thistbl
)
3325 (message "Convergence after %d iterations" i
)
3326 (message "Table was already stable"))
3328 (user-error "No convergence after %d iterations" i
))))
3331 (defun org-table-recalculate-buffer-tables ()
3332 "Recalculate all tables in the current buffer."
3334 (org-with-wide-buffer
3335 (org-table-map-tables
3337 ;; Reason for separate `org-table-align': When repeating
3338 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
3340 (org-table-recalculate t t
)
3345 (defun org-table-iterate-buffer-tables ()
3346 "Iterate all tables in the buffer, to converge inter-table dependencies."
3350 (checksum (md5 (buffer-string)))
3352 (org-with-wide-buffer
3356 (org-table-map-tables (lambda () (org-table-recalculate t t
)) t
)
3357 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3359 (org-table-map-tables #'org-table-align t
)
3360 (message "Convergence after %d iterations" (- imax i
))
3362 (setq checksum c1
)))
3363 (org-table-map-tables #'org-table-align t
)
3364 (user-error "No convergence after %d iterations" imax
)))))
3366 (defun org-table-calc-current-TBLFM (&optional arg
)
3367 "Apply the #+TBLFM in the line at point to the table."
3369 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3370 (let ((formula (buffer-substring
3371 (line-beginning-position)
3372 (line-end-position))))
3374 ;; Insert a temporary formula at right after the table
3375 (goto-char (org-table-TBLFM-begin))
3376 (let ((s (point-marker)))
3377 (insert formula
"\n")
3378 (let ((e (point-marker)))
3379 ;; Recalculate the table.
3380 (beginning-of-line 0) ; move to the inserted line
3381 (skip-chars-backward " \r\n\t")
3383 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3384 ;; Delete the formula inserted temporarily.
3387 (set-marker e nil
)))))))
3389 (defun org-table-TBLFM-begin ()
3390 "Find the beginning of the TBLFM lines and return its position.
3391 Return nil when the beginning of TBLFM line was not found."
3393 (when (progn (forward-line 1)
3394 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3395 (line-beginning-position 2))))
3397 (defun org-table-expand-lhs-ranges (equations)
3398 "Expand list of formulas.
3399 If some of the RHS in the formulas are ranges or a row reference,
3400 expand them to individual field equations for each field. This
3401 function assumes the table is already analyzed (i.e., using
3402 `org-table-analyze')."
3404 (dolist (e equations
(nreverse res
))
3408 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3409 ;; This just refers to one fixed field.
3411 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3412 ;; This just refers to one fixed named field.
3414 ((string-match-p "\\`\\$[0-9]+\\'" lhs
)
3415 ;; Column formulas are treated specially and are not
3418 ((string-match "\\`@[0-9]+\\'" lhs
)
3419 (dotimes (ic org-table-current-ncol
)
3420 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3424 (let* ((range (org-table-get-range
3425 lhs org-table-current-begin-pos
1 nil
'corners
))
3426 (r1 (org-table-line-to-dline (nth 0 range
)))
3428 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3430 (cl-loop for ir from r1 to r2 do
3431 (cl-loop for ic from c1 to c2 do
3432 (push (cons (propertize
3433 (format "@%d$%d" ir ic
) :orig-eqn e
)
3437 (defun org-table-formula-handle-first/last-rc
(s)
3438 "Replace @<, @>, $<, $> with first/last row/column of the table.
3439 So @< and $< will always be replaced with @1 and $1, respectively.
3440 The advantage of these special markers are that structure editing of
3441 the table will not change them, while @1 and $1 will be modified
3442 when a line/row is swapped out of that privileged position. So for
3443 formulas that use a range of rows or columns, it may often be better
3444 to anchor the formula with \"I\" row markers, or to offset from the
3445 borders of the table using the @< @> $< $> makers."
3446 (let (n nmax len char
(start 0))
3447 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3450 (setq start
(match-end 3))
3451 (setq nmax
(if (equal (match-string 1 s
) "@")
3452 (1- (length org-table-dlines
))
3453 org-table-current-ncol
)
3454 len
(- (match-end 2) (match-beginning 2))
3455 char
(string-to-char (match-string 2 s
))
3459 (if (or (< n
1) (> n nmax
))
3460 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3461 (match-string 0 s
) s
))
3462 (setq start
(match-beginning 0))
3463 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3466 (defun org-table-formula-substitute-names (f)
3467 "Replace $const with values in string F."
3469 (pp (/= (string-to-char f
) ?
'))
3470 (duration (string-match-p ";.*[Tt].*\\'" f
))
3471 (new (replace-regexp-in-string ; Check for column names.
3472 org-table-column-name-regexp
3474 (concat "$" (cdr (assoc (match-string 1 m
)
3475 org-table-column-names
))))
3477 ;; Parameters and constants.
3480 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3482 (if (match-end 2) (setq start
(match-end 2))
3484 ;; When a duration is expected, convert value on the fly.
3487 (let ((v (org-table-get-constant (match-string 1 new
))))
3488 (if (and (org-string-nw-p v
) duration
)
3489 (org-table-time-string-to-seconds v
)
3492 (setq new
(replace-match
3493 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3494 (if org-table-formula-debug
(propertize new
:orig-formula f
) new
)))
3496 (defun org-table-get-constant (const)
3497 "Find the value for a parameter or constant in a formula.
3498 Parameters get priority."
3499 (or (cdr (assoc const org-table-local-parameters
))
3500 (cdr (assoc const org-table-formula-constants-local
))
3501 (cdr (assoc const org-table-formula-constants
))
3502 (and (fboundp 'constants-get
) (constants-get const
))
3503 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3504 (org-entry-get nil
(substring const
5) 'inherit
))
3507 (defvar org-table-fedit-map
3508 (let ((map (make-sparse-keymap)))
3509 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3510 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3511 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3512 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3513 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3514 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3515 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3516 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3517 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3518 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3519 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3520 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3521 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3522 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3523 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3524 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3525 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3526 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3527 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3528 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3531 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3533 ["Finish and Install" org-table-fedit-finish t
]
3534 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3535 ["Abort" org-table-fedit-abort t
]
3537 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3538 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3540 "Shift Reference at Point"
3541 ["Up" org-table-fedit-ref-up t
]
3542 ["Down" org-table-fedit-ref-down t
]
3543 ["Left" org-table-fedit-ref-left t
]
3544 ["Right" org-table-fedit-ref-right t
]
3546 "Change Test Row for Column Formulas"
3547 ["Up" org-table-fedit-line-up t
]
3548 ["Down" org-table-fedit-line-down t
]
3550 ["Scroll Table Window" org-table-fedit-scroll t
]
3551 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3552 ["Show Table Grid" org-table-fedit-toggle-coordinates
3553 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3554 org-table-overlay-coordinates
)]
3556 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3557 :style toggle
:selected org-table-buffer-is-an
]))
3560 (defvar org-table--fedit-source nil
3561 "Position of the TBLFM line being edited.")
3564 (defun org-table-edit-formulas ()
3565 "Edit the formulas of the current table in a separate buffer."
3567 (let ((at-tblfm (org-at-TBLFM-p)))
3568 (unless (or at-tblfm
(org-at-table-p))
3569 (user-error "Not at a table"))
3571 ;; Move point within the table before analyzing it.
3572 (when at-tblfm
(re-search-backward "^[ \t]*|"))
3573 (org-table-analyze))
3574 (let ((key (org-table-current-field-formula 'key
'noerror
))
3575 (eql (sort (org-table-get-stored-formulas t
(and at-tblfm
(point)))
3576 #'org-table-formula-less-p
))
3577 (pos (point-marker))
3578 (source (copy-marker (line-beginning-position)))
3580 (wc (current-window-configuration))
3581 (sel-win (selected-window))
3582 (titles '((column .
"# Column Formulas\n")
3583 (field .
"# Field and Range Formulas\n")
3584 (named .
"# Named Field Formulas\n"))))
3585 (org-switch-to-buffer-other-window "*Edit Formulas*")
3587 ;; Keep global-font-lock-mode from turning on font-lock-mode
3588 (let ((font-lock-global-modes '(not fundamental-mode
)))
3590 (setq-local font-lock-global-modes
(list 'not major-mode
))
3591 (setq-local org-pos pos
)
3592 (setq-local org-table--fedit-source source
)
3593 (setq-local org-window-configuration wc
)
3594 (setq-local org-selected-window sel-win
)
3595 (use-local-map org-table-fedit-map
)
3596 (add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3597 (easy-menu-add org-table-fedit-menu
)
3598 (setq startline
(org-current-line))
3601 ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry
))
3603 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3605 (title (assq type titles
)))
3607 (unless (bobp) (insert "\n"))
3609 (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3610 (setq titles
(remove title titles
)))
3611 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3613 (if (memq (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3614 (car entry
) " = " (cdr entry
) "\n")))
3615 (remove-text-properties 0 (length s
) '(face nil
) s
)
3617 (when (eq org-table-use-standard-references t
)
3618 (org-table-fedit-toggle-ref-type))
3619 (org-goto-line startline
)
3620 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3621 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3622 See menu for more commands.")))))
3624 (defun org-table-fedit-post-command ()
3625 (when (not (memq this-command
'(lisp-complete-symbol)))
3626 (let ((win (selected-window)))
3628 (ignore-errors (org-table-show-reference))
3629 (select-window win
)))))
3631 (defun org-table-formula-to-user (s)
3632 "Convert a formula from internal to user representation."
3633 (if (eq org-table-use-standard-references t
)
3634 (org-table-convert-refs-to-an s
)
3637 (defun org-table-formula-from-user (s)
3638 "Convert a formula from user to internal representation."
3639 (if org-table-use-standard-references
3640 (org-table-convert-refs-to-rc s
)
3643 (defun org-table-convert-refs-to-rc (s)
3644 "Convert spreadsheet references from A7 to @7$28.
3645 Works for single references, but also for entire formulas and even the
3648 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3651 ;; format match, just advance
3652 (setq start
(match-end 0)))
3653 ((and (> (match-beginning 0) 0)
3654 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3655 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3656 ;; 3.e5 or something like this.
3657 (setq start
(match-end 0)))
3658 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3659 ;; (member (match-string 1 s)
3660 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3662 ;; function name, just advance
3663 (setq start
(match-end 0)))
3665 (setq start
(match-beginning 0)
3667 (if (equal (match-string 2 s
) "&")
3668 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3670 (string-to-number (match-string 2 s
))
3671 (org-letters-to-number (match-string 1 s
))))
3675 (defun org-table-convert-refs-to-an (s)
3676 "Convert spreadsheet references from to @7$28 to AB7.
3677 Works for single references, but also for entire formulas and even the
3679 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3680 (setq s
(replace-match
3682 (org-number-to-letters
3683 (string-to-number (match-string 2 s
)))
3684 (string-to-number (match-string 1 s
)))
3686 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3687 (setq s
(replace-match (concat "\\1"
3688 (org-number-to-letters
3689 (string-to-number (match-string 2 s
))) "&")
3693 (defun org-letters-to-number (s)
3694 "Convert a base 26 number represented by letters into an integer.
3695 For example: AB -> 28."
3698 (while (> (length s
) 0)
3699 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3703 (defun org-number-to-letters (n)
3704 "Convert an integer into a base 26 number represented by letters.
3705 For example: 28 -> AB."
3708 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3712 (defun org-table-time-string-to-seconds (s)
3713 "Convert a time string into numerical duration in seconds.
3714 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3715 If S is a string representing a number, keep this number."
3718 (let (hour minus min sec res
)
3720 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3721 (setq minus
(< 0 (length (match-string 1 s
)))
3722 hour
(string-to-number (match-string 2 s
))
3723 min
(string-to-number (match-string 3 s
))
3724 sec
(string-to-number (match-string 4 s
)))
3726 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3727 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3728 ((and (not (string-match org-ts-regexp-both s
))
3729 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3730 (setq minus
(< 0 (length (match-string 1 s
)))
3731 hour
(string-to-number (match-string 2 s
))
3732 min
(string-to-number (match-string 3 s
)))
3734 (setq res
(- (+ (* hour
3600) (* min
60))))
3735 (setq res
(+ (* hour
3600) (* min
60)))))
3736 (t (setq res
(string-to-number s
))))
3737 (number-to-string res
))))
3739 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3740 "Convert a number of seconds to a time string.
3741 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3742 minutes or seconds."
3743 (let* ((secs0 (abs secs
))
3745 (cond ((eq output-format
'days
)
3746 (format "%.3f" (/ (float secs0
) 86400)))
3747 ((eq output-format
'hours
)
3748 (format "%.2f" (/ (float secs0
) 3600)))
3749 ((eq output-format
'minutes
)
3750 (format "%.1f" (/ (float secs0
) 60)))
3751 ((eq output-format
'seconds
)
3752 (format "%d" secs0
))
3753 (t (format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3754 (if (< secs
0) (concat "-" res
) res
)))
3756 (defun org-table-fedit-convert-buffer (function)
3757 "Convert all references in this buffer, using FUNCTION."
3758 (let ((origin (copy-marker (line-beginning-position))))
3759 (goto-char (point-min))
3761 (insert (funcall function
(buffer-substring (point) (line-end-position))))
3762 (delete-region (point) (line-end-position))
3765 (set-marker origin nil
)))
3767 (defun org-table-fedit-toggle-ref-type ()
3768 "Convert all references in the buffer from B3 to @3$2 and back."
3770 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
3771 (org-table-fedit-convert-buffer
3772 (if org-table-buffer-is-an
3773 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3774 (message "Reference type switched to %s"
3775 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3777 (defun org-table-fedit-ref-up ()
3778 "Shift the reference at point one row/hline up."
3780 (org-table-fedit-shift-reference 'up
))
3781 (defun org-table-fedit-ref-down ()
3782 "Shift the reference at point one row/hline down."
3784 (org-table-fedit-shift-reference 'down
))
3785 (defun org-table-fedit-ref-left ()
3786 "Shift the reference at point one field to the left."
3788 (org-table-fedit-shift-reference 'left
))
3789 (defun org-table-fedit-ref-right ()
3790 "Shift the reference at point one field to the right."
3792 (org-table-fedit-shift-reference 'right
))
3794 (defun org-table-fedit-shift-reference (dir)
3796 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3797 (if (memq dir
'(left right
))
3798 (org-rematch-and-replace 1 (eq dir
'left
))
3799 (user-error "Cannot shift reference in this direction")))
3800 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3801 ;; A B3-like reference
3802 (if (memq dir
'(up down
))
3803 (org-rematch-and-replace 2 (eq dir
'up
))
3804 (org-rematch-and-replace 1 (eq dir
'left
))))
3806 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3807 ;; An internal reference
3808 (if (memq dir
'(up down
))
3809 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3810 (org-rematch-and-replace 5 (eq dir
'left
))))))
3812 (defun org-rematch-and-replace (n &optional decr hline
)
3813 "Re-match the group N, and replace it with the shifted reference."
3814 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3815 (goto-char (match-beginning n
))
3816 (and (looking-at (regexp-quote (match-string n
)))
3817 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3820 (defun org-table-shift-refpart (ref &optional decr hline
)
3821 "Shift a reference part REF.
3822 If DECR is set, decrease the references row/column, else increase.
3823 If HLINE is set, this may be a hline reference, it certainly is not
3824 a translation reference."
3826 (let* ((sign (string-match "^[-+]" ref
)) n
)
3828 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3830 ((and hline
(string-match "^I+" ref
))
3831 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3832 (setq n
(+ n
(if decr -
1 1)))
3833 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3835 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3837 (concat sign
(make-string n ?I
)))
3839 ((string-match "^[0-9]+" ref
)
3840 (setq n
(string-to-number (concat sign ref
)))
3841 (setq n
(+ n
(if decr -
1 1)))
3843 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3844 (number-to-string (max 1 n
))))
3846 ((string-match "^[a-zA-Z]+" ref
)
3847 (org-number-to-letters
3848 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3850 (t (user-error "Cannot shift reference"))))))
3852 (defun org-table-fedit-toggle-coordinates ()
3853 "Toggle the display of coordinates in the referenced table."
3855 (let ((pos (marker-position org-pos
)))
3856 (with-current-buffer (marker-buffer org-pos
)
3859 (org-table-toggle-coordinate-overlays)))))
3861 (defun org-table-fedit-finish (&optional arg
)
3862 "Parse the buffer for formula definitions and install them.
3863 With prefix ARG, apply the new formulas to the table."
3865 (org-table-remove-rectangle-highlight)
3866 (when org-table-use-standard-references
3867 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3868 (setq org-table-buffer-is-an nil
))
3870 (sel-win org-selected-window
)
3871 (source org-table--fedit-source
)
3873 (goto-char (point-min))
3874 (while (re-search-forward
3875 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3877 (let ((var (match-string 1))
3878 (form (org-trim (match-string 3))))
3879 (unless (equal form
"")
3880 (while (string-match "[ \t]*\n[ \t]*" form
)
3881 (setq form
(replace-match " " t t form
)))
3882 (when (assoc var eql
)
3883 (user-error "Double formulas for %s" var
))
3884 (push (cons var form
) eql
))))
3885 (set-window-configuration org-window-configuration
)
3886 (select-window sel-win
)
3888 (org-table-store-formulas eql
)
3889 (set-marker pos nil
)
3890 (set-marker source nil
)
3891 (kill-buffer "*Edit Formulas*")
3893 (org-table-recalculate 'all
)
3894 (message "New formulas installed - press C-u C-c C-c to apply."))))
3896 (defun org-table-fedit-abort ()
3897 "Abort editing formulas, without installing the changes."
3899 (org-table-remove-rectangle-highlight)
3900 (let ((pos org-pos
) (sel-win org-selected-window
))
3901 (set-window-configuration org-window-configuration
)
3902 (select-window sel-win
)
3904 (move-marker pos nil
)
3905 (message "Formula editing aborted without installing changes")))
3907 (defun org-table-fedit-lisp-indent ()
3908 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3910 (let ((pos (point)) beg end ind
)
3911 (beginning-of-line 1)
3913 ((looking-at "[ \t]")
3915 (call-interactively 'lisp-indent-line
))
3916 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3917 ((not (fboundp 'pp-buffer
))
3918 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3919 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3920 (goto-char (- (match-end 0) 2))
3922 (setq ind
(make-string (current-column) ?\
))
3923 (condition-case nil
(forward-sexp 1)
3925 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3928 (narrow-to-region beg end
)
3929 (if (eq last-command this-command
)
3931 (goto-char (point-min))
3932 (setq this-command nil
)
3933 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3934 (replace-match " ")))
3936 (untabify (point-min) (point-max))
3937 (goto-char (1+ (point-min)))
3938 (while (re-search-forward "^." nil t
)
3939 (beginning-of-line 1)
3941 (goto-char (point-max))
3942 (org-delete-backward-char 1)))
3946 (defvar org-show-positions nil
)
3948 (defun org-table-show-reference (&optional local
)
3949 "Show the location/value of the $ expression at point.
3950 When LOCAL is non-nil, show references for the table at point."
3952 (org-table-remove-rectangle-highlight)
3953 (when local
(org-table-analyze))
3955 (let ((pos (if local
(point) org-pos
))
3957 (org-inhibit-highlight-removal t
)
3958 (win (selected-window))
3959 (org-show-positions nil
)
3960 var name e what match dest
)
3962 ((org-in-regexp "^@[0-9]+[ \t=]")
3963 (setq match
(concat (substring (match-string 0) 0 -
1)
3965 (substring (match-string 0) 0 -
1)
3968 ((or (org-in-regexp org-table-range-regexp2
)
3969 (org-in-regexp org-table-translate-regexp
)
3970 (org-in-regexp org-table-range-regexp
))
3973 (org-table-convert-refs-to-rc (match-string 0))))
3975 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3976 ((org-in-regexp "\\$[0-9]+") 'column
)
3978 (t (user-error "No reference at point")))
3979 match
(and what
(or match
(match-string 0))))
3980 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3981 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3982 'secondary-selection
))
3983 (add-hook 'before-change-functions
3984 #'org-table-remove-rectangle-highlight
)
3985 (when (eq what
'name
) (setq var
(substring match
1)))
3986 (when (eq what
'range
)
3987 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3988 (setq match
(org-table-formula-substitute-names match
)))
3992 (re-search-backward "^\\S-" nil t
)
3994 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3995 \\([0-9]+\\|&\\)\\) *=")
3998 (org-table-convert-refs-to-rc (match-string 1))))
3999 (org-table-add-rectangle-overlay
4000 (match-beginning 1) (match-end 1) face2
))))
4001 (if (and (markerp pos
) (marker-buffer pos
))
4002 (if (get-buffer-window (marker-buffer pos
))
4003 (select-window (get-buffer-window (marker-buffer pos
)))
4004 (org-switch-to-buffer-other-window (get-buffer-window
4005 (marker-buffer pos
)))))
4007 (org-table-force-dataline)
4009 (if local org-table-current-begin-pos
(org-table-begin))))
4011 (setq name
(substring dest
1))
4013 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
4014 (org-table-goto-field dest
))
4015 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4017 (org-table-goto-field dest
))
4018 (t (org-table-goto-column (string-to-number name
))))
4019 (move-marker pos
(point))
4020 (org-table-highlight-rectangle nil nil face2
))
4022 ((equal dest match
))
4025 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
4026 ((setq e
(assoc var org-table-named-field-locations
))
4027 (org-table-goto-field var
)
4028 (org-table-highlight-rectangle)
4029 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
4030 ((setq e
(assoc var org-table-column-names
))
4031 (org-table-goto-column (string-to-number (cdr e
)))
4032 (org-table-highlight-rectangle)
4033 (goto-char table-start
)
4034 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
4037 (goto-char (match-beginning 1))
4038 (org-table-highlight-rectangle)
4039 (message "Named column (column %s)" (cdr e
)))
4040 (user-error "Column name not found")))
4043 (org-table-goto-column (string-to-number (substring match
1)))
4044 (org-table-highlight-rectangle)
4045 (message "Column %s" (substring match
1)))
4046 ((setq e
(assoc var org-table-local-parameters
))
4047 (goto-char table-start
)
4048 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
4050 (goto-char (match-beginning 1))
4051 (org-table-highlight-rectangle)
4052 (message "Local parameter."))
4053 (user-error "Parameter not found")))
4054 ((not var
) (user-error "No reference at point"))
4055 ((setq e
(assoc var org-table-formula-constants-local
))
4056 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4058 ((setq e
(assoc var org-table-formula-constants
))
4059 (message "Constant: $%s=%s in `org-table-formula-constants'."
4061 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4062 (message "Constant: $%s=%s, from `constants.el'%s."
4063 var e
(format " (%s units)" constants-unit-system
)))
4064 (t (user-error "Undefined name $%s" var
)))
4066 (when (and org-show-positions
4067 (not (memq this-command
'(org-table-fedit-scroll
4068 org-table-fedit-scroll-down
))))
4069 (push pos org-show-positions
)
4070 (push table-start org-show-positions
)
4071 (let ((min (apply 'min org-show-positions
))
4072 (max (apply 'max org-show-positions
)))
4073 (set-window-start (selected-window) min
)
4075 (or (pos-visible-in-window-p max
)
4076 (set-window-start (selected-window) max
)))))
4077 (select-window win
))))
4079 (defun org-table-force-dataline ()
4080 "Make sure the cursor is in a dataline in a table."
4081 (unless (save-excursion
4082 (beginning-of-line 1)
4083 (looking-at org-table-dataline-regexp
))
4084 (let* ((re org-table-dataline-regexp
)
4085 (p1 (save-excursion (re-search-forward re nil
'move
)))
4086 (p2 (save-excursion (re-search-backward re nil
'move
))))
4088 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4090 ((or p1 p2
) (goto-char (or p1 p2
)))
4091 (t (user-error "No table dataline around here"))))))
4093 (defun org-table-fedit-line-up ()
4094 "Move cursor one line up in the window showing the table."
4096 (org-table-fedit-move 'previous-line
))
4098 (defun org-table-fedit-line-down ()
4099 "Move cursor one line down in the window showing the table."
4101 (org-table-fedit-move 'next-line
))
4103 (defun org-table-fedit-move (command)
4104 "Move the cursor in the window showing the table.
4105 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4106 (let ((org-table-allow-automatic-line-recalculation nil
)
4107 (pos org-pos
) (win (selected-window)) p
)
4108 (select-window (get-buffer-window (marker-buffer org-pos
)))
4110 (call-interactively command
)
4111 (while (and (org-at-table-p)
4112 (org-at-table-hline-p))
4113 (call-interactively command
))
4114 (or (org-at-table-p) (goto-char p
))
4115 (move-marker pos
(point))
4116 (select-window win
)))
4118 (defun org-table-fedit-scroll (N)
4120 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4121 (scroll-other-window N
)))
4123 (defun org-table-fedit-scroll-down (N)
4125 (org-table-fedit-scroll (- N
)))
4127 (defvar org-table-rectangle-overlays nil
)
4129 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4130 "Add a new overlay."
4131 (let ((ov (make-overlay beg end
)))
4132 (overlay-put ov
'face
(or face
'secondary-selection
))
4133 (push ov org-table-rectangle-overlays
)))
4135 (defun org-table-highlight-rectangle (&optional beg end face
)
4136 "Highlight rectangular region in a table.
4137 When buffer positions BEG and END are provided, use them to
4138 delimit the region to highlight. Otherwise, refer to point. Use
4139 FACE, when non-nil, for the highlight."
4140 (let* ((beg (or beg
(point)))
4141 (end (or end
(point)))
4147 (cons (line-beginning-position) (org-table-current-column))))
4151 (cons (line-beginning-position) (org-table-current-column)))))
4152 (when (boundp 'org-show-positions
)
4153 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4154 (goto-char (car start-coordinates
))
4155 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
4156 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
4157 (last-row (car end-coordinates
)))
4158 (while (<= (point) last-row
)
4159 (when (looking-at org-table-dataline-regexp
)
4160 (org-table-goto-column column-start
)
4161 (skip-chars-backward "^|\n")
4163 (org-table-goto-column column-end
)
4164 (skip-chars-forward "^|\n")
4165 (org-table-add-rectangle-overlay p
(point) face
)))
4167 (goto-char (car start-coordinates
)))
4168 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
4170 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
4171 "Remove the rectangle overlays."
4172 (unless org-inhibit-highlight-removal
4173 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4174 (mapc 'delete-overlay org-table-rectangle-overlays
)
4175 (setq org-table-rectangle-overlays nil
)))
4177 (defvar-local org-table-coordinate-overlays nil
4178 "Collects the coordinate grid overlays, so that they can be removed.")
4180 (defun org-table-overlay-coordinates ()
4181 "Add overlays to the table at point, to show row/column coordinates."
4183 (mapc 'delete-overlay org-table-coordinate-overlays
)
4184 (setq org-table-coordinate-overlays nil
)
4186 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4187 (goto-char (org-table-begin))
4188 (while (org-at-table-p)
4189 (setq eol
(point-at-eol))
4190 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4191 (push ov org-table-coordinate-overlays
)
4192 (setq hline
(looking-at org-table-hline-regexp
))
4193 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4194 (format "%4d" (setq id
(1+ id
)))))
4195 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4198 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4199 (setq beg
(1+ (match-beginning 0))
4201 s1
(concat "$" (int-to-string ic
))
4202 s2
(org-number-to-letters ic
)
4203 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4204 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4205 (push ov org-table-coordinate-overlays
)
4206 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4207 (beginning-of-line 2)))))
4210 (defun org-table-toggle-coordinate-overlays ()
4211 "Toggle the display of Row/Column numbers in tables."
4213 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4214 (message "Tables Row/Column numbers display turned %s"
4215 (if org-table-overlay-coordinates
"on" "off"))
4216 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4218 (unless org-table-overlay-coordinates
4219 (mapc 'delete-overlay org-table-coordinate-overlays
)
4220 (setq org-table-coordinate-overlays nil
)))
4223 (defun org-table-toggle-formula-debugger ()
4224 "Toggle the formula debugger in tables."
4226 (setq org-table-formula-debug
(not org-table-formula-debug
))
4227 (message "Formula debugging has been turned %s"
4228 (if org-table-formula-debug
"on" "off")))
4230 ;;; The orgtbl minor mode
4232 ;; Define a minor mode which can be used in other modes in order to
4233 ;; integrate the Org table editor.
4235 ;; This is really a hack, because the Org table editor uses several
4236 ;; keys which normally belong to the major mode, for example the TAB
4237 ;; and RET keys. Here is how it works: The minor mode defines all the
4238 ;; keys necessary to operate the table editor, but wraps the commands
4239 ;; into a function which tests if the cursor is currently inside
4240 ;; a table. If that is the case, the table editor command is
4241 ;; executed. However, when any of those keys is used outside a table,
4242 ;; the function uses `key-binding' to look up if the key has an
4243 ;; associated command in another currently active keymap (minor modes,
4244 ;; major mode, global), and executes that command. There might be
4245 ;; problems if any of the keys used by the table editor is otherwise
4246 ;; used as a prefix key.
4248 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4249 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4250 ;; addresses this by checking explicitly for both bindings.
4252 ;; The optimized version (see variable `orgtbl-optimized') takes over
4253 ;; all keys which are bound to `self-insert-command' in the *global map*.
4254 ;; Some modes bind other commands to simple characters, for example
4255 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4256 ;; active, this binding is ignored inside tables and replaced with a
4257 ;; modified self-insert.
4260 (defvar orgtbl-mode-map
(make-keymap)
4261 "Keymap for `orgtbl-mode'.")
4263 (defvar org-old-auto-fill-inhibit-regexp nil
4264 "Local variable used by `orgtbl-mode'.")
4266 (defconst orgtbl-line-start-regexp
4267 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4268 "Matches a line belonging to an orgtbl.")
4270 (defconst orgtbl-extra-font-lock-keywords
4271 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4272 0 (quote 'org-table
) 'prepend
))
4273 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4275 ;; Install it as a minor mode.
4276 (put 'orgtbl-mode
:included t
)
4277 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4280 (define-minor-mode orgtbl-mode
4281 "The `org-mode' table editor as a minor mode for use in other modes."
4282 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4283 (org-load-modules-maybe)
4285 ((derived-mode-p 'org-mode
)
4286 ;; Exit without error, in case some hook functions calls this
4287 ;; by accident in org-mode.
4288 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4290 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4291 ;; Make sure we are first in minor-mode-map-alist
4292 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4293 ;; FIXME: maybe it should use emulation-mode-map-alists?
4294 (and c
(setq minor-mode-map-alist
4295 (cons c
(delq c minor-mode-map-alist
)))))
4296 (setq-local org-table-may-need-update t
)
4297 (add-hook 'before-change-functions
'org-before-change-function
4299 (setq-local org-old-auto-fill-inhibit-regexp
4300 auto-fill-inhibit-regexp
)
4301 (setq-local auto-fill-inhibit-regexp
4302 (if auto-fill-inhibit-regexp
4303 (concat orgtbl-line-start-regexp
"\\|"
4304 auto-fill-inhibit-regexp
)
4305 orgtbl-line-start-regexp
))
4306 (add-to-invisibility-spec '(org-cwidth))
4307 (when (fboundp 'font-lock-add-keywords
)
4308 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4309 (org-restart-font-lock))
4310 (easy-menu-add orgtbl-mode-menu
))
4312 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4313 (org-table-cleanup-narrow-column-properties)
4314 (org-remove-from-invisibility-spec '(org-cwidth))
4315 (remove-hook 'before-change-functions
'org-before-change-function t
)
4316 (when (fboundp 'font-lock-remove-keywords
)
4317 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4318 (org-restart-font-lock))
4319 (easy-menu-remove orgtbl-mode-menu
)
4320 (force-mode-line-update 'all
))))
4322 (defun org-table-cleanup-narrow-column-properties ()
4323 "Remove all properties related to narrow-column invisibility."
4324 (let ((s (point-min)))
4325 (while (setq s
(text-property-any s
(point-max)
4326 'display org-narrow-column-arrow
))
4327 (remove-text-properties s
(1+ s
) '(display t
)))
4328 (setq s
(point-min))
4329 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4330 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4331 (setq s
(point-min))
4332 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4333 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4335 (defun orgtbl-make-binding (fun n
&rest keys
)
4336 "Create a function for binding in the table minor mode.
4337 FUN is the command to call inside a table. N is used to create a unique
4338 command name. KEYS are keys that should be checked in for a command
4339 to execute outside of tables."
4342 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4344 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4345 "Outside of tables, run the binding of `"
4346 (mapconcat #'key-description keys
"' or `")
4351 (list 'call-interactively
(list 'quote fun
))
4352 (list 'let
'(orgtbl-mode)
4353 (list 'call-interactively
4356 (list 'key-binding k
))
4358 '('orgtbl-error
))))))))
4360 (defun orgtbl-error ()
4361 "Error when there is no default binding for a table key."
4363 (user-error "This key has no function outside tables"))
4365 (defun orgtbl-setup ()
4366 "Setup orgtbl keymaps."
4369 '(([(meta shift left
)] org-table-delete-column
)
4370 ([(meta left
)] org-table-move-column-left
)
4371 ([(meta right
)] org-table-move-column-right
)
4372 ([(meta shift right
)] org-table-insert-column
)
4373 ([(meta shift up
)] org-table-kill-row
)
4374 ([(meta shift down
)] org-table-insert-row
)
4375 ([(meta up
)] org-table-move-row-up
)
4376 ([(meta down
)] org-table-move-row-down
)
4377 ("\C-c\C-w" org-table-cut-region
)
4378 ("\C-c\M-w" org-table-copy-region
)
4379 ("\C-c\C-y" org-table-paste-rectangle
)
4380 ("\C-c\C-w" org-table-wrap-region
)
4381 ("\C-c-" org-table-insert-hline
)
4382 ("\C-c}" org-table-toggle-coordinate-overlays
)
4383 ("\C-c{" org-table-toggle-formula-debugger
)
4384 ("\C-m" org-table-next-row
)
4385 ([(shift return
)] org-table-copy-down
)
4386 ("\C-c?" org-table-field-info
)
4387 ("\C-c " org-table-blank-field
)
4388 ("\C-c+" org-table-sum
)
4389 ("\C-c=" org-table-eval-formula
)
4390 ("\C-c'" org-table-edit-formulas
)
4391 ("\C-c`" org-table-edit-field
)
4392 ("\C-c*" org-table-recalculate
)
4393 ("\C-c^" org-table-sort-lines
)
4394 ("\M-a" org-table-beginning-of-field
)
4395 ("\M-e" org-table-end-of-field
)
4396 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4398 (while (setq elt
(pop bindings
))
4399 (setq nfunc
(1+ nfunc
))
4400 (setq key
(org-key (car elt
))
4402 cmd
(orgtbl-make-binding fun nfunc key
))
4403 (org-defkey orgtbl-mode-map key cmd
))
4405 ;; Special treatment needed for TAB, RET and DEL
4406 (org-defkey orgtbl-mode-map
[(return)]
4407 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4408 (org-defkey orgtbl-mode-map
"\C-m"
4409 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4410 (org-defkey orgtbl-mode-map
[(tab)]
4411 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4412 (org-defkey orgtbl-mode-map
"\C-i"
4413 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4414 (org-defkey orgtbl-mode-map
[(shift tab
)]
4415 (orgtbl-make-binding 'org-table-previous-field
104
4416 [(shift tab
)] [(tab)] "\C-i"))
4417 (org-defkey orgtbl-mode-map
[backspace]
4418 (orgtbl-make-binding 'org-delete-backward-char 109
4419 [backspace] (kbd "DEL")))
4421 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4422 (orgtbl-make-binding 'org-table-previous-field
107
4423 [S-iso-lefttab
] [backtab] [(shift tab)]
4426 (org-defkey orgtbl-mode-map [backtab]
4427 (orgtbl-make-binding 'org-table-previous-field
108
4428 [backtab] [S-iso-lefttab] [(shift tab)]
4431 (org-defkey orgtbl-mode-map "\M-\C-m"
4432 (orgtbl-make-binding 'org-table-wrap-region 105
4433 "\M-\C-m" [(meta return)]))
4434 (org-defkey orgtbl-mode-map [(meta return)]
4435 (orgtbl-make-binding 'org-table-wrap-region 106
4436 [(meta return)] "\M-\C-m"))
4438 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4439 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4441 (when orgtbl-optimized
4442 ;; If the user wants maximum table support, we need to hijack
4443 ;; some standard editing functions
4444 (org-remap orgtbl-mode-map
4445 'self-insert-command 'orgtbl-self-insert-command
4446 'delete-char 'org-delete-char
4447 'delete-backward-char 'org-delete-backward-char)
4448 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4449 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4451 ["Create or convert" org-table-create-or-convert-from-region
4452 :active (not (org-at-table-p)) :keys "C-c |" ]
4454 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4455 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4456 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4457 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4459 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4460 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4461 ["Copy Field from Above"
4462 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4465 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4466 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4467 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4468 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4470 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4471 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4472 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4473 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4474 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4476 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4478 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4479 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4480 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4481 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4484 ["Insert table template" orgtbl-insert-radio-table
4485 (assq major-mode orgtbl-radio-table-templates)]
4486 ["Comment/uncomment table" orgtbl-toggle-comment t])
4488 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4489 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4490 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4491 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4492 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4493 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4494 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4495 ["Sum Column/Rectangle" org-table-sum
4496 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4497 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4499 org-table-toggle-formula-debugger :active (org-at-table-p)
4501 :style toggle :selected org-table-formula-debug]
4502 ["Show Col/Row Numbers"
4503 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4505 :style toggle :selected org-table-overlay-coordinates]
4508 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4509 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4512 (defun orgtbl-ctrl-c-ctrl-c (arg)
4513 "If the cursor is inside a table, realign the table.
4514 If it is a table to be sent away to a receiver, do it.
4515 With prefix arg, also recompute table."
4517 (let ((case-fold-search t) (pos (point)) action)
4519 (beginning-of-line 1)
4521 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4522 ((looking-at "[ \t]*|") pos)
4523 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4527 (org-table-maybe-eval-formula)
4529 (call-interactively 'org-table-recalculate)
4530 (org-table-maybe-recalculate-line))
4531 (call-interactively 'org-table-align)
4532 (when (orgtbl-send-table 'maybe)
4533 (run-hooks 'orgtbl-after-send-table-hook)))
4534 ((eq action 'recalc)
4536 (beginning-of-line 1)
4537 (skip-chars-backward " \r\n\t")
4538 (if (org-at-table-p)
4539 (org-call-with-arg 'org-table-recalculate t))))
4540 (t (let (orgtbl-mode)
4541 (call-interactively (key-binding "\C-c\C-c")))))))
4543 (defun orgtbl-create-or-convert-from-region (_arg)
4544 "Create table or convert region to table, if no conflicting binding.
4545 This installs the table binding `C-c |', but only if there is no
4546 conflicting binding to this key outside orgtbl-mode."
4548 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4550 (call-interactively cmd)
4551 (call-interactively 'org-table-create-or-convert-from-region))))
4553 (defun orgtbl-tab (arg)
4554 "Justification and field motion for `orgtbl-mode'."
4556 (if arg (org-table-edit-field t)
4557 (org-table-justify-field-maybe)
4558 (org-table-next-field)))
4560 (defun orgtbl-ret ()
4561 "Justification and field motion for `orgtbl-mode'."
4565 (org-table-justify-field-maybe)
4566 (org-table-next-row)))
4568 (defun orgtbl-self-insert-command (N)
4569 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4570 If the cursor is in a table looking at whitespace, the whitespace is
4571 overwritten, and the table is not marked as requiring realignment."
4573 (if (and (org-at-table-p)
4575 (and org-table-auto-blank-field
4576 (member last-command
4577 '(orgtbl-hijacker-command-100
4578 orgtbl-hijacker-command-101
4579 orgtbl-hijacker-command-102
4580 orgtbl-hijacker-command-103
4581 orgtbl-hijacker-command-104
4582 orgtbl-hijacker-command-105
4584 (org-table-blank-field))
4587 (looking-at "[^|\n]* \\( \\)|"))
4588 (let (org-table-may-need-update)
4589 (delete-region (match-beginning 1) (match-end 1))
4590 (self-insert-command N))
4591 (setq org-table-may-need-update t)
4594 (cmd (or (key-binding
4595 (or (and (listp function-key-map)
4596 (setq a (assoc last-input-event function-key-map))
4598 (vector last-input-event)))
4599 'self-insert-command)))
4600 (call-interactively cmd)
4601 (if (and org-self-insert-cluster-for-undo
4602 (eq cmd 'self-insert-command))
4603 (if (not (eq last-command 'orgtbl-self-insert-command))
4604 (setq org-self-insert-command-undo-counter 1)
4605 (if (>= org-self-insert-command-undo-counter 20)
4606 (setq org-self-insert-command-undo-counter 1)
4607 (and (> org-self-insert-command-undo-counter 0)
4609 (not (cadr buffer-undo-list)) ; remove nil entry
4610 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4611 (setq org-self-insert-command-undo-counter
4612 (1+ org-self-insert-command-undo-counter))))))))
4615 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4616 "Regular expression matching exponentials as produced by calc.")
4618 (defun orgtbl-gather-send-defs ()
4619 "Gather a plist of :name, :transform, :params for each destination before
4622 (goto-char (org-table-begin))
4624 (beginning-of-line 0)
4625 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4626 (let ((name (org-no-properties (match-string 1)))
4627 (transform (intern (match-string 2)))
4628 (params (if (match-end 3)
4629 (read (concat "(" (match-string 3) ")")))))
4630 (push (list :name name :transform transform :params params)
4632 (beginning-of-line 0)))
4635 (defun orgtbl-send-replace-tbl (name text)
4636 "Find and replace table NAME with TEXT."
4638 (goto-char (point-min))
4639 (let* ((location-flag nil)
4640 (name (regexp-quote name))
4641 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
4642 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
4643 (while (re-search-forward begin-re nil t)
4644 (unless location-flag (setq location-flag t))
4645 (let ((beg (line-beginning-position 2)))
4646 (unless (re-search-forward end-re nil t)
4647 (user-error "Cannot find end of receiver location at %d" beg))
4649 (delete-region beg (point))
4650 (insert text "\n")))
4651 (unless location-flag
4652 (user-error "No valid receiver location found in the buffer")))))
4655 (defun org-table-to-lisp (&optional txt)
4656 "Convert the table at point to a Lisp structure.
4657 The structure will be a list. Each item is either the symbol `hline'
4658 for a horizontal separator line, or a list of field values as strings.
4659 The table is taken from the parameter TXT, or from the buffer at point."
4660 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4662 (buffer-substring-no-properties (org-table-begin)
4665 (if (string-match org-table-hline-regexp x) 'hline
4666 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4667 (org-split-string txt "[ \t]*\n[ \t]*"))))
4669 (defun orgtbl-send-table (&optional maybe)
4670 "Send a transformed version of table at point to the receiver position.
4671 With argument MAYBE, fail quietly if no transformation is defined
4675 (unless (org-at-table-p) (user-error "Not at a table"))
4676 ;; when non-interactive, we assume align has just happened.
4677 (when (called-interactively-p 'any) (org-table-align))
4678 (let ((dests (orgtbl-gather-send-defs))
4679 (table (org-table-to-lisp
4680 (buffer-substring-no-properties (org-table-begin)
4684 (if maybe (throw 'exit nil)
4685 (user-error "Don't know how to transform this table")))
4686 (dolist (dest dests)
4687 (let ((name (plist-get dest :name))
4688 (transform (plist-get dest :transform))
4689 (params (plist-get dest :params)))
4690 (unless (fboundp transform)
4691 (user-error "No such transformation function %s" transform))
4692 (orgtbl-send-replace-tbl name (funcall transform table params)))
4694 (message "Table converted and installed at %d receiver location%s"
4695 ntbl (if (> ntbl 1) "s" ""))
4696 (and (> ntbl 0) ntbl))))
4698 (defun org-remove-by-index (list indices &optional i0)
4699 "Remove the elements in LIST with indices in INDICES.
4700 First element has index 0, or I0 if given."
4703 (if (integerp indices) (setq indices (list indices)))
4704 (setq i0 (1- (or i0 0)))
4705 (delq :rm (mapcar (lambda (x)
4707 (if (memq i0 indices) :rm x))
4710 (defun orgtbl-toggle-comment ()
4711 "Comment or uncomment the orgtbl at point."
4713 (let* ((case-fold-search t)
4714 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4715 (re2 (concat "^" orgtbl-line-start-regexp))
4716 (commented (save-excursion (beginning-of-line 1)
4717 (cond ((looking-at re1) t)
4718 ((looking-at re2) nil)
4719 (t (user-error "Not at an org table")))))
4720 (re (if commented re1 re2))
4723 (beginning-of-line 1)
4724 (while (looking-at re) (beginning-of-line 0))
4725 (beginning-of-line 2)
4727 (while (looking-at re) (beginning-of-line 2))
4729 (comment-region beg end (if commented '(4) nil))))
4731 (defun orgtbl-insert-radio-table ()
4732 "Insert a radio table template appropriate for this major mode."
4734 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4737 (unless e (user-error "No radio table setup defined for %s" major-mode))
4738 (setq name (read-string "Table name: "))
4739 (while (string-match "%n" txt)
4740 (setq txt (replace-match name t t txt)))
4741 (or (bolp) (insert "\n"))
4747 (defun orgtbl-to-generic (table params)
4748 "Convert the orgtbl-mode TABLE to some other format.
4750 This generic routine can be used for many standard cases.
4752 TABLE is a list, each entry either the symbol `hline' for
4753 a horizontal separator line, or a list of fields for that
4754 line. PARAMS is a property list of parameters that can
4755 influence the conversion.
4757 Valid parameters are:
4761 Export back-end used as a basis to transcode elements of the
4762 table, when no specific parameter applies to it. It is also
4763 used to translate cells contents. You can prevent this by
4764 setting :raw property to a non-nil value.
4768 When non-nil, only convert rows, not the table itself. This is
4769 equivalent to setting to the empty string both :tstart
4770 and :tend, which see.
4774 When set to an integer N, skip the first N lines of the table.
4775 Horizontal separation lines do count for this parameter!
4779 List of columns that should be skipped. If the table has
4780 a column with calculation marks, that column is automatically
4781 discarded beforehand.
4785 String to be inserted on horizontal separation lines. May be
4786 nil to ignore these lines altogether.
4790 Separator between two fields, as a string.
4792 Each in the following group may be either a string or a function
4793 of no arguments returning a string:
4797 Strings to start and end the table. Ignored when :splice is t.
4801 Strings to start and end a new table line.
4805 Strings to start and end the last table line. Default,
4806 respectively, to :lstart and :lend.
4808 Each in the following group may be a string or a function of one
4809 argument (either the cells in the current row, as a list of
4810 strings, or the current cell) returning a string:
4814 Format string for an entire row, with enough %s to capture all
4815 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4819 Format for the entire last line, defaults to :lfmt.
4823 A format to be used to wrap the field, should contain %s for
4824 the original field value. For example, to wrap everything in
4825 dollars, you could use :fmt \"$%s$\". This may also be
4826 a property list with column numbers and format strings, or
4829 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4831 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4833 Same as above, specific for the header lines in the table.
4834 All lines before the first hline are treated as header. If
4835 any of these is not present, the data line value is used.
4837 This may be either a string or a function of two arguments:
4841 Use this format to print numbers with exponential. The format
4842 should have %s twice for inserting mantissa and exponent, for
4843 example \"%s\\\\times10^{%s}\". This may also be a property
4844 list with column numbers and format strings or functions.
4845 :fmt will still be applied after :efmt."
4846 ;; Make sure `org-export-create-backend' is available.
4848 (let* ((backend (plist-get params :backend))
4850 ;; Build a custom back-end according to PARAMS. Before
4851 ;; defining a translator, check if there is anything to do.
4852 ;; When there isn't, let BACKEND handle the element.
4853 (org-export-create-backend
4854 :parent (or backend 'org)
4856 `((table . ,(org-table--to-generic-table params))
4857 (table-row . ,(org-table--to-generic-row params))
4858 (table-cell . ,(org-table--to-generic-cell params))
4859 ;; Macros are not going to be expanded. However, no
4860 ;; regular back-end has a transcoder for them. We
4861 ;; provide one so they are not ignored, but displayed
4863 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4865 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4866 ;; Initialize communication channel in INFO.
4868 (let ((org-inhibit-startup t)) (org-mode))
4869 (let ((standard-output (current-buffer))
4870 (org-element-use-cache nil))
4872 (cond ((eq e 'hline) (princ "|--\n"))
4874 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4876 ;; Add back-end specific filters, but not user-defined ones. In
4877 ;; particular, make sure to call parse-tree filters on the
4880 (let ((org-export-filters-alist nil))
4881 (org-export-install-filters
4883 (org-export-get-environment backend nil params)
4884 `(:back-end ,(org-export-get-backend backend))))))
4886 (org-export-filter-apply-functions
4887 (plist-get info :filter-parse-tree)
4888 (org-element-map (org-element-parse-buffer) 'table
4891 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4892 (user-error "Unknown :backend value"))
4893 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4894 ;; Handle :skip parameter.
4895 (let ((skip (plist-get info :skip)))
4897 (unless (wholenump skip) (user-error "Wrong :skip value"))
4899 (org-element-map data 'table-row
4902 (org-element-extract-element row)
4906 ;; Handle :skipcols parameter.
4907 (let ((skipcols (plist-get info :skipcols)))
4909 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4910 (org-element-map data 'table
4912 (let ((specialp (org-export-table-has-special-column-p table)))
4913 (dolist (row (org-element-contents table))
4914 (when (eq (org-element-property :type row) 'standard)
4916 (dolist (cell (nthcdr (if specialp 1 0)
4917 (org-element-contents row)))
4918 (when (memq c skipcols)
4919 (org-element-extract-element cell))
4920 (cl-incf c))))))))))
4921 ;; Since we are going to export using a low-level mechanism,
4922 ;; ignore special column and special rows manually.
4923 (let ((special? (org-export-table-has-special-column-p data))
4925 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4927 (when (if (eq (org-element-type datum) 'table-row)
4928 (org-export-table-row-is-special-p datum nil)
4929 (org-export-first-sibling-p datum nil))
4930 (push datum ignore))))
4931 (setq info (plist-put info :ignore-list ignore)))
4932 ;; We use a low-level mechanism to export DATA so as to skip all
4933 ;; usual pre-processing and post-processing, i.e., hooks, Babel
4934 ;; code evaluation, include keywords and macro expansion. Only
4935 ;; back-end specific filters are retained.
4936 (let ((output (org-export-data-with-backend data custom-backend info)))
4937 ;; Remove final newline.
4938 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4940 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4941 (cond ((null value) nil)
4942 ((functionp value) `(funcall ',value ,@args))
4944 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4945 (args `(format ,value ,@args))
4947 ((and with-cons (consp value))
4948 `(let ((val (cadr (memq column ',value))))
4949 (cond ((null val) contents)
4950 ((stringp val) (format val ,@args))
4951 ((functionp val) (funcall val ,@args))
4952 (t (user-error "Wrong %s value" ,name)))))
4953 (t (user-error "Wrong %s value" name))))
4955 (defun org-table--to-generic-table (params)
4956 "Return custom table transcoder according to PARAMS.
4957 PARAMS is a plist. See `orgtbl-to-generic' for more
4959 (let ((backend (plist-get params :backend))
4960 (splice (plist-get params :splice))
4961 (tstart (plist-get params :tstart))
4962 (tend (plist-get params :tend)))
4963 `(lambda (table contents info)
4965 ,(and tstart (not splice)
4966 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4967 ,(if (or (not backend) tstart tend splice) 'contents
4968 `(org-export-with-backend ',backend table contents info))
4969 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4971 (defun org-table--to-generic-row (params)
4972 "Return custom table row transcoder according to PARAMS.
4973 PARAMS is a plist. See `orgtbl-to-generic' for more
4975 (let* ((backend (plist-get params :backend))
4976 (lstart (plist-get params :lstart))
4977 (llstart (plist-get params :llstart))
4978 (hlstart (plist-get params :hlstart))
4979 (hllstart (plist-get params :hllstart))
4980 (lend (plist-get params :lend))
4981 (llend (plist-get params :llend))
4982 (hlend (plist-get params :hlend))
4983 (hllend (plist-get params :hllend))
4984 (lfmt (plist-get params :lfmt))
4985 (llfmt (plist-get params :llfmt))
4986 (hlfmt (plist-get params :hlfmt))
4987 (hllfmt (plist-get params :hllfmt)))
4988 `(lambda (row contents info)
4989 (if (eq (org-element-property :type row) 'rule)
4991 ((plist-member params :hline)
4992 (org-table--generic-apply (plist-get params :hline) ":hline"))
4993 (backend `(org-export-with-backend ',backend row nil info)))
4994 (let ((headerp ,(and (or hlfmt hlstart hlend)
4995 '(org-export-table-row-in-header-p row info)))
4997 ,(and (or hllfmt hllstart hllend)
4998 '(org-export-table-row-ends-header-p row info)))
4999 (lastp (not (org-export-get-next-element row info))))
5001 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5002 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5003 ;; `:lstart', `:lend' and their relatives.
5005 '(org-element-map row 'table-cell
5007 ;; Export all cells, without separators.
5009 ;; Use `org-export-data-with-backend'
5010 ;; instead of `org-export-data' to eschew
5011 ;; cached values, which
5012 ;; ignore :orgtbl-ignore-sep parameter.
5013 (org-export-data-with-backend
5015 (plist-get info :back-end)
5016 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5020 `(last-header-p ,(org-table--generic-apply
5021 hllfmt ":hllfmt" nil cells)))
5023 `(headerp ,(org-table--generic-apply
5024 hlfmt ":hlfmt" nil cells)))
5026 `(lastp ,(org-table--generic-apply
5027 llfmt ":llfmt" nil cells)))
5029 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5033 (or hllstart hllend)
5036 ,(org-table--generic-apply hllstart ":hllstart")
5038 ,(org-table--generic-apply hllend ":hllend"))))
5043 ,(org-table--generic-apply hlstart ":hlstart")
5045 ,(org-table--generic-apply hlend ":hlend"))))
5050 ,(org-table--generic-apply llstart ":llstart")
5052 ,(org-table--generic-apply llend ":llend"))))
5057 ,(org-table--generic-apply lstart ":lstart")
5059 ,(org-table--generic-apply lend ":lend")))
5061 `(org-export-with-backend
5062 ',backend row contents info))
5063 (t 'contents)))))))))))))))
5065 (defun org-table--to-generic-cell (params)
5066 "Return custom table cell transcoder according to PARAMS.
5067 PARAMS is a plist. See `orgtbl-to-generic' for more
5069 (let* ((backend (plist-get params :backend))
5070 (efmt (plist-get params :efmt))
5071 (fmt (plist-get params :fmt))
5072 (hfmt (plist-get params :hfmt))
5073 (sep (plist-get params :sep))
5074 (hsep (plist-get params :hsep)))
5075 `(lambda (cell contents info)
5076 ;; Make sure that contents are exported as Org data when :raw
5077 ;; parameter is non-nil.
5078 ,(when (and backend (plist-get params :raw))
5080 ;; Since we don't know what are the pseudo object
5081 ;; types defined in backend, we cannot pass them to
5082 ;; `org-element-interpret-data'. As a consequence,
5083 ;; they will be treated as pseudo elements, and will
5084 ;; have newlines appended instead of spaces.
5085 ;; Therefore, we must make sure :post-blank value is
5086 ;; really turned into spaces.
5087 (replace-regexp-in-string
5090 (org-element-interpret-data
5091 (org-element-contents cell))))))
5093 (let ((headerp ,(and (or hfmt hsep)
5094 '(org-export-table-row-in-header-p
5095 (org-export-get-parent-element cell) info)))
5097 ;; Call costly `org-export-table-cell-address' only if
5098 ;; absolutely necessary, i.e., if one
5099 ;; of :fmt :efmt :hmft has a "plist type" value.
5100 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5101 (list efmt hfmt fmt))
5102 '(1+ (cdr (org-export-table-cell-address cell info))))))
5104 ;; Check if we can apply `:efmt' on CONTENTS.
5106 `(when (string-match orgtbl-exp-regexp contents)
5107 (let ((mantissa (match-string 1 contents))
5108 (exponent (match-string 2 contents)))
5109 (setq contents ,(org-table--generic-apply
5110 efmt ":efmt" t 'mantissa 'exponent)))))
5111 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5113 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5114 hfmt ":hfmt" t 'contents))))
5115 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5116 fmt ":fmt" t 'contents))))))
5117 ;; If a separator is provided, use it instead of BACKEND's.
5118 ;; Separators are ignored when LFMT (or equivalent) is
5122 `(if (or ,(and (not sep) '(not headerp))
5123 (plist-get info :orgtbl-ignore-sep)
5124 (not (org-export-get-next-element cell info)))
5125 ,(if (not backend) 'contents
5126 `(org-export-with-backend ',backend cell contents info))
5128 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5130 (backend `(org-export-with-backend ',backend cell contents info))
5134 (defun orgtbl-to-tsv (table params)
5135 "Convert the orgtbl-mode table to TAB separated material."
5136 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5139 (defun orgtbl-to-csv (table params)
5140 "Convert the orgtbl-mode table to CSV material.
5141 This does take care of the proper quoting of fields with comma or quotes."
5142 (orgtbl-to-generic table
5143 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5147 (defun orgtbl-to-latex (table params)
5148 "Convert the orgtbl-mode TABLE to LaTeX.
5150 TABLE is a list, each entry either the symbol `hline' for
5151 a horizontal separator line, or a list of fields for that line.
5152 PARAMS is a property list of parameters that can influence the
5153 conversion. All parameters from `orgtbl-to-generic' are
5154 supported. It is also possible to use the following ones:
5158 When non-nil, use formal \"booktabs\" style.
5162 Specify environment to use, as a string. If you use
5163 \"longtable\", you may also want to specify :language property,
5164 as a string, to get proper continuation strings."
5169 ;; Provide sane default values.
5170 (list :backend 'latex
5171 :latex-default-table-mode 'table
5172 :latex-tables-centered nil
5173 :latex-tables-booktabs (plist-get params :booktabs)
5174 :latex-table-scientific-notation nil
5175 :latex-default-table-environment
5176 (or (plist-get params :environment) "tabular"))
5180 (defun orgtbl-to-html (table params)
5181 "Convert the orgtbl-mode TABLE to HTML.
5183 TABLE is a list, each entry either the symbol `hline' for
5184 a horizontal separator line, or a list of fields for that line.
5185 PARAMS is a property list of parameters that can influence the
5186 conversion. All parameters from `orgtbl-to-generic' are
5187 supported. It is also possible to use the following one:
5191 Attributes and values, as a plist, which will be used in
5197 ;; Provide sane default values.
5198 (list :backend 'html
5199 :html-table-data-tags '("<td%s>" . "</td>")
5200 :html-table-use-header-tags-for-first-column nil
5201 :html-table-align-individual-fields t
5202 :html-table-row-tags '("<tr>" . "</tr>")
5203 :html-table-attributes
5204 (if (plist-member params :attributes)
5205 (plist-get params :attributes)
5206 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5211 (defun orgtbl-to-texinfo (table params)
5212 "Convert the orgtbl-mode TABLE to Texinfo.
5214 TABLE is a list, each entry either the symbol `hline' for
5215 a horizontal separator line, or a list of fields for that line.
5216 PARAMS is a property list of parameters that can influence the
5217 conversion. All parameters from `orgtbl-to-generic' are
5218 supported. It is also possible to use the following one:
5222 Column widths, as a string. When providing column fractions,
5223 \"@columnfractions\" command can be omitted."
5224 (require 'ox-texinfo)
5229 (list :backend 'texinfo
5230 :texinfo-tables-verbatim nil
5231 :texinfo-table-scientific-notation nil)
5233 (columns (let ((w (plist-get params :columns)))
5235 ((string-match-p "{\\|@columnfractions " w) w)
5236 (t (concat "@columnfractions " w))))))
5237 (if (not columns) output
5238 (replace-regexp-in-string
5239 "@multitable \\(.*\\)" columns output t nil 1))))
5242 (defun orgtbl-to-orgtbl (table params)
5243 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5245 TABLE is a list, each entry either the symbol `hline' for
5246 a horizontal separator line, or a list of fields for that line.
5247 PARAMS is a property list of parameters that can influence the
5248 conversion. All parameters from `orgtbl-to-generic' are
5251 Useful when slicing one table into many. The :hline, :sep,
5252 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5253 be set to provide ORGTBL directives for the generated table."
5255 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5257 (defun orgtbl-to-table.el (table params)
5258 "Convert the orgtbl-mode TABLE into a table.el table.
5259 TABLE is a list, each entry either the symbol `hline' for
5260 a horizontal separator line, or a list of fields for that line.
5261 PARAMS is a property list of parameters that can influence the
5262 conversion. All parameters from `orgtbl-to-generic' are
5265 (insert (orgtbl-to-orgtbl table params))
5267 (replace-regexp-in-string
5269 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5271 (defun orgtbl-to-unicode (table params)
5272 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5274 TABLE is a list, each entry either the symbol `hline' for
5275 a horizontal separator line, or a list of fields for that line.
5276 PARAMS is a property list of parameters that can influence the
5277 conversion. All parameters from `orgtbl-to-generic' are
5278 supported. It is also possible to use the following ones:
5282 When non-nil, use \"ascii-art-to-unicode\" package to translate
5283 the table. You can download it here:
5284 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5288 When non-nil, narrow columns width than provided width cookie,
5289 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5294 (list :backend 'ascii
5295 :ascii-charset 'utf-8
5296 :ascii-table-widen-columns (not (plist-get params :narrow))
5297 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5300 ;; Put the cursor in a column containing numerical values
5303 ;; A new column is added with a bar plot.
5304 ;; When the table is refreshed (C-u C-c *),
5305 ;; the plot is updated to reflect the new values.
5307 (defun orgtbl-ascii-draw (value min max &optional width characters)
5308 "Draw an ascii bar in a table.
5309 VALUE is the value to plot, it determines the width of the bar to draw.
5310 MIN is the value that will be displayed as empty (zero width bar).
5311 MAX is the value that will draw a bar filling all the WIDTH.
5312 WIDTH is the span in characters from MIN to MAX.
5313 CHARACTERS is a string that will compose the bar, with shades of grey
5314 from pure white to pure black. It defaults to a 10 characters string
5315 of regular ascii characters."
5316 (let* ((width (ceiling (or width 12)))
5317 (characters (or characters " .:;c!lhVHW"))
5318 (len (1- (length characters)))
5319 (value (float (if (numberp value)
5320 value (string-to-number value))))
5321 (relative (/ (- value min) (- max min)))
5322 (steps (round (* relative width len))))
5323 (cond ((< steps 0) "too small")
5324 ((> steps (* width len)) "too large")
5325 (t (let* ((int-division (/ steps len))
5326 (remainder (- steps (* int-division len))))
5327 (concat (make-string int-division (elt characters len))
5328 (string (elt characters remainder))))))))
5331 (defun orgtbl-ascii-plot (&optional ask)
5332 "Draw an ASCII bar plot in a column.
5334 With cursor in a column containing numerical values, this function
5335 will draw a plot in a new column.
5337 ASK, if given, is a numeric prefix to override the default 12
5338 characters width of the plot. ASK may also be the `\\[universal-argument]' \
5340 which will prompt for the width."
5342 (let ((col (org-table-current-column))
5343 (min 1e999) ; 1e999 will be converted to infinity
5344 (max -1e999) ; which is the desired result
5345 (table (org-table-to-lisp))
5348 (read-number "Length of column " 12))
5351 ;; Skip any hline a the top of table.
5352 (while (eq (car table) 'hline) (setq table (cdr table)))
5353 ;; Skip table header if any.
5354 (dolist (x (or (cdr (memq 'hline table)) table))
5356 (setq x (nth (1- col) x))
5358 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5360 (setq x (string-to-number x))
5361 (when (> min x) (setq min x))
5362 (when (< max x) (setq max x)))))
5363 (org-table-insert-column)
5364 (org-table-move-column-right)
5365 (org-table-store-formulas
5368 (concat "$" (number-to-string (1+ col)))
5369 (format "'(%s $%s %s %s %s)"
5370 "orgtbl-ascii-draw" col min max length))
5371 (org-table-get-stored-formulas)))
5372 (org-table-recalculate t)))
5374 ;; Example of extension: unicode characters
5375 ;; Here are two examples of different styles.
5377 ;; Unicode block characters are used to give a smooth effect.
5378 ;; See http://en.wikipedia.org/wiki/Block_Elements
5379 ;; Use one of those drawing functions
5380 ;; - orgtbl-ascii-draw (the default ascii)
5381 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5382 ;; - orgtbl-uc-draw-cont (smooth unicode)
5384 ;; This is best viewed with the "DejaVu Sans Mono" font
5385 ;; (use M-x set-default-font).
5387 (defun orgtbl-uc-draw-grid (value min max &optional width)
5388 "Draw a bar in a table using block unicode characters.
5389 It is a variant of orgtbl-ascii-draw with Unicode block
5390 characters, for a smooth display. Bars appear as grids (to the
5391 extent the font allows)."
5392 ;; http://en.wikipedia.org/wiki/Block_Elements
5393 ;; best viewed with the "DejaVu Sans Mono" font.
5394 (orgtbl-ascii-draw value min max width
5395 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5397 (defun orgtbl-uc-draw-cont (value min max &optional width)
5398 "Draw a bar in a table using block unicode characters.
5399 It is a variant of orgtbl-ascii-draw with Unicode block
5400 characters, for a smooth display. Bars are solid (to the extent
5402 (orgtbl-ascii-draw value min max width
5403 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5405 (defun org-table-get-remote-range (name-or-id form)
5406 "Get a field value or a list of values in a range from table at ID.
5408 NAME-OR-ID may be the name of a table in the current file as set
5409 by a \"#+NAME:\" directive. The first table following this line
5410 will then be used. Alternatively, it may be an ID referring to
5411 any entry, also in a different file. In this case, the first
5412 table in that entry will be referenced.
5413 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5414 \"@I$2..@II$2\". All the references must be absolute, not relative.
5416 The return value is either a single string for a single field, or a
5417 list of the fields in the rectangle."
5419 (let ((case-fold-search t) (id-loc nil)
5420 ;; Protect a bunch of variables from being overwritten by
5421 ;; the context of the remote table.
5422 org-table-column-names org-table-column-name-regexp
5423 org-table-local-parameters org-table-named-field-locations
5424 org-table-current-line-types
5425 org-table-current-begin-pos org-table-dlines
5426 org-table-current-ncol
5427 org-table-hlines org-table-last-alignment
5428 org-table-last-column-widths org-table-last-alignment
5429 org-table-last-column-widths
5431 (setq form (org-table-convert-refs-to-rc form))
5432 (org-with-wide-buffer
5433 (goto-char (point-min))
5434 (if (re-search-forward
5435 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5436 (regexp-quote name-or-id) "[ \t]*$")
5438 (setq buffer (current-buffer) loc (match-beginning 0))
5439 (setq id-loc (org-id-find name-or-id 'marker))
5440 (unless (and id-loc (markerp id-loc))
5441 (user-error "Can't find remote table \"%s\"" name-or-id))
5442 (setq buffer (marker-buffer id-loc)
5443 loc (marker-position id-loc))
5444 (move-marker id-loc nil))
5445 (with-current-buffer buffer
5446 (org-with-wide-buffer
5449 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5450 (not (match-beginning 1)))
5451 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5453 (setq form (org-table-formula-substitute-names
5454 (org-table-formula-handle-first/last-rc form)))
5455 (if (and (string-match org-table-range-regexp form)
5456 (> (length (match-string 0 form)) 1))
5457 (org-table-get-range
5458 (match-string 0 form) org-table-current-begin-pos 1)
5461 (defun org-table-remote-reference-indirection (form)
5462 "Return formula with table remote references substituted by indirection.
5463 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5464 This indirection works only with the format @ROW$COLUMN. The
5465 format \"B3\" is not supported because it can not be
5466 distinguished from a plain table name or ID."
5468 ;; Same as in `org-table-eval-formula'.
5469 (concat "\\<remote([ \t]*\\("
5470 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5472 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
5473 (replace-regexp-in-string
5477 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
5478 (org-table-get-range
5479 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
5484 (defmacro org-define-lookup-function (mode)
5485 (let ((mode-str (symbol-name mode))
5486 (first-p (eq mode 'first))
5487 (all-p (eq mode 'all)))
5488 (let ((plural-str (if all-p "s" "")))
5489 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5490 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5491 If R-LIST is nil, return matching element%s of S-LIST.
5492 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5493 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5494 This function is generated by a call to the macro `org-define-lookup-function'."
5495 mode-str plural-str plural-str plural-str)
5496 (let ,(let ((lvars '((p (or predicate 'equal))
5498 (rl (or r-list s-list))
5500 (if first-p (cons '(match-p nil) lvars) lvars))
5501 (while ,(if first-p '(and (not match-p) sl) 'sl)
5502 (when (funcall p val (car sl))
5503 ,(when first-p '(setq match-p t))
5504 (let ((rval (car rl)))
5505 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5506 (setq sl (cdr sl) rl (cdr rl)))
5509 (org-define-lookup-function first)
5510 (org-define-lookup-function last)
5511 (org-define-lookup-function all)
5513 (provide 'org-table)
5516 ;; generated-autoload-file: "org-loaddefs.el"
5519 ;;; org-table.el ends here