1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2015 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.
42 (declare-function org-element-at-point
"org-element" ())
43 (declare-function org-element-contents
"org-element" (element))
44 (declare-function org-element-extract-element
"org-element" (element))
45 (declare-function org-element-interpret-data
"org-element" (data))
46 (declare-function org-element-lineage
"org-element"
47 (blob &optional types with-self
))
48 (declare-function org-element-map
"org-element"
50 &optional info first-match no-recursion with-affiliated
))
51 (declare-function org-element-parse-buffer
"org-element"
52 (&optional granularity visible-only
))
53 (declare-function org-element-property
"org-element" (property element
))
54 (declare-function org-element-type
"org-element" (element))
56 (declare-function org-export-create-backend
"org-export" (&rest rest
))
57 (declare-function org-export-data-with-backend
"org-export" (arg1 arg2 arg3
))
58 (declare-function org-export-first-sibling-p
"org-export" (arg1 arg2
))
59 (declare-function org-export-get-backend
"org-export" (arg1))
60 (declare-function org-export-get-environment
"org-export" (&optional arg1 arg2 arg3
))
61 (declare-function org-export-table-has-special-column-p
"org-export" (arg1))
62 (declare-function org-export-table-row-is-special-p
"org-export" (arg1 arg2
))
64 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
66 (defvar orgtbl-mode
) ; defined below
67 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
68 (defvar constants-unit-system
)
69 (defvar org-table-follow-field-mode
)
70 (defvar sort-fold-case
)
72 (defvar orgtbl-after-send-table-hook nil
73 "Hook for functions attaching to `C-c C-c', if the table is sent.
74 This can be used to add additional functionality after the table is sent
75 to the receiver position, otherwise, if table is not sent, the functions
78 (defvar org-table-TBLFM-begin-regexp
"^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
80 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
81 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
82 In the optimized version, the table editor takes over all simple keys that
83 normally just insert a character. In tables, the characters are inserted
84 in a way to minimize disturbing the table structure (i.e. in overwrite mode
85 for empty fields). Outside tables, the correct binding of the keys is
88 The default for this option is t if the optimized version is also used in
89 Org-mode. See the variable `org-enable-table-editor' for details. Changing
90 this variable requires a restart of Emacs to become effective."
94 (defcustom orgtbl-radio-table-templates
95 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
96 % END RECEIVE ORGTBL %n
98 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
101 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
102 @c END RECEIVE ORGTBL %n
104 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
107 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
108 <!-- END RECEIVE ORGTBL %n -->
110 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
113 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
114 #+ END RECEIVE ORGTBL %n
116 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
119 "Templates for radio tables in different major modes.
120 Each template must define lines that will be treated as a comment and that
121 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
122 lines where \"%n\" will be replaced with the name of the table during
123 insertion of the template. The transformed table will later be inserted
126 The template should also contain a minimal table in a multiline comment.
127 If multiline comments are not possible in the buffer language,
128 you can pack it into a string that will not be used when the code
129 is compiled or executed. Above the table will you need a line with
130 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
131 convert the table into a data structure useful in the
132 language of the buffer. Check the manual for the section on
133 \"Translator functions\", and more generally check out
134 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
136 All occurrences of %n in a template will be replaced with the name of the
137 table, obtained by prompting the user."
140 (list (symbol :tag
"Major mode")
141 (string :tag
"Format"))))
143 (defgroup org-table-settings nil
144 "Settings for tables in Org-mode."
145 :tag
"Org Table Settings"
148 (defcustom org-table-default-size
"5x2"
149 "The default size for newly created tables, Columns x Rows."
150 :group
'org-table-settings
153 (defcustom org-table-number-regexp
154 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
155 "Regular expression for recognizing numbers in table columns.
156 If a table column contains mostly numbers, it will be aligned to the
157 right. If not, it will be aligned to the left.
159 The default value of this option is a regular expression which allows
160 anything which looks remotely like a number as used in scientific
161 context. For example, all of the following will be considered a
163 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
165 Other options offered by the customize interface are more restrictive."
166 :group
'org-table-settings
168 (const :tag
"Positive Integers"
170 (const :tag
"Integers"
172 (const :tag
"Floating Point Numbers"
173 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
174 (const :tag
"Floating Point Number or Integer"
175 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
176 (const :tag
"Exponential, Floating point, Integer"
177 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
178 (const :tag
"Very General Number-Like, including hex and Calc radix"
179 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
180 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
181 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
182 (string :tag
"Regexp:")))
184 (defcustom org-table-number-fraction
0.5
185 "Fraction of numbers in a column required to make the column align right.
186 In a column all non-white fields are considered. If at least
187 this fraction of fields is matched by `org-table-number-regexp',
188 alignment to the right border applies."
189 :group
'org-table-settings
192 (defgroup org-table-editing nil
193 "Behavior of tables during editing in Org-mode."
194 :tag
"Org Table Editing"
197 (defcustom org-table-automatic-realign t
198 "Non-nil means automatically re-align table when pressing TAB or RETURN.
199 When nil, aligning is only done with \\[org-table-align], or after column
201 :group
'org-table-editing
204 (defcustom org-table-auto-blank-field t
205 "Non-nil means automatically blank table field when starting to type into it.
206 This only happens when typing immediately after a field motion
207 command (TAB, S-TAB or RET).
208 Only relevant when `org-enable-table-editor' is equal to `optimized'."
209 :group
'org-table-editing
212 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
213 "Non-nil means automatically exit the follow mode.
214 When nil, the follow mode will stay on and be active in any table
215 the cursor enters. Since the table follow filed mode messes with the
216 window configuration, it is not recommended to set this variable to nil,
217 except maybe locally in a special file that has mostly tables with long
223 (defcustom org-table-fix-formulas-confirm nil
224 "Whether the user should confirm when Org fixes formulas."
225 :group
'org-table-editing
228 (const :tag
"with yes-or-no" yes-or-no-p
)
229 (const :tag
"with y-or-n" y-or-n-p
)
230 (const :tag
"no confirmation" nil
)))
231 (put 'org-table-fix-formulas-confirm
233 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
235 (defcustom org-table-tab-jumps-over-hlines t
236 "Non-nil means tab in the last column of a table with jump over a hline.
237 If a horizontal separator line is following the current line,
238 `org-table-next-field' can either create a new row before that line, or jump
239 over the line. When this option is nil, a new line will be created before
241 :group
'org-table-editing
244 (defgroup org-table-calculation nil
245 "Options concerning tables in Org-mode."
246 :tag
"Org Table Calculation"
249 (defcustom org-table-use-standard-references
'from
250 "Should org-mode work with table references like B3 instead of @3$2?
253 from accept as input, do not present for editing
254 t accept as input and present for editing"
255 :group
'org-table-calculation
257 (const :tag
"Never, don't even check user input for them" nil
)
258 (const :tag
"Always, both as user input, and when editing" t
)
259 (const :tag
"Convert user input, don't offer during editing" from
)))
261 (defcustom org-table-copy-increment t
262 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
263 :group
'org-table-calculation
265 :package-version
'(Org .
"8.3")
267 (const :tag
"Use the difference between the current and the above fields" t
)
268 (integer :tag
"Use a number" 1)
269 (const :tag
"Don't increment the value when copying a field" nil
)))
271 (defcustom org-calc-default-modes
272 '(calc-internal-prec 12
273 calc-float-format
(float 8)
276 calc-symbolic-mode nil
277 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
278 calc-display-working-message t
280 "List with Calc mode settings for use in `calc-eval' for table formulas.
281 The list must contain alternating symbols (Calc modes variables and values).
282 Don't remove any of the default settings, just change the values. Org-mode
283 relies on the variables to be present in the list."
284 :group
'org-table-calculation
287 (defcustom org-table-duration-custom-format
'hours
288 "Format for the output of calc computations like $1+$2;t.
289 The default value is `hours', and will output the results as a
290 number of hours. Other allowed values are `seconds', `minutes' and
291 `days', and the output will be a fraction of seconds, minutes or
293 :group
'org-table-calculation
295 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
296 (symbol :tag
"Minutes" 'minutes
)
297 (symbol :tag
"Hours " 'hours
)
298 (symbol :tag
"Days " 'days
)))
300 (defcustom org-table-formula-field-format
"%s"
301 "Format for fields which contain the result of a formula.
302 For example, using \"~%s~\" will display the result within tilde
303 characters. Beware that modifying the display can prevent the
304 field from being used in another formula."
305 :group
'org-table-settings
309 (defcustom org-table-formula-evaluate-inline t
310 "Non-nil means TAB and RET evaluate a formula in current table field.
311 If the current field starts with an equal sign, it is assumed to be a formula
312 which should be evaluated as described in the manual and in the documentation
313 string of the command `org-table-eval-formula'. This feature requires the
315 When this variable is nil, formula calculation is only available through
316 the command \\[org-table-eval-formula]."
317 :group
'org-table-calculation
320 (defcustom org-table-formula-use-constants t
321 "Non-nil means interpret constants in formulas in tables.
322 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
323 by the value given in `org-table-formula-constants', or by a value obtained
324 from the `constants.el' package."
325 :group
'org-table-calculation
328 (defcustom org-table-formula-constants nil
329 "Alist with constant names and values, for use in table formulas.
330 The car of each element is a name of a constant, without the `$' before it.
331 The cdr is the value as a string. For example, if you'd like to use the
332 speed of light in a formula, you would configure
334 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
336 and then use it in an equation like `$1*$c'.
338 Constants can also be defined on a per-file basis using a line like
340 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
341 :group
'org-table-calculation
343 (cons (string :tag
"name")
344 (string :tag
"value"))))
346 (defcustom org-table-allow-automatic-line-recalculation t
347 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
349 Automatically means when TAB or RET or \\[org-ctrl-c-ctrl-c] \
350 are pressed in the line."
351 :group
'org-table-calculation
354 (defcustom org-table-relative-ref-may-cross-hline t
355 "Non-nil means relative formula references may cross hlines.
356 Here are the allowed values:
358 nil Relative references may not cross hlines. They will reference the
359 field next to the hline instead. Coming from below, the reference
360 will be to the field below the hline. Coming from above, it will be
362 t Relative references may cross hlines.
363 error An attempt to cross a hline will throw an error.
365 It is probably good to never set this variable to nil, for the sake of
366 portability of tables."
367 :group
'org-table-calculation
369 (const :tag
"Allow to cross" t
)
370 (const :tag
"Stick to hline" nil
)
371 (const :tag
"Error on attempt to cross" error
)))
373 (defcustom org-table-formula-create-columns nil
374 "Non-nil means that evaluation of a field formula can add new
375 columns if an out-of-bounds field is being set."
376 :group
'org-table-calculation
378 :package-version
'(Org .
"8.3")
380 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
381 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
382 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
383 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
385 (defgroup org-table-import-export nil
386 "Options concerning table import and export in Org-mode."
387 :tag
"Org Table Import Export"
390 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
391 "Default export parameters for `org-table-export'.
392 These can be overridden for a specific table by setting the
393 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
394 radio tables for the different export transformations and
395 available parameters."
396 :group
'org-table-import-export
399 (defcustom org-table-convert-region-max-lines
999
400 "Max lines that `org-table-convert-region' will attempt to process.
402 The function can be slow on larger regions; this safety feature
403 prevents it from hanging emacs."
404 :group
'org-table-import-export
407 :package-version
'(Org .
"8.3"))
409 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
410 "Regexp matching a line marked for automatic recalculation.")
412 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
413 "Regexp matching a line marked for recalculation.")
415 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
416 "Regexp matching a line marked for calculation.")
418 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
419 "Regexp matching any line outside an Org table.")
421 (defvar org-table-last-highlighted-reference nil
)
423 (defvar org-table-formula-history nil
)
425 (defvar org-table-column-names nil
426 "Alist with column names, derived from the `!' line.
427 This variable is initialized with `org-table-analyze'.")
429 (defvar org-table-column-name-regexp nil
430 "Regular expression matching the current column names.
431 This variable is initialized with `org-table-analyze'.")
433 (defvar org-table-local-parameters nil
434 "Alist with parameter names, derived from the `$' line.
435 This variable is initialized with `org-table-analyze'.")
437 (defvar org-table-named-field-locations nil
438 "Alist with locations of named fields.
439 Associations follow the pattern (NAME LINE COLUMN) where
440 NAME is the name of the field as a string,
441 LINE is the number of lines from the beginning of the table,
442 COLUMN is the column of the field, as an integer.
443 This variable is initialized with `org-table-analyze'.")
445 (defvar org-table-current-line-types nil
446 "Table row types in current table.
447 This variable is initialized with `org-table-analyze'.")
449 (defvar org-table-current-begin-pos nil
450 "Current table begin position, as a marker.
451 This variable is initialized with `org-table-analyze'.")
453 (defvar org-table-current-ncol nil
454 "Number of columns in current table.
455 This variable is initialized with `org-table-analyze'.")
457 (defvar org-table-dlines nil
458 "Vector of data line line numbers in the current table.
459 Line numbers are counted from the beginning of the table. This
460 variable is initialized with `org-table-analyze'.")
462 (defvar org-table-hlines nil
463 "Vector of hline 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 (defconst org-table-range-regexp
468 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
470 "Regular expression for matching ranges in formulas.")
472 (defconst org-table-range-regexp2
474 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
476 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
477 "Match a range for reference display.")
479 (defconst org-table-translate-regexp
480 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
481 "Match a reference that needs translation, for reference display.")
483 (defmacro org-table-save-field
(&rest body
)
484 "Save current field; execute BODY; restore field.
485 Field is restored even in case of abnormal exit."
486 (declare (debug (body)))
487 (org-with-gensyms (line column
)
488 `(let ((,line
(copy-marker (line-beginning-position)))
489 (,column
(org-table-current-column)))
493 (org-table-goto-column ,column
)
494 (set-marker ,line nil
)))))
497 (defun org-table-create-with-table.el
()
498 "Use the table.el package to insert a new table.
499 If there is already a table at point, convert between Org-mode tables
500 and table.el tables."
505 (if (y-or-n-p "Convert table to Org-mode table? ")
506 (org-table-convert)))
508 (when (y-or-n-p "Convert table to table.el table? ")
510 (org-table-convert)))
511 (t (call-interactively 'table-insert
))))
514 (defun org-table-create-or-convert-from-region (arg)
515 "Convert region to table, or create an empty table.
516 If there is an active region, convert it to a table, using the function
517 `org-table-convert-region'. See the documentation of that function
518 to learn how the prefix argument is interpreted to determine the field
520 If there is no such region, create an empty table with `org-table-create'."
522 (if (org-region-active-p)
523 (org-table-convert-region (region-beginning) (region-end) arg
)
524 (org-table-create arg
)))
527 (defun org-table-create (&optional size
)
528 "Query for a size and insert a table skeleton.
529 SIZE is a string Columns x Rows like for example \"3x2\"."
532 (setq size
(read-string
533 (concat "Table size Columns x Rows [e.g. "
534 org-table-default-size
"]: ")
535 "" nil org-table-default-size
)))
538 (indent (make-string (current-column) ?\
))
539 (split (org-split-string size
" *x *"))
540 (rows (string-to-number (nth 1 split
)))
541 (columns (string-to-number (car split
)))
542 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
544 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
545 (point-at-bol) (point)))
546 (beginning-of-line 1)
548 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
549 (dotimes (_ rows
) (insert line
))
552 ;; Insert a hline after the first row.
560 (defun org-table-convert-region (beg0 end0
&optional separator
)
561 "Convert region to a table.
562 The region goes from BEG0 to END0, but these borders will be moved
563 slightly, to make sure a beginning of line in the first line is included.
565 SEPARATOR specifies the field separator in the lines. It can have the
568 (4) Use the comma as a field separator
569 (16) Use a TAB as field separator
570 (64) Prompt for a regular expression as field separator
571 integer When a number, use that many spaces as field separator
572 regexp When a regular expression, use it to match the separator
573 nil When nil, the command tries to be smart and figure out the
574 separator in the following way:
575 - when each line contains a TAB, assume TAB-separated material
576 - when each line contains a comma, assume CSV material
577 - else, assume one or more SPACE characters as separator."
579 (let* ((beg (min beg0 end0
))
580 (end (max beg0 end0
))
582 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
583 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
584 org-table-convert-region-max-lines
)
585 (if (equal separator
'(64))
586 (setq separator
(read-regexp "Regexp for field separator")))
588 (beginning-of-line 1)
589 (setq beg
(point-marker))
591 (if (bolp) (backward-char 1) (end-of-line 1))
592 (setq end
(point-marker))
593 ;; Get the right field separator
598 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
599 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
602 (if (equal separator
'(4))
603 (while (< (point) end
)
604 ;; parse the csv stuff
606 ((looking-at "^") (insert "| "))
607 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
608 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
609 (replace-match "\\1")
610 (if (looking-at "\"") (insert "\"")))
611 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
612 ((looking-at "[ \t]*,") (replace-match " | "))
613 (t (beginning-of-line 2))))
615 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
616 ((equal separator
'(16)) "^\\|\t")
617 ((integerp separator
)
619 (user-error "Number of spaces in separator must be >= 1")
620 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
622 (format "^ *\\|%s" separator
))
623 (t (error "This should not happen"))))
624 (while (re-search-forward re end t
)
625 (replace-match "| " t t
)))
630 (defun org-table-import (file arg
)
631 "Import FILE as a table.
632 The file is assumed to be tab-separated. Such files can be produced by most
633 spreadsheet and database applications. If no tabs (at least one per line)
634 are found, lines will be split on whitespace into fields."
636 (or (bolp) (newline))
639 (insert-file-contents file
)
640 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
644 (defun org-table-export (&optional file format
)
645 "Export table to a file, with configurable format.
646 Such a file can be imported into usual spreadsheet programs.
648 FILE can be the output file name. If not given, it will be taken
649 from a TABLE_EXPORT_FILE property in the current entry or higher
650 up in the hierarchy, or the user will be prompted for a file
651 name. FORMAT can be an export format, of the same kind as it
652 used when `orgtbl-mode' sends a table in a different format.
654 The command suggests a format depending on TABLE_EXPORT_FORMAT,
655 whether it is set locally or up in the hierarchy, then on the
656 extension of the given file name, and finally on the variable
657 `org-table-export-default-format'."
659 (unless (org-at-table-p) (user-error "No table at point"))
660 (org-table-align) ; Make sure we have everything we need.
661 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
663 (setq file
(read-file-name "Export table to: "))
664 (unless (or (not (file-exists-p file
))
665 (y-or-n-p (format "Overwrite file %s? " file
)))
666 (user-error "File not written")))
667 (when (file-directory-p file
)
668 (user-error "This is a directory path, not a file"))
669 (when (and (buffer-file-name (buffer-base-buffer))
672 (file-truename (buffer-file-name (buffer-base-buffer)))))
673 (user-error "Please specify a file name that is different from current"))
674 (let ((fileext (concat (file-name-extension file
) "$"))
675 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
677 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
678 "orgtbl-to-html" "orgtbl-to-generic"
679 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
680 "orgtbl-to-unicode"))
682 (replace-regexp-in-string
684 (replace-regexp-in-string
689 (and (org-string-match-p fileext f
) f
))
691 org-table-export-default-format
)
695 "Format: " formats nil nil deffmt-readable
))))
696 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
697 (let ((transform (intern (match-string 1 format
)))
698 (params (and (match-end 2)
699 (read (concat "(" (match-string 2 format
) ")"))))
700 (table (org-table-to-lisp
701 (buffer-substring-no-properties
702 (org-table-begin) (org-table-end)))))
703 (unless (fboundp transform
)
704 (user-error "No such transformation function %s" transform
))
706 (with-current-buffer (find-file-noselect file
)
707 (setq buf
(current-buffer))
710 (insert (funcall transform table params
) "\n")
713 (message "Export done."))
714 (user-error "TABLE_EXPORT_FORMAT invalid")))))
716 (defvar org-table-aligned-begin-marker
(make-marker)
717 "Marker at the beginning of the table last aligned.
718 Used to check if cursor still is in that table, to minimize realignment.")
719 (defvar org-table-aligned-end-marker
(make-marker)
720 "Marker at the end of the table last aligned.
721 Used to check if cursor still is in that table, to minimize realignment.")
722 (defvar org-table-last-alignment nil
723 "List of flags for flushright alignment, from the last re-alignment.
724 This is being used to correctly align a single field after TAB or RET.")
725 (defvar org-table-last-column-widths nil
726 "List of max width of fields in each column.
727 This is being used to correctly align a single field after TAB or RET.")
728 (defvar-local org-table-formula-debug nil
729 "Non-nil means debug table formulas.
730 When nil, simply write \"#ERROR\" in corrupted fields.")
731 (defvar-local org-table-overlay-coordinates nil
732 "Overlay coordinates after each align of a table.")
734 (defvar org-last-recalc-line nil
)
735 (defvar org-table-do-narrow t
) ; for dynamic scoping
736 (defconst org-narrow-column-arrow
"=>"
737 "Used as display property in narrowed table columns.")
740 (defun org-table-align ()
741 "Align the table at point by aligning all vertical bars."
743 (let* ((beg (org-table-begin))
744 (end (copy-marker (org-table-end))))
745 (org-table-save-field
746 ;; Make sure invisible characters in the table are at the right
747 ;; place since column widths take them into account.
748 (font-lock-fontify-region beg end
)
749 (move-marker org-table-aligned-begin-marker beg
)
750 (move-marker org-table-aligned-end-marker end
)
752 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
753 ;; Table's rows. Separators are replaced by nil. Trailing
754 ;; spaces are also removed.
755 (lines (mapcar (lambda (l)
756 (and (not (org-string-match-p "\\`[ \t]*|-" l
))
757 (let ((l (org-trim l
)))
758 (remove-text-properties
759 0 (length l
) '(display t org-cwidth t
) l
)
761 (org-split-string (buffer-substring beg end
) "\n")))
762 ;; Get the data fields by splitting the lines.
763 (fields (mapcar (lambda (l) (org-split-string l
" *| *"))
765 ;; Compute number of fields in the longest line. If the
766 ;; table contains no field, create a default table.
767 (maxfields (if fields
(apply #'max
(mapcar #'length fields
))
768 (kill-region beg end
)
769 (org-table-create org-table-default-size
)
770 (user-error "Empty table - created default table")))
771 ;; A list of empty strings to fill any short rows on output.
772 (emptycells (make-list maxfields
""))
774 ;; Check for special formatting.
775 (dotimes (i maxfields
)
776 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) fields
))
778 ;; Look for an explicit width or alignment.
779 (when (save-excursion
780 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t
)
781 (and org-table-do-narrow
783 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t
))))
785 (dolist (cell column
)
786 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell
)
787 (when (match-end 1) (setq falign
(match-string 1 cell
)))
788 (when (and org-table-do-narrow
(match-end 2))
789 (setq fmax
(string-to-number (match-string 2 cell
))))
790 (when (or falign fmax
) (throw :exit nil
)))))
791 ;; Find fields that are wider than FMAX, and shorten them.
794 (when (> (org-string-width x
) fmax
)
798 (substitute-command-keys
799 "Clipped table field, use \\[org-table-edit-field] to \
800 edit. Full value is:\n")
801 (substring-no-properties x
)))
804 (or (string-match org-bracket-link-regexp x
)
809 "Cannot narrow field starting with wide link \"%s\""
811 (if (= (org-string-width x
) l
) (setq f2 f1
)
813 (while (< (org-string-width (substring x
0 f2
)) f1
)
815 (add-text-properties f2 l
(list 'org-cwidth t
) x
)
817 (if (>= (string-width (substring x
(1- f2
) f2
)) 2) (1- f2
)
820 (list 'display org-narrow-column-arrow
)
822 ;; Get the maximum width for each column
823 (push (apply #'max
(or fmax
1) 1 (mapcar #'org-string-width column
))
825 ;; Get the fraction of numbers among non-empty cells to
826 ;; decide about alignment of the column.
827 (if falign
(push (equal (downcase falign
) "r") typenums
)
834 (if (org-string-match-p org-table-number-regexp x
)
838 (push (>= frac org-table-number-fraction
) typenums
)))))
839 (setq lengths
(nreverse lengths
))
840 (setq typenums
(nreverse typenums
))
841 ;; Store alignment of this table, for later editing of single
843 (setq org-table-last-alignment typenums
)
844 (setq org-table-last-column-widths lengths
)
845 ;; With invisible characters, `format' does not get the field
846 ;; width right So we need to make these fields wide by hand.
847 ;; Invisible characters may be introduced by fontified links,
848 ;; emphasis, macros or sub/superscripts.
849 (when (or (text-property-any beg end
'invisible
'org-link
)
850 (text-property-any beg end
'invisible t
))
851 (dotimes (i maxfields
)
852 (let ((len (nth i lengths
)))
853 (dotimes (j (length fields
))
854 (let* ((c (nthcdr i
(nth j fields
)))
858 (let ((l (length cell
)))
859 (or (text-property-any 0 l
'invisible
'org-link cell
)
860 (text-property-any beg end
'invisible t
)))
861 (< (org-string-width cell
) len
))
862 (let ((s (make-string (- len
(org-string-width cell
)) ?\s
)))
863 (setcar c
(if (nth i typenums
) (concat s cell
)
864 (concat cell s
))))))))))
866 ;; Compute the formats needed for output of the table.
867 (let ((hfmt (concat indent
"|"))
868 (rfmt (concat indent
"|"))
871 (dolist (l lengths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
872 (let ((ty (if (pop typenums
) "" "-"))) ; Flush numbers right.
873 (setq rfmt
(concat rfmt
(format rfmt1 ty l
)))
874 (setq hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
))))))
875 ;; Replace modified lines only. Check not only contents, but
876 ;; also columns' width.
879 (if l
(apply #'format rfmt
(append (pop fields
) emptycells
))
881 (previous (buffer-substring (point) (line-end-position))))
882 (if (and (equal previous line
)
886 (setq a
(next-single-property-change
887 a
'org-cwidth previous
))
888 (setq b
(next-single-property-change
889 b
'org-cwidth line
)))
894 (delete-region (point) (line-beginning-position 2))))))
895 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
896 (goto-char org-table-aligned-begin-marker
)
897 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
899 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
900 (setq org-table-may-need-update nil
)))))
903 (defun org-table-begin (&optional table-type
)
904 "Find the beginning of the table and return its position.
905 With a non-nil optional argument TABLE-TYPE, return the beginning
906 of a table.el-type table. This function assumes point is on
909 (org-element-property :post-affiliated
(org-element-at-point)))
911 (and (re-search-backward org-table-border-regexp nil t
)
912 (line-beginning-position 2))))
916 (defun org-table-end (&optional table-type
)
917 "Find the end of the table and return its position.
918 With a non-nil optional argument TABLE-TYPE, return the end of
919 a table.el-type table. This function assumes point is on
923 (goto-char (org-element-property :end
(org-element-at-point)))
924 (skip-chars-backward " \t\n")
925 (line-beginning-position 2))
926 ((re-search-forward org-table-border-regexp nil t
)
928 ;; When the line right after the table is the last line in
929 ;; the buffer with trailing spaces but no final newline
930 ;; character, trailing spaces, be sure to catch the correct
931 ;; ending at its beginning. In any other case, ending is
932 ;; expected to be at point max.
933 (t (goto-char (point-max))
934 (skip-chars-backward " \t")
935 (if (bolp) (point) (line-end-position))))))
938 (defun org-table-justify-field-maybe (&optional new
)
939 "Justify the current field, text to left, number to right.
940 Optional argument NEW may specify text to replace the current field content."
942 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
943 ((org-at-table-hline-p))
945 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
947 (< (point) org-table-aligned-begin-marker
)
948 (>= (point) org-table-aligned-end-marker
)))
949 ;; This is not the same table, force a full re-align
950 (setq org-table-may-need-update t
))
951 (t ;; realign the current field, based on previous full realign
952 (let* ((pos (point)) s
953 (col (org-table-current-column))
954 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
957 (skip-chars-backward "^|\n")
958 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
960 (setq s
(match-string 1)
964 (buffer-substring-no-properties
965 (match-end 0) (match-beginning 0))) 3))
966 e
(not (= (match-beginning 2) (match-end 2))))
967 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
968 l
(if e
"|" (setq org-table-may-need-update t
) ""))
971 (if (<= (org-string-width new
) l
)
972 (setq n
(format f new
))
973 (setq n
(concat new
"|") org-table-may-need-update t
)))
974 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
976 (let (org-table-may-need-update)
977 (replace-match n t t
))))
978 (setq org-table-may-need-update t
))
982 (defun org-table-next-field ()
983 "Go to the next field in the current table, creating new lines as needed.
984 Before doing so, re-align the table if necessary."
986 (org-table-maybe-eval-formula)
987 (org-table-maybe-recalculate-line)
988 (if (and org-table-automatic-realign
989 org-table-may-need-update
)
991 (let ((end (org-table-end)))
992 (if (org-at-table-hline-p)
996 (re-search-forward "|" end
)
997 (if (looking-at "[ \t]*$")
998 (re-search-forward "|" end
))
999 (if (and (looking-at "-")
1000 org-table-tab-jumps-over-hlines
1001 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1002 (goto-char (match-beginning 1)))
1003 (if (looking-at "-")
1005 (beginning-of-line 0)
1006 (org-table-insert-row 'below
))
1007 (if (looking-at " ") (forward-char 1))))
1009 (org-table-insert-row 'below
)))))
1012 (defun org-table-previous-field ()
1013 "Go to the previous field in the table.
1014 Before doing so, re-align the table if necessary."
1016 (org-table-justify-field-maybe)
1017 (org-table-maybe-recalculate-line)
1018 (if (and org-table-automatic-realign
1019 org-table-may-need-update
)
1021 (if (org-at-table-hline-p)
1025 (re-search-backward "|" (org-table-begin))
1026 (re-search-backward "|" (org-table-begin)))
1027 (error (user-error "Cannot move to previous table field")))
1028 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1029 (re-search-backward "|" (org-table-begin)))
1030 (if (looking-at "| ?")
1031 (goto-char (match-end 0))))
1033 (defun org-table-beginning-of-field (&optional n
)
1034 "Move to the beginning of the current table field.
1035 If already at or before the beginning, move to the beginning of the
1037 With numeric argument N, move N-1 fields backward first."
1039 (let ((pos (point)))
1042 (org-table-previous-field))
1043 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1044 (user-error "No more table fields before the current")
1045 (goto-char (match-end 0))
1046 (and (looking-at " ") (forward-char 1)))
1047 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1049 (defun org-table-end-of-field (&optional n
)
1050 "Move to the end of the current table field.
1051 If already at or after the end, move to the end of the next table field.
1052 With numeric argument N, move N-1 fields forward first."
1054 (let ((pos (point)))
1057 (org-table-next-field))
1058 (when (re-search-forward "|" (point-at-eol 1) t
)
1060 (skip-chars-backward " ")
1061 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1063 (if (<= (point) pos
) (org-table-end-of-field 2))))
1066 (defun org-table-next-row ()
1067 "Go to the next row (same column) in the current table.
1068 Before doing so, re-align the table if necessary."
1070 (org-table-maybe-eval-formula)
1071 (org-table-maybe-recalculate-line)
1072 (if (or (looking-at "[ \t]*$")
1073 (save-excursion (skip-chars-backward " \t") (bolp)))
1075 (if (and org-table-automatic-realign
1076 org-table-may-need-update
)
1078 (let ((col (org-table-current-column)))
1079 (beginning-of-line 2)
1080 (if (or (not (org-at-table-p))
1081 (org-at-table-hline-p))
1083 (beginning-of-line 0)
1084 (org-table-insert-row 'below
)))
1085 (org-table-goto-column col
)
1086 (skip-chars-backward "^|\n\r")
1087 (if (looking-at " ") (forward-char 1)))))
1090 (defun org-table-copy-down (n)
1091 "Copy the value of the current field one row below.
1093 If the field at the cursor is empty, copy the content of the
1094 nearest non-empty field above. With argument N, use the Nth
1097 If the current field is not empty, it is copied down to the next
1098 row, and the cursor is moved with it. Therefore, repeating this
1099 command causes the column to be filled row-by-row.
1101 If the variable `org-table-copy-increment' is non-nil and the
1102 field is an integer or a timestamp, it will be incremented while
1103 copying. By default, increment by the difference between the
1104 value in the current field and the one in the field above. To
1105 increment using a fixed integer, set `org-table-copy-increment'
1106 to a number. In the case of a timestamp, increment by days."
1108 (let* ((colpos (org-table-current-column))
1109 (col (current-column))
1110 (field (save-excursion (org-table-get-field)))
1111 (field-up (or (save-excursion
1112 (org-table-get (1- (org-table-current-line))
1113 (org-table-current-column))) ""))
1114 (non-empty (string-match "[^ \t]" field
))
1115 (non-empty-up (string-match "[^ \t]" field-up
))
1116 (beg (org-table-begin))
1119 (org-table-check-inside-data-field)
1124 (while (progn (beginning-of-line 1)
1125 (re-search-backward org-table-dataline-regexp
1127 (org-table-goto-column colpos t
)
1128 (if (and (looking-at
1129 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1130 (<= (setq n
(1- n
)) 0))
1131 (throw 'exit
(match-string 1))))))
1134 (while (progn (beginning-of-line 1)
1135 (re-search-backward org-table-dataline-regexp
1137 (org-table-goto-column colpos t
)
1138 (if (and (looking-at
1139 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1140 (<= (setq n
(1- n
)) 0))
1141 (throw 'exit
(match-string 1))))))
1142 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1143 ;; Above field was not empty, go down to the next row
1144 (setq txt
(org-trim field
))
1145 (org-table-next-row)
1146 (org-table-blank-field))
1147 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1149 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1150 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1151 (string-match org-ts-regexp3 txt
))
1152 (- (org-time-string-to-absolute txt
)
1153 (org-time-string-to-absolute txt-up
)))
1154 ((string-match org-ts-regexp3 txt
) 1)
1155 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1156 (- (string-to-number txt
)
1157 (string-to-number (match-string 0 txt-up
))))
1161 (user-error "No non-empty field found")
1162 (if (and org-table-copy-increment
1163 (not (equal orig-n
0))
1164 (string-match "^[-+^/*0-9eE.]+$" txt
)
1165 (< (string-to-number txt
) 100000000))
1166 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1168 (org-move-to-column col
)
1169 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1170 (org-timestamp-up-day inc
)
1171 (org-table-maybe-recalculate-line))
1173 (org-move-to-column col
))))
1175 (defun org-table-check-inside-data-field (&optional noerror
)
1176 "Is point inside a table data field?
1177 I.e. not on a hline or before the first or after the last column?
1178 This actually throws an error, so it aborts the current command."
1179 (cond ((and (org-at-table-p)
1180 (not (save-excursion (skip-chars-backward " \t") (bolp)))
1181 (not (org-at-table-hline-p))
1182 (not (looking-at "[ \t]*$"))))
1184 (t (user-error "Not in table data field"))))
1186 (defvar org-table-clip nil
1187 "Clipboard for table regions.")
1189 (defun org-table-get (line column
)
1190 "Get the field in table line LINE, column COLUMN.
1191 If LINE is larger than the number of data lines in the table, the function
1192 returns nil. However, if COLUMN is too large, we will simply return an
1194 If LINE is nil, use the current line.
1195 If COLUMN is nil, use the current column."
1196 (setq column
(or column
(org-table-current-column)))
1198 (and (or (not line
) (org-table-goto-line line
))
1199 (org-trim (org-table-get-field column
)))))
1201 (defun org-table-put (line column value
&optional align
)
1202 "Put VALUE into line LINE, column COLUMN.
1203 When ALIGN is set, also realign the table."
1204 (setq column
(or column
(org-table-current-column)))
1205 (prog1 (save-excursion
1206 (and (or (not line
) (org-table-goto-line line
))
1207 (progn (org-table-goto-column column nil
'force
) t
)
1208 (org-table-get-field column value
)))
1209 (and align
(org-table-align))))
1211 (defun org-table-current-line ()
1212 "Return the index of the current data line."
1213 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1215 (goto-char (org-table-begin))
1216 (while (and (re-search-forward org-table-dataline-regexp end t
)
1218 (< (point-at-eol) pos
))))
1221 (defun org-table-goto-line (N)
1222 "Go to the Nth data line in the current table.
1223 Return t when the line exists, nil if it does not exist."
1224 (goto-char (org-table-begin))
1225 (let ((end (org-table-end)) (cnt 0))
1226 (while (and (re-search-forward org-table-dataline-regexp end t
)
1227 (< (setq cnt
(1+ cnt
)) N
)))
1231 (defun org-table-blank-field ()
1232 "Blank the current table field or active region."
1234 (org-table-check-inside-data-field)
1235 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1236 (let (org-table-clip)
1237 (org-table-cut-region (region-beginning) (region-end)))
1238 (skip-chars-backward "^|")
1240 (if (looking-at "|[^|\n]+")
1241 (let* ((pos (match-beginning 0))
1242 (match (match-string 0))
1243 (len (org-string-width match
)))
1244 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1245 (goto-char (+ 2 pos
))
1246 (substring match
1)))))
1248 (defun org-table-get-field (&optional n replace
)
1249 "Return the value of the field in column N of current row.
1250 N defaults to current field.
1251 If REPLACE is a string, replace field with this value. The return value
1252 is always the old value."
1253 (and n
(org-table-goto-column n
))
1254 (skip-chars-backward "^|\n")
1256 (if (looking-at "|[^|\r\n]*")
1257 (let* ((pos (match-beginning 0))
1258 (val (buffer-substring (1+ pos
) (match-end 0))))
1260 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1262 (goto-char (min (point-at-eol) (+ 2 pos
)))
1264 (forward-char 1) ""))
1267 (defun org-table-field-info (_arg)
1268 "Show info about the current field, and highlight any reference at point."
1270 (unless (org-at-table-p) (user-error "Not at a table"))
1273 (let* ((pos (point))
1274 (col (org-table-current-column))
1275 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1276 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1277 (line-beginning-position))
1279 org-table-named-field-locations
)))
1280 (eql (org-table-expand-lhs-ranges
1283 (cons (org-table-formula-handle-first/last-rc
(car e
))
1285 (org-table-get-stored-formulas))))
1286 (dline (org-table-current-dline))
1287 (ref (format "@%d$%d" dline col
))
1288 (ref1 (org-table-convert-refs-to-an ref
))
1289 (fequation (or (assoc name eql
) (assoc ref eql
)))
1290 (cequation (assoc (int-to-string col
) eql
))
1291 (eqn (or fequation cequation
)))
1292 (let ((p (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))))
1293 (when p
(setq eqn p
)))
1295 (ignore-errors (org-table-show-reference 'local
))
1296 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1298 (if cname
(concat " or $" cname
) "")
1300 (if name
(concat " or $" name
) "")
1301 ;; FIXME: formula info not correct if special table line
1303 (concat ", formula: "
1304 (org-table-formula-to-user
1306 (if (string-match "^[$@]"(car eqn
)) "" "$")
1307 (car eqn
) "=" (cdr eqn
))))
1310 (defun org-table-current-column ()
1311 "Find out which column we are in."
1313 (when (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1315 (let ((column 0) (pos (point)))
1317 (while (search-forward "|" pos t
) (incf column
))
1318 (when (org-called-interactively-p 'interactive
)
1319 (message "In table column %d" column
))
1323 (defun org-table-current-dline ()
1324 "Find out what table data line we are in.
1325 Only data lines count for this."
1327 (when (org-called-interactively-p 'any
)
1328 (org-table-check-inside-data-field))
1332 (goto-char (org-table-begin))
1333 (while (<= (point) pos
)
1334 (when (looking-at org-table-dataline-regexp
) (incf c
))
1336 (when (org-called-interactively-p 'any
)
1337 (message "This is table line %d" c
))
1341 (defun org-table-goto-column (n &optional on-delim force
)
1342 "Move the cursor to the Nth column in the current table line.
1343 With optional argument ON-DELIM, stop with point before the left delimiter
1345 If there are less than N fields, just go to after the last delimiter.
1346 However, when FORCE is non-nil, create new columns if necessary."
1348 (beginning-of-line 1)
1350 (while (and (> (setq n
(1- n
)) -
1)
1351 (or (search-forward "|" (point-at-eol) t
)
1353 (progn (end-of-line 1)
1354 (skip-chars-backward "^|")
1357 (when (and force
(not (looking-at ".*|")))
1358 (save-excursion (end-of-line 1) (insert " | ")))
1361 (if (looking-at " ") (forward-char 1)))))
1364 (defun org-table-insert-column ()
1365 "Insert a new column into the table."
1367 (unless (org-at-table-p) (user-error "Not at a table"))
1368 (org-table-find-dataline)
1369 (let* ((col (max 1 (org-table-current-column)))
1370 (beg (org-table-begin))
1371 (end (copy-marker (org-table-end))))
1372 (org-table-save-field
1374 (while (< (point) end
)
1375 (unless (org-at-table-hline-p)
1376 (org-table-goto-column col t
)
1379 (set-marker end nil
)
1381 (when (or (not org-table-fix-formulas-confirm
)
1382 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1383 (org-table-fix-formulas "$" nil
(1- col
) 1)
1384 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1386 (defun org-table-find-dataline ()
1387 "Find a data line in the current table, which is needed for column commands."
1388 (if (and (org-at-table-p)
1389 (not (org-at-table-hline-p)))
1391 (let ((col (current-column))
1392 (end (org-table-end)))
1393 (org-move-to-column col
)
1394 (while (and (< (point) end
)
1395 (or (not (= (current-column) col
))
1396 (org-at-table-hline-p)))
1397 (beginning-of-line 2)
1398 (org-move-to-column col
))
1399 (if (and (org-at-table-p)
1400 (not (org-at-table-hline-p)))
1403 "Please position cursor in a data line for column operations")))))
1405 (defun org-table-line-to-dline (line &optional above
)
1406 "Turn a buffer line number into a data line number.
1408 If there is no data line in this line, return nil.
1410 If there is no matching dline (most likely the reference was
1411 a hline), the first dline below it is used. When ABOVE is
1412 non-nil, the one above is used."
1414 (max (1- (length org-table-dlines
))))
1415 (cond ((or (> (aref org-table-dlines min
) line
)
1416 (< (aref org-table-dlines max
) line
))
1418 ((= (aref org-table-dlines max
) line
) max
)
1420 (while (> (- max min
) 1)
1421 (let* ((mean (/ (+ max min
) 2))
1422 (v (aref org-table-dlines mean
)))
1423 (cond ((= v line
) (throw 'exit mean
))
1424 ((> v line
) (setq max mean
))
1425 (t (setq min mean
)))))
1426 (if above min max
))))))
1429 (defun org-table-delete-column ()
1430 "Delete a column from the table."
1432 (unless (org-at-table-p) (user-error "Not at a table"))
1433 (org-table-find-dataline)
1434 (org-table-check-inside-data-field)
1435 (let ((col (org-table-current-column))
1436 (beg (org-table-begin))
1437 (end (copy-marker (org-table-end))))
1438 (org-table-save-field
1440 (while (< (point) end
)
1441 (if (org-at-table-hline-p)
1443 (org-table-goto-column col t
)
1444 (and (looking-at "|[^|\n]+|")
1445 (replace-match "|")))
1447 (set-marker end nil
)
1448 (org-table-goto-column (max 1 (1- col
)))
1450 (when (or (not org-table-fix-formulas-confirm
)
1451 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1452 (org-table-fix-formulas
1453 "$" (list (cons (number-to-string col
) "INVALID")) col -
1 col
)
1454 (org-table-fix-formulas
1455 "$LR" (list (cons (number-to-string col
) "INVALID")) col -
1 col
))))
1458 (defun org-table-move-column-right ()
1459 "Move column to the right."
1461 (org-table-move-column nil
))
1463 (defun org-table-move-column-left ()
1464 "Move column to the left."
1466 (org-table-move-column 'left
))
1469 (defun org-table-move-column (&optional left
)
1470 "Move the current column to the right. With arg LEFT, move to the left."
1472 (unless (org-at-table-p) (user-error "Not at a table"))
1473 (org-table-find-dataline)
1474 (org-table-check-inside-data-field)
1475 (let* ((col (org-table-current-column))
1476 (col1 (if left
(1- col
) col
))
1477 (colpos (if left
(1- col
) (1+ col
)))
1478 (beg (org-table-begin))
1479 (end (copy-marker (org-table-end))))
1480 (when (and left
(= col
1))
1481 (user-error "Cannot move column further left"))
1482 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1483 (user-error "Cannot move column further right"))
1484 (org-table-save-field
1486 (while (< (point) end
)
1487 (unless (org-at-table-hline-p)
1488 (org-table-goto-column col1 t
)
1489 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1490 (replace-match "|\\2|\\1|")))
1492 (set-marker end nil
)
1493 (org-table-goto-column colpos
)
1495 (when (or (not org-table-fix-formulas-confirm
)
1496 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1497 (org-table-fix-formulas
1498 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1499 (cons (number-to-string colpos
) (number-to-string col
))))
1500 (org-table-fix-formulas
1501 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1502 (cons (number-to-string colpos
) (number-to-string col
)))))))
1505 (defun org-table-move-row-down ()
1506 "Move table row down."
1508 (org-table-move-row nil
))
1510 (defun org-table-move-row-up ()
1511 "Move table row up."
1513 (org-table-move-row 'up
))
1516 (defun org-table-move-row (&optional up
)
1517 "Move the current table line down. With arg UP, move it up."
1519 (let* ((col (current-column))
1521 (hline1p (save-excursion (beginning-of-line 1)
1522 (looking-at org-table-hline-regexp
)))
1523 (dline1 (org-table-current-dline))
1524 (dline2 (+ dline1
(if up -
1 1)))
1527 (beginning-of-line tonew
)
1528 (unless (org-at-table-p)
1530 (user-error "Cannot move row further"))
1531 (setq hline2p
(looking-at org-table-hline-regexp
))
1533 (beginning-of-line 1)
1535 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1536 (delete-region (point) (1+ (point-at-eol)))
1537 (beginning-of-line tonew
)
1539 (beginning-of-line 0)
1540 (org-move-to-column col
)
1541 (unless (or hline1p hline2p
1542 (not (or (not org-table-fix-formulas-confirm
)
1543 (funcall org-table-fix-formulas-confirm
1544 "Fix formulas? "))))
1545 (org-table-fix-formulas
1546 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1547 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1550 (defun org-table-insert-row (&optional arg
)
1551 "Insert a new row above the current line into the table.
1552 With prefix ARG, insert below the current line."
1554 (if (not (org-at-table-p))
1555 (user-error "Not at a table"))
1556 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1557 (new (org-table-clean-line line
)))
1558 ;; Fix the first field if necessary
1559 (if (string-match "^[ \t]*| *[#$] *|" line
)
1560 (setq new
(replace-match (match-string 0 line
) t t new
)))
1561 (beginning-of-line (if arg
2 1))
1562 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1563 (beginning-of-line 0)
1564 (re-search-forward "| ?" (point-at-eol) t
)
1565 (and (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 "|[ \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 ((org-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.
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 (org-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
))))
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-mode table is
1831 converted to table.el, all horizontal separator lines get lost, because
1832 table.el uses these as cell boundaries and has no notion of horizontal lines.
1833 A table.el table can be converted to an Org-mode table only if it does not
1834 do row or column spanning. Multiline cells will become multiple cells.
1835 Beware, Org-mode does not test if the table can be successfully converted - it
1836 blindly applies a recipe that works for simple tables."
1839 (if (org-at-table.el-p
)
1840 ;; convert to Org-mode 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.
1986 When called with a \\[universal-argument] prefix, just make the full field visible so that
1987 it can be edited in place."
1991 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1993 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1994 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1995 (remove-text-properties b e
'(org-cwidth t invisible t
1996 display t intangible t
))
1997 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1998 (font-lock-fontify-block))))
2000 (let ((pos (point-marker))
2002 (if (eq org-table-use-standard-references t
)
2003 (concat (org-number-to-letters (org-table-current-column))
2004 (int-to-string (org-table-current-dline)))
2005 (concat "@" (int-to-string (org-table-current-dline))
2006 "$" (int-to-string (org-table-current-column)))))
2007 (field (org-table-get-field))
2008 (cw (current-window-configuration))
2011 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2012 (when (and (local-variable-p 'org-field-marker
)
2013 (markerp org-field-marker
))
2014 (move-marker org-field-marker nil
))
2016 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2017 (let ((org-inhibit-startup t
)) (org-mode))
2019 (setq truncate-lines nil
)
2021 (goto-char (setq p
(point-max)))
2022 (insert (org-trim field
))
2023 (remove-text-properties p
(point-max)
2024 '(invisible t org-cwidth t display t
2027 (setq-local org-finish-function
'org-table-finish-edit-field
)
2028 (setq-local org-window-configuration cw
)
2029 (setq-local org-field-marker pos
)
2030 (message "Edit and finish with C-c C-c")))))
2032 (defun org-table-finish-edit-field ()
2033 "Finish editing a table data field.
2034 Remove all newline characters, insert the result into the table, realign
2035 the table and kill the editing buffer."
2036 (let ((pos org-field-marker
)
2037 (cw org-window-configuration
)
2038 (cb (current-buffer))
2040 (goto-char (point-min))
2041 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2042 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2043 (replace-match " "))
2044 (setq text
(org-trim (buffer-string)))
2045 (set-window-configuration cw
)
2047 (select-window (get-buffer-window (marker-buffer pos
)))
2049 (move-marker pos nil
)
2050 (org-table-check-inside-data-field)
2051 (org-table-get-field nil text
)
2053 (message "New field value inserted")))
2055 (define-minor-mode org-table-follow-field-mode
2056 "Minor mode to make the table field editor window follow the cursor.
2057 When this mode is active, the field editor window will always show the
2058 current field. The mode exits automatically when the cursor leaves the
2059 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2060 nil
" TblFollow" nil
2061 (if org-table-follow-field-mode
2062 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2064 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2065 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2066 (win (and buf
(get-buffer-window buf
))))
2067 (when win
(delete-window win
))
2069 (with-current-buffer buf
2070 (move-marker org-field-marker nil
))
2071 (kill-buffer buf
)))))
2073 (defun org-table-follow-fields-with-editor ()
2074 (if (and org-table-exit-follow-field-mode-when-leaving-table
2075 (not (org-at-table-p)))
2076 ;; We have left the table, exit the follow mode
2077 (org-table-follow-field-mode -
1)
2078 (when (org-table-check-inside-data-field 'noerror
)
2079 (let ((win (selected-window)))
2080 (org-table-edit-field nil
)
2081 (org-fit-window-to-buffer)
2082 (select-window win
)))))
2084 (defvar org-timecnt
) ; dynamically scoped parameter
2087 (defun org-table-sum (&optional beg end nlast
)
2088 "Sum numbers in region of current table column.
2089 The result will be displayed in the echo area, and will be available
2090 as kill to be inserted with \\[yank].
2092 If there is an active region, it is interpreted as a rectangle and all
2093 numbers in that rectangle will be summed. If there is no active
2094 region and point is located in a table column, sum all numbers in that
2097 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2098 numbers are assumed to be times as well (in decimal hours) and the
2099 numbers are added as such.
2101 If NLAST is a number, only the NLAST fields will actually be summed."
2104 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2106 ((and beg end
)) ; beg and end given explicitly
2107 ((org-region-active-p)
2108 (setq beg
(region-beginning) end
(region-end)))
2110 (setq col
(org-table-current-column))
2111 (goto-char (org-table-begin))
2112 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2113 (user-error "No table data"))
2114 (org-table-goto-column col
)
2116 (goto-char (org-table-end))
2117 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2118 (user-error "No table data"))
2119 (org-table-goto-column col
)
2120 (setq end
(point))))
2121 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2122 (items1 (cond ((not nlast
) items
)
2123 ((>= nlast
(length items
)) items
)
2124 (t (setq items
(reverse items
))
2125 (setcdr (nthcdr (1- nlast
) items
) nil
)
2127 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2129 (res (apply '+ numbers
))
2130 (sres (if (= org-timecnt
0)
2131 (number-to-string res
)
2132 (setq diff
(* 3600 res
)
2133 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2134 m
(floor (/ diff
60)) diff
(mod diff
60)
2136 (format "%.0f:%02.0f:%02.0f" h m s
))))
2138 (if (org-called-interactively-p 'interactive
)
2140 (substitute-command-keys
2141 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2142 (length numbers
) sres
))))
2145 (defun org-table-get-number-for-summing (s)
2147 (if (string-match "^ *|? *" s
)
2148 (setq s
(replace-match "" nil nil s
)))
2149 (if (string-match " *|? *$" s
)
2150 (setq s
(replace-match "" nil nil s
)))
2151 (setq n
(string-to-number s
))
2153 ((and (string-match "0" s
)
2154 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2155 ((string-match "\\`[ \t]+\\'" s
) nil
)
2156 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2157 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2158 (m (string-to-number (or (match-string 2 s
) "0")))
2159 (s (string-to-number (or (match-string 4 s
) "0"))))
2160 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2161 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2165 (defun org-table-current-field-formula (&optional key noerror
)
2166 "Return the formula active for the current field.
2168 Assumes that table is already analyzed. If KEY is given, return
2169 the key to this formula. Otherwise return the formula preceded
2170 with \"=\" or \":=\"."
2171 (let* ((col (org-table-current-column))
2172 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2173 (line-beginning-position))
2175 org-table-named-field-locations
)))
2176 (scol (int-to-string col
))
2177 (ref (format "@%d$%d" (org-table-current-dline) col
))
2178 (stored-list (org-table-get-stored-formulas noerror
))
2179 (ass (or (assoc name stored-list
)
2180 (assoc ref stored-list
)
2181 (assoc scol stored-list
))))
2182 (cond (key (car ass
))
2183 (ass (concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2186 (defun org-table-get-formula (&optional equation named
)
2187 "Read a formula from the minibuffer, offer stored formula as default.
2188 When NAMED is non-nil, look for a named equation."
2189 (let* ((stored-list (org-table-get-stored-formulas))
2190 (name (car (rassoc (list (count-lines org-table-current-begin-pos
2191 (line-beginning-position))
2192 (org-table-current-column))
2193 org-table-named-field-locations
)))
2194 (ref (format "@%d$%d" (org-table-current-dline)
2195 (org-table-current-column)))
2197 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2200 (int-to-string (org-table-current-column))))
2201 (name (or name ref
))
2202 (org-table-may-need-update nil
)
2203 (stored (cdr (assoc scol stored-list
)))
2205 ((and stored equation
(string-match "^ *=? *$" equation
))
2209 (t (org-table-formula-from-user
2211 (org-table-formula-to-user
2212 (format "%s formula %s%s="
2213 (if named
"Field" "Column")
2214 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2216 (if stored
(org-table-formula-to-user stored
) "")
2217 'org-table-formula-history
2220 (when (not (string-match "\\S-" eq
))
2222 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2223 (org-table-store-formulas stored-list
)
2224 (user-error "Formula removed"))
2225 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2226 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2227 (if (and name
(not named
))
2228 ;; We set the column equation, delete the named one.
2229 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2232 (setcdr (assoc scol stored-list
) eq
)
2233 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2234 (if (or mustsave
(not (equal stored eq
)))
2235 (org-table-store-formulas stored-list
))
2238 (defun org-table-store-formulas (alist)
2239 "Store the list of formulas below the current table."
2240 (setq alist
(sort alist
'org-table-formula-less-p
))
2241 (let ((case-fold-search t
))
2243 (goto-char (org-table-end))
2244 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2246 ;; don't overwrite TBLFM, we might use text properties to store stuff
2247 (goto-char (match-beginning 3))
2248 (delete-region (match-beginning 3) (match-end 0)))
2250 (insert (or (match-string 2) "#+TBLFM:")))
2252 (mapconcat (lambda (x)
2254 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2255 (car x
) "=" (cdr x
)))
2259 (defsubst org-table-formula-make-cmp-string
(a)
2260 (when (string-match "\\`$[<>]" a
)
2261 (let ((arrow (string-to-char (substring a
1))))
2262 ;; Fake a high number to make sure this is sorted at the end.
2263 (setq a
(org-table-formula-handle-first/last-rc a
))
2264 (setq a
(format "$%d" (+ 10000
2265 (if (= arrow ?
<) -
1000 0)
2266 (string-to-number (substring a
1)))))))
2268 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2272 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2274 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2276 (concat "@@" (match-string 5 a
))))))
2278 (defun org-table-formula-less-p (a b
)
2279 "Compare two formulas for sorting."
2280 (let ((as (org-table-formula-make-cmp-string (car a
)))
2281 (bs (org-table-formula-make-cmp-string (car b
))))
2282 (and as bs
(string< as bs
))))
2285 (defun org-table-get-stored-formulas (&optional noerror
)
2286 "Return an alist with the stored formulas directly after current table."
2287 (interactive) ;; FIXME interactive?
2288 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2290 (goto-char (org-table-end))
2291 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2292 (setq strings
(org-split-string (org-match-string-no-properties 2)
2294 (while (setq string
(pop strings
))
2295 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2296 (setq scol
(if (match-end 2)
2297 (match-string 2 string
)
2298 (match-string 1 string
))
2299 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2300 (concat "$" scol
) scol
)
2301 eq
(match-string 3 string
)
2302 eq-alist
(cons (cons scol eq
) eq-alist
))
2303 (if (member scol seen
)
2306 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2309 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2310 (push scol seen
))))))
2311 (nreverse eq-alist
)))
2313 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2314 "Modify the equations after the table structure has been edited.
2315 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2316 For all numbers larger than LIMIT, shift them by DELTA."
2318 (goto-char (org-table-end))
2319 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2320 (let ((msg "The formulas in #+TBLFM have been updated")
2321 (re (concat key
"\\([0-9]+\\)"))
2324 (if (or (equal key
"$") (equal key
"$LR"))
2325 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2326 (regexp-quote key
) remove
)
2327 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2330 (while (re-search-forward re2
(point-at-eol) t
)
2331 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2332 (if (equal (char-before (match-beginning 0)) ?.
)
2334 "Change makes TBLFM term %s invalid, use undo to recover"
2336 (replace-match "")))))
2337 (while (re-search-forward re
(point-at-eol) t
)
2338 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2339 (setq s
(match-string 1) n
(string-to-number s
))
2341 ((setq a
(assoc s replace
))
2342 (replace-match (concat key
(cdr a
)) t t
)
2344 ((and limit
(> n limit
))
2345 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2350 (defun org-table-maybe-eval-formula ()
2351 "Check if the current field starts with \"=\" or \":=\".
2352 If yes, store the formula and apply it."
2353 ;; We already know we are in a table. Get field will only return a formula
2354 ;; when appropriate. It might return a separator line, but no problem.
2355 (when org-table-formula-evaluate-inline
2356 (let* ((field (org-trim (or (org-table-get-field) "")))
2358 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2359 (setq named
(equal (string-to-char field
) ?
:)
2360 eq
(match-string 1 field
))
2361 (if (or (fboundp 'calc-eval
)
2362 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2363 (org-table-eval-formula (if named
'(4) nil
)
2364 (org-table-formula-from-user eq
))
2365 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2367 (defvar org-recalc-commands nil
2368 "List of commands triggering the recalculation of a line.
2369 Will be filled automatically during use.")
2371 (defvar org-recalc-marks
2372 '((" " .
"Unmarked: no special line, no automatic recalculation")
2373 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2374 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2375 ("!" .
"Column name definition line. Reference in formula as $name.")
2376 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2377 ("_" .
"Names for values in row below this one.")
2378 ("^" .
"Names for values in row above this one.")))
2381 (defun org-table-rotate-recalc-marks (&optional newchar
)
2382 "Rotate the recalculation mark in the first column.
2383 If in any row, the first field is not consistent with a mark,
2384 insert a new column for the markers.
2385 When there is an active region, change all the lines in the region,
2386 after prompting for the marking character.
2387 After each change, a message will be displayed indicating the meaning
2390 (unless (org-at-table-p) (user-error "Not at a table"))
2391 (let* ((region (org-region-active-p))
2393 (save-excursion (goto-char (region-beginning))
2394 (copy-marker (line-beginning-position)))))
2396 (save-excursion (goto-char (region-end))
2397 (copy-marker (line-beginning-position)))))
2398 (l (copy-marker (line-beginning-position)))
2399 (col (org-table-current-column))
2402 (read-char-exclusive
2403 "Change region to what mark? Type # * ! $ or SPC: "))
2407 (goto-char (org-table-begin))
2409 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2410 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2411 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2413 (when l1
(goto-char l1
))
2416 (unless (looking-at org-table-dataline-regexp
)
2417 (user-error "Not at a table data line")))
2418 (when no-special-column
2419 (org-table-goto-column 1)
2420 (org-table-insert-column))
2421 (let ((previous-line-end (line-end-position))
2425 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2427 (t (cadr (member (match-string 1)
2428 (append (mapcar #'car org-recalc-marks
)
2430 ;; Rotate mark in first row.
2431 (org-table-get-field 1 (format " %s " newchar
))
2432 ;; Rotate marks in additional rows if a region is active.
2436 (while (<= (point) l2
)
2437 (when (looking-at org-table-dataline-regexp
)
2438 (org-table-get-field 1 (format " %s " newchar
)))
2440 ;; Only align if rotation actually changed lines' length.
2441 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2443 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2444 (when l1
(set-marker l1 nil
))
2445 (when l2
(set-marker l2 nil
))
2447 (when (org-called-interactively-p 'interactive
)
2448 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2451 (defun org-table-analyze ()
2452 "Analyze table at point and store results.
2454 This function sets up the following dynamically scoped variables:
2456 `org-table-column-name-regexp',
2457 `org-table-column-names',
2458 `org-table-current-begin-pos',
2459 `org-table-current-line-types',
2460 `org-table-current-ncol',
2463 `org-table-local-parameters',
2464 `org-table-named-field-locations'."
2465 (let ((beg (org-table-begin))
2466 (end (org-table-end)))
2469 ;; Extract column names.
2470 (setq org-table-column-names nil
)
2471 (when (save-excursion
2472 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
2474 (dolist (name (org-split-string (match-string 1) " *| *"))
2476 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
2477 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
2478 (setq org-table-column-names
(nreverse org-table-column-names
))
2479 (setq org-table-column-name-regexp
2480 (format "\\$\\(%s\\)\\>"
2481 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
2482 ;; Extract local parameters.
2483 (setq org-table-local-parameters nil
)
2485 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2486 (dolist (field (org-split-string (match-string 1) " *| *"))
2488 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2489 (push (cons (match-string 1 field
) (match-string 2 field
))
2490 org-table-local-parameters
)))))
2491 ;; Update named fields locations. We minimize `count-lines'
2492 ;; processing by storing last known number of lines in LAST.
2493 (setq org-table-named-field-locations nil
)
2495 (let ((last (cons (point) 0)))
2496 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2497 (let ((c (match-string 1))
2498 (fields (org-split-string (match-string 2) " *| *")))
2500 (forward-line (if (equal c
"_") 1 -
1))
2502 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2503 (org-split-string (match-string 1) " *| *")))
2504 (line (incf (cdr last
) (count-lines (car last
) (point))))
2506 (setcar last
(point)) ; Update last known position.
2507 (while (and fields fields1
)
2508 (let ((field (pop fields
))
2511 (when (and (stringp field
)
2513 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
2515 (push (cons field v
) org-table-local-parameters
)
2516 (push (list field line col
)
2517 org-table-named-field-locations
))))))))))
2518 ;; Re-use existing markers when possible.
2519 (if (markerp org-table-current-begin-pos
)
2520 (move-marker org-table-current-begin-pos
(point))
2521 (setq org-table-current-begin-pos
(point-marker)))
2522 ;; Analyze the line types.
2523 (let ((l 0) hlines dlines types
)
2524 (while (looking-at "[ \t]*|\\(-\\)?")
2525 (push (if (match-end 1) 'hline
'dline
) types
)
2526 (if (match-end 1) (push l hlines
) (push l dlines
))
2529 (push 'hline types
) ; Add an imaginary extra hline to the end.
2530 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
2531 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
2532 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
))))
2534 (let* ((last-dline (car dlines
))
2535 (fields (org-split-string
2536 (buffer-substring (line-beginning-position)
2537 (line-end-position))
2539 (nfields (length fields
))
2541 (setq org-table-current-ncol nfields
)
2542 (dotimes (i nfields
)
2543 (let ((column (1+ i
)))
2544 (push (list (format "LR%d" column
) last-dline column
) al
)
2545 (push (cons (format "LR%d" column
) (nth i fields
)) al2
)))
2546 (setq org-table-named-field-locations
2547 (append org-table-named-field-locations al
))
2548 (setq org-table-local-parameters
2549 (append org-table-local-parameters al2
)))))))
2551 (defun org-table-goto-field (ref &optional create-column-p
)
2552 "Move point to a specific field in the current table.
2554 REF is either the name of a field its absolute reference, as
2555 a string. No column is created unless CREATE-COLUMN-P is
2556 non-nil. If it is a function, it is called with the column
2557 number as its argument as is used as a predicate to know if the
2558 column can be created.
2560 This function assumes the table is already analyzed (i.e., using
2561 `org-table-analyze')."
2564 ((cdr (assoc ref org-table-named-field-locations
)))
2565 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
2566 (list (condition-case nil
2567 (aref org-table-dlines
2568 (string-to-number (match-string 1 ref
)))
2569 (error (user-error "Invalid row number in %s" ref
)))
2570 (string-to-number (match-string 2 ref
))))
2571 (t (user-error "Unknown field: %s" ref
))))
2572 (line (car coordinates
))
2573 (column (nth 1 coordinates
))
2574 (create-new-column (if (functionp create-column-p
)
2575 (funcall create-column-p column
)
2578 (goto-char org-table-current-begin-pos
)
2580 (org-table-goto-column column nil create-new-column
))))
2583 (defun org-table-maybe-recalculate-line ()
2584 "Recompute the current line if marked for it, and if we haven't just done it."
2586 (and org-table-allow-automatic-line-recalculation
2587 (not (and (memq last-command org-recalc-commands
)
2588 (eq org-last-recalc-line
(line-beginning-position))))
2589 (save-excursion (beginning-of-line 1)
2590 (looking-at org-table-auto-recalculate-regexp
))
2591 (org-table-recalculate) t
))
2593 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2594 (defsubst org-set-calc-mode
(var &optional value
)
2596 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2597 ("R" calc-angle-mode rad
)
2598 ("F" calc-prefer-frac t
)
2599 ("S" calc-symbolic-mode t
)))
2600 value
(nth 2 var
) var
(nth 1 var
)))
2601 (if (memq var org-tbl-calc-modes
)
2602 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2603 (cons var
(cons value org-tbl-calc-modes
)))
2607 (defun org-table-eval-formula (&optional arg equation
2608 suppress-align suppress-const
2609 suppress-store suppress-analysis
)
2610 "Replace the table field value at the cursor by the result of a calculation.
2612 This function makes use of Dave Gillespie's Calc package, in my view the
2613 most exciting program ever written for GNU Emacs. So you need to have Calc
2614 installed in order to use this function.
2616 In a table, this command replaces the value in the current field with the
2617 result of a formula. It also installs the formula as the \"current\" column
2618 formula, by storing it in a special line below the table. When called
2619 with a `C-u' prefix, the current field must be a named field, and the
2620 formula is installed as valid in only this specific field.
2622 When called with two `C-u' prefixes, insert the active equation
2623 for the field back into the current field, so that it can be
2624 edited there. This is useful in order to use \\[org-table-show-reference]
2625 to check the referenced fields.
2627 When called, the command first prompts for a formula, which is read in
2628 the minibuffer. Previously entered formulas are available through the
2629 history list, and the last used formula is offered as a default.
2630 These stored formulas are adapted correctly when moving, inserting, or
2631 deleting columns with the corresponding commands.
2633 The formula can be any algebraic expression understood by the Calc package.
2634 For details, see the Org-mode manual.
2636 This function can also be called from Lisp programs and offers
2637 additional arguments: EQUATION can be the formula to apply. If this
2638 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2639 used to speed-up recursive calls by by-passing unnecessary aligns.
2640 SUPPRESS-CONST suppresses the interpretation of constants in the
2641 formula, assuming that this has been done already outside the function.
2642 SUPPRESS-STORE means the formula should not be stored, either because
2643 it is already stored, or because it is a modified equation that should
2644 not overwrite the stored one."
2646 (org-table-check-inside-data-field)
2647 (or suppress-analysis
(org-table-analyze))
2648 (if (equal arg
'(16))
2649 (let ((eq (org-table-current-field-formula)))
2650 (or eq
(user-error "No equation active for current field"))
2651 (org-table-get-field nil eq
)
2653 (setq org-table-may-need-update t
))
2655 (ndown (if (integerp arg
) arg
1))
2656 (org-table-automatic-realign nil
)
2657 (case-fold-search nil
)
2659 (formula (if (and equation suppress-store
)
2661 (org-table-get-formula equation
(equal arg
'(4)))))
2662 (n0 (org-table-current-column))
2663 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2664 (numbers nil
) ; was a variable, now fixed default
2666 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2667 duration duration-output-format
)
2668 ;; Parse the format string. Since we have a lot of modes, this is
2669 ;; a lot of work. However, I think calc still uses most of the time.
2670 (if (string-match ";" formula
)
2671 (let ((tmp (org-split-string formula
";")))
2672 (setq formula
(car tmp
)
2673 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2675 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2676 (setq c
(string-to-char (match-string 1 fmt
))
2677 n
(string-to-number (match-string 2 fmt
)))
2679 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2680 (setq org-tbl-calc-modes
2683 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2684 (?s . sci
) (?e . eng
))))
2686 (setq fmt
(replace-match "" t t fmt
)))
2687 (if (string-match "T" fmt
)
2688 (setq duration t numbers t
2689 duration-output-format nil
2690 fmt
(replace-match "" t t fmt
)))
2691 (if (string-match "t" fmt
)
2693 duration-output-format org-table-duration-custom-format
2695 fmt
(replace-match "" t t fmt
)))
2696 (if (string-match "N" fmt
)
2698 fmt
(replace-match "" t t fmt
)))
2699 (if (string-match "L" fmt
)
2701 fmt
(replace-match "" t t fmt
)))
2702 (if (string-match "E" fmt
)
2704 fmt
(replace-match "" t t fmt
)))
2705 (while (string-match "[DRFS]" fmt
)
2706 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2707 (setq fmt
(replace-match "" t t fmt
)))
2708 (unless (string-match "\\S-" fmt
)
2710 (if (and (not suppress-const
) org-table-formula-use-constants
)
2711 (setq formula
(org-table-formula-substitute-names formula
)))
2712 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2714 (setq fields
(org-split-string
2715 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2717 ;; replace fields with duration values if relevant
2720 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2723 (setq fields
(mapcar
2725 (if (string-match "\\S-" x
)
2726 (number-to-string (string-to-number x
))
2729 (setq ndown
(1- ndown
))
2730 (setq form
(copy-sequence formula
)
2731 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2732 (if (and lispp literal
) (setq lispp
'literal
))
2734 ;; Insert row and column number of formula result field
2735 (while (string-match "[@$]#" form
)
2740 (if (equal (substring form
(match-beginning 0)
2741 (1+ (match-beginning 0)))
2743 (org-table-current-dline)
2744 (org-table-current-column))))
2747 ;; Check for old vertical references
2748 (org-table--error-on-old-row-references form
)
2749 ;; Insert remote references
2750 (setq form
(org-table-remote-reference-indirection form
))
2751 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2755 (org-table-make-reference
2756 (let ((rmtrng (org-table-get-remote-range
2757 (match-string 1 form
) (match-string 2 form
))))
2760 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2761 (org-table-time-string-to-seconds rmtrng
))
2763 keep-empty numbers lispp
))
2765 ;; Insert complex ranges
2766 (while (and (string-match org-table-range-regexp form
)
2767 (> (length (match-string 0 form
)) 1))
2770 (org-table-get-range
2771 (match-string 0 form
) org-table-current-begin-pos n0
)))
2774 (org-table-make-reference
2775 ;; possibly handle durations
2778 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2779 (org-table-time-string-to-seconds formrg
))
2781 keep-empty numbers lispp
)))
2782 (if (not (save-match-data
2783 (string-match (regexp-quote form
) formrpl
)))
2784 (setq form
(replace-match formrpl t t form
))
2785 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2786 ;; Insert simple ranges, i.e. included in the current row.
2787 (while (string-match
2788 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2793 (org-table-make-reference
2795 (+ (if (match-end 2) n0
0)
2796 (string-to-number (match-string 1 form
))
2798 (+ (if (match-end 4) n0
0)
2799 (string-to-number (match-string 3 form
))))
2800 keep-empty numbers lispp
))
2803 ;; Insert the references to fields in same row
2804 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2805 (setq n
(+ (string-to-number (match-string 1 form
))
2806 (if (match-end 2) n0
0))
2807 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2808 formrpl
(save-match-data
2809 (org-table-make-reference
2810 x keep-empty numbers lispp
)))
2813 (string-match (regexp-quote formula
) formrpl
)))
2814 (user-error "Invalid field specifier \"%s\""
2815 (match-string 0 form
)))
2816 (setq form
(replace-match formrpl t t form
)))
2819 (setq ev
(condition-case nil
2820 (eval (eval (read form
)))
2822 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2823 ev
(if duration
(org-table-time-seconds-to-string
2824 (string-to-number ev
)
2825 duration-output-format
) ev
))
2826 (or (fboundp 'calc-eval
)
2827 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2828 ;; Use <...> time-stamps so that Calc can handle them
2829 (while (string-match (concat "\\[" org-ts-regexp1
"\\]") form
)
2830 (setq form
(replace-match "<\\1>" nil nil form
)))
2831 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2832 (when (string-match org-ts-regexp2 form
)
2833 (let* ((ts (match-string 0 form
))
2834 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2835 (system-time-locale "C")
2836 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2837 (cdr org-time-stamp-formats
))
2838 (car org-time-stamp-formats
))))
2839 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2841 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2843 (calc-eval (cons form org-tbl-calc-modes
)
2844 (when (and (not keep-empty
) numbers
) 'num
)))
2845 ev
(if duration
(org-table-time-seconds-to-string
2846 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2847 (string-to-number (org-table-time-string-to-seconds ev
))
2848 (string-to-number ev
))
2849 duration-output-format
)
2852 (when org-table-formula-debug
2853 (with-output-to-temp-buffer "*Substitution History*"
2854 (princ (format "Substitution history of formula
2858 $1-> %s\n" orig formula form0 form
))
2860 (princ (format " %s^\nError: %s"
2861 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2862 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2864 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2865 (setq bw
(get-buffer-window "*Substitution History*"))
2866 (org-fit-window-to-buffer bw
)
2867 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2868 (unless (let (inhibit-redisplay)
2869 (y-or-n-p "Debugging Formula. Continue to next? "))
2871 (user-error "Abort"))
2874 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2875 (org-table-justify-field-maybe
2876 (format org-table-formula-field-format
2877 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2878 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2879 (call-interactively 'org-return
)
2881 (and down
(org-table-maybe-recalculate-line))
2882 (or suppress-align
(and org-table-may-need-update
2883 (org-table-align))))))
2885 (defun org-table-put-field-property (prop value
)
2887 (put-text-property (progn (skip-chars-backward "^|") (point))
2888 (progn (skip-chars-forward "^|") (point))
2891 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2892 "Get a calc vector from a column, according to descriptor DESC.
2894 Optional arguments TBEG and COL can give the beginning of the table and
2895 the current column, to avoid unnecessary parsing.
2897 HIGHLIGHT means just highlight the range.
2899 When CORNERS-ONLY is set, only return the corners of the range as
2900 a list (line1 column1 line2 column2) where line1 and line2 are
2901 line numbers relative to beginning of table, or TBEG, and column1
2902 and column2 are table column numbers."
2903 (let* ((desc (if (eq (string-to-char desc
) ?
@) desc
(concat "@" desc
)))
2904 (col (or col
(org-table-current-column)))
2905 (tbeg (or tbeg
(org-table-begin)))
2906 (thisline (count-lines tbeg
(line-beginning-position))))
2907 (unless (string-match org-table-range-regexp desc
)
2908 (user-error "Invalid table range specifier `%s'" desc
))
2909 (let ((rangep (match-end 3))
2910 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2911 (or (save-match-data
2912 (and (org-string-nw-p r
)
2913 (org-table--descriptor-line r thisline
)))
2915 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
2916 (or (save-match-data
2917 (and (org-string-nw-p r
)
2918 (org-table--descriptor-line r thisline
)))
2920 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
2921 (if (or (not c
) (= (string-to-number c
) 0)) col
2922 (+ (string-to-number c
)
2923 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
2924 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
2925 (if (or (not c
) (= (string-to-number c
) 0)) col
2926 (+ (string-to-number c
)
2927 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
2929 (if (and (not corners-only
)
2930 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2933 (forward-line (- r1 thisline
))
2934 (while (not (looking-at org-table-dataline-regexp
))
2936 (prog1 (org-trim (org-table-get-field c1
))
2937 (when highlight
(org-table-highlight-rectangle))))
2938 ;; A range, return a vector. First sort the numbers to get
2939 ;; a regular rectangle.
2940 (let ((first-row (min r1 r2
))
2941 (last-row (max r1 r2
))
2942 (first-column (min c1 c2
))
2943 (last-column (max c1 c2
)))
2944 (if corners-only
(list first-row first-column last-row last-column
)
2945 ;; Copy the range values into a list.
2946 (forward-line (- first-row thisline
))
2947 (while (not (looking-at org-table-dataline-regexp
))
2950 (org-table-goto-column first-column
)
2951 (let ((beg (point)))
2952 (forward-line (- last-row first-row
))
2953 (while (not (looking-at org-table-dataline-regexp
))
2955 (org-table-goto-column last-column
)
2956 (let ((end (point)))
2958 (org-table-highlight-rectangle
2959 beg
(progn (skip-chars-forward "^|\n") (point))))
2960 ;; Return string representation of calc vector.
2963 (org-table-copy-region beg end
))))))))))))
2965 (defun org-table--descriptor-line (desc cline
)
2966 "Return relative line number corresponding to descriptor DESC.
2967 The cursor is currently in relative line number CLINE."
2968 (if (string-match "\\`[0-9]+\\'" desc
)
2969 (aref org-table-dlines
(string-to-number desc
))
2970 (when (or (not (string-match
2971 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
2974 (and (not (match-end 3)) (not (match-end 6)))
2975 (and (match-end 3) (match-end 6) (not (match-end 5))))
2976 (user-error "Invalid row descriptor `%s'" desc
))
2977 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
2978 (hdir (match-string 2 desc
))
2979 (odir (match-string 5 desc
))
2980 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
2981 (rel (and (match-end 6)
2982 (or (and (match-end 1) (not (match-end 3)))
2984 (when (and hn
(not hdir
))
2987 (when (eq (aref org-table-current-line-types
0) 'hline
) (decf hn
)))
2988 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
2991 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
2994 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
2997 (defun org-table--row-type (type n i backwards relative desc
)
2998 "Return relative line of Nth row with type TYPE.
2999 Search starts from relative line I. When BACKWARDS in non-nil,
3000 look before I. When RELATIVE is non-nil, the reference is
3001 relative. DESC is the original descriptor that started the
3002 search, as a string."
3003 (let ((l (length org-table-current-line-types
)))
3006 (while (and (incf i
(if backwards -
1 1))
3009 (not (eq (aref org-table-current-line-types i
) type
))
3010 ;; We are going to cross a hline. Check if this is
3011 ;; an authorized move.
3014 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
3015 ((eq org-table-relative-ref-may-cross-hline t
))
3016 ((eq org-table-relative-ref-may-cross-hline
'error
)
3017 (user-error "Row descriptor %s crosses hline" desc
))
3018 (t (decf i
(if backwards -
1 1)) ; Step back.
3019 (throw :exit nil
)))))))
3020 (cond ((or (< i
0) (>= i l
))
3021 (user-error "Row descriptor %s leads outside table" desc
))
3022 ;; The last hline doesn't exist. Instead, point to last row
3024 ((= i
(1- l
)) (1- i
))
3027 (defun org-table--error-on-old-row-references (s)
3028 (when (string-match "&[-+0-9I]" s
)
3029 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3031 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3032 "Convert list ELEMENTS to something appropriate to insert into formula.
3033 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3034 NUMBERS indicates that everything should be converted to numbers.
3035 LISPP non-nil means to return something appropriate for a Lisp
3036 list, `literal' is for the format specifier L."
3037 ;; Calc nan (not a number) is used for the conversion of the empty
3038 ;; field to a reference for several reasons: (i) It is accepted in a
3039 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3040 ;; (ii) In a single field (not in range) it can be distinguished
3041 ;; from "(nan)" which is the reference made from a single field
3042 ;; containing "nan".
3043 (if (stringp elements
)
3046 (if (eq lispp
'literal
)
3048 (if (and (eq elements
"") (not keep-empty
))
3051 (if numbers
(string-to-number elements
) elements
))))
3052 (if (string-match "\\S-" elements
)
3054 (when numbers
(setq elements
(number-to-string
3055 (string-to-number elements
))))
3056 (concat "(" elements
")"))
3057 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3062 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3064 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3068 (if (eq lispp
'literal
)
3070 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3072 (concat "[" (mapconcat
3074 (if (string-match "\\S-" x
)
3076 (number-to-string (string-to-number x
))
3078 (if (or (not keep-empty
) numbers
) "0" "nan")))
3082 (defun org-table-message-once-per-second (t1 &rest args
)
3083 "If there has been more than one second since T1, display message.
3084 ARGS are passed as arguments to the `message' function. Returns
3085 current time if a message is printed, otherwise returns T1. If
3086 T1 is nil, always messages."
3087 (let ((curtime (current-time)))
3088 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3089 (progn (apply 'message args
)
3094 (defun org-table-recalculate (&optional all noalign
)
3095 "Recalculate the current table line by applying all stored formulas.
3096 With prefix arg ALL, do this for all lines in the table.
3097 With the prefix argument ALL is `(16)' \
3098 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3099 it is the symbol `iterate', recompute the table until it no longer changes.
3100 If NOALIGN is not nil, do not re-align the table after the computations
3101 are done. This is typically used internally to save time, if it is
3102 known that the table will be realigned a little later anyway."
3104 (unless (memq this-command org-recalc-commands
)
3105 (push this-command org-recalc-commands
))
3106 (unless (org-at-table-p) (user-error "Not at a table"))
3107 (if (or (eq all
'iterate
) (equal all
'(16)))
3110 (let* ((eqlist (sort (org-table-get-stored-formulas)
3111 (lambda (a b
) (string< (car a
) (car b
)))))
3112 (eqlist1 (copy-sequence eqlist
))
3113 (inhibit-redisplay (not debug-on-error
))
3114 (line-re org-table-dataline-regexp
)
3115 (log-first-time (current-time))
3116 (log-last-time log-first-time
)
3118 beg end eqlnum eqlname
)
3119 ;; Insert constants in all formulas
3121 (org-table-save-field
3125 (when (string-match "\\`@-?I+" (car x
))
3126 (user-error "Can't assign to hline relative reference"))
3127 (when (string-match "\\`$[<>]" (car x
))
3128 (let ((old-lhs (car x
)))
3132 (org-table-formula-handle-first/last-rc old-lhs
)
3135 (when (assoc (car x
) eqlist1
)
3136 (user-error "\"%s=\" formula tries to overwrite \
3137 existing formula for column %s"
3140 (cons (org-table-formula-handle-first/last-rc
(car x
))
3141 (org-table-formula-substitute-names
3142 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3144 ;; Split the equation list.
3146 (if (<= (string-to-char (car eq
)) ?
9)
3149 (setq eqlnum
(nreverse eqlnum
))
3150 ;; Expand ranges in lhs of formulas
3151 (setq eqlname
(org-table-expand-lhs-ranges (nreverse eqlname
)))
3152 ;; Get the correct line range to process
3155 (setq end
(copy-marker (org-table-end)))
3156 (goto-char (setq beg org-table-current-begin-pos
))
3158 ((re-search-forward org-table-calculate-mark-regexp end t
)
3159 ;; This is a table with marked lines, compute selected
3161 (setq line-re org-table-recalculate-regexp
))
3162 ;; Move forward to the first non-header line.
3163 ((and (re-search-forward org-table-dataline-regexp end t
)
3164 (re-search-forward org-table-hline-regexp end t
)
3165 (re-search-forward org-table-dataline-regexp end t
))
3166 (setq beg
(match-beginning 0)))
3167 ;; Just leave BEG where it is.
3169 (setq beg
(line-beginning-position)
3170 end
(copy-marker (line-beginning-position 2))))
3172 ;; Mark named fields untouchable. Also check if several
3173 ;; field/range formulas try to set the same field.
3174 (remove-text-properties beg end
'(org-untouchable t
))
3175 (let ((current-line (count-lines org-table-current-begin-pos
3176 (line-beginning-position)))
3178 (dolist (eq eqlname
)
3179 (let* ((name (car eq
))
3180 (location (assoc name org-table-named-field-locations
))
3181 (eq-line (or (nth 1 location
)
3182 (and (string-match "\\`@\\([0-9]+\\)" name
)
3183 (aref org-table-dlines
3185 (match-string 1 name
))))))
3188 ;; Turn field coordinates associated to NAME
3189 ;; into an absolute reference.
3191 (org-table-line-to-dline eq-line
)
3194 (when (member reference seen-fields
)
3195 (user-error "Several field/range formulas try to set %s"
3197 (push reference seen-fields
)
3198 (when (or all
(eq eq-line current-line
))
3199 (org-table-goto-field name
)
3200 (org-table-put-field-property :org-untouchable t
)))))
3201 ;; Evaluate the column formulas, but skip fields covered by
3204 (while (re-search-forward line-re end t
)
3205 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
3206 ;; Unprotected line, recalculate.
3210 (org-table-message-once-per-second
3212 "Re-applying formulas to full table...(line %d)" cnt
)))
3213 (if (markerp org-last-recalc-line
)
3214 (move-marker org-last-recalc-line
(line-beginning-position))
3215 (setq org-last-recalc-line
3216 (copy-marker (line-beginning-position))))
3217 (dolist (entry eqlnum
)
3218 (goto-char org-last-recalc-line
)
3219 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3220 (unless (get-text-property (point) :org-untouchable
)
3221 (org-table-eval-formula
3222 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
3223 ;; Evaluate the field formulas.
3224 (dolist (eq eqlname
)
3225 (let ((reference (car eq
))
3228 (org-table-message-once-per-second
3229 (and all log-last-time
)
3230 "Re-applying formula to field: %s" (car eq
)))
3231 (org-table-goto-field
3233 ;; Possibly create a new column, as long as
3234 ;; `org-table-formula-create-columns' allows it.
3235 (let ((column-count (progn (end-of-line)
3236 (1- (org-table-current-column)))))
3238 (when (> column
1000)
3239 (user-error "Formula column target too large"))
3240 (and (> column
,column-count
)
3241 (or (eq org-table-formula-create-columns t
)
3242 (and (eq org-table-formula-create-columns
'warn
)
3244 (org-display-warning
3245 "Out-of-bounds formula added columns")
3247 (and (eq org-table-formula-create-columns
'prompt
)
3249 "Out-of-bounds formula. Add columns? ")))))))
3250 (org-table-eval-formula nil formula t t t t
))))
3251 ;; Clean up markers and internal text property.
3252 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3253 (set-marker end nil
)
3255 (when org-table-may-need-update
(org-table-align))
3257 (org-table-message-once-per-second
3258 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
3259 (org-table-message-once-per-second
3260 (and all log-first-time
) "Re-applying formulas... done")))))
3263 (defun org-table-iterate (&optional arg
)
3264 "Recalculate the table until it does not change anymore.
3265 The maximum number of iterations is 10, but you can choose a different value
3266 with the prefix ARG."
3268 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3270 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3275 (org-table-recalculate 'all
)
3276 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3277 (if (not (string= lasttbl thistbl
))
3278 (setq lasttbl thistbl
)
3280 (message "Convergence after %d iterations" i
)
3281 (message "Table was already stable"))
3283 (user-error "No convergence after %d iterations" i
))))
3286 (defun org-table-recalculate-buffer-tables ()
3287 "Recalculate all tables in the current buffer."
3292 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3295 (defun org-table-iterate-buffer-tables ()
3296 "Iterate all tables in the buffer, to converge inter-table dependencies."
3300 (checksum (md5 (buffer-string)))
3308 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3309 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3311 (message "Convergence after %d iterations" (- imax i
))
3313 (setq checksum c1
)))
3314 (user-error "No convergence after %d iterations" imax
))))))
3316 (defun org-table-calc-current-TBLFM (&optional arg
)
3317 "Apply the #+TBLFM in the line at point to the table."
3319 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3320 (let ((formula (buffer-substring
3321 (line-beginning-position)
3322 (line-end-position))))
3324 ;; Insert a temporary formula at right after the table
3325 (goto-char (org-table-TBLFM-begin))
3326 (let ((s (point-marker)))
3327 (insert formula
"\n")
3328 (let ((e (point-marker)))
3329 ;; Recalculate the table.
3330 (beginning-of-line 0) ; move to the inserted line
3331 (skip-chars-backward " \r\n\t")
3333 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3334 ;; Delete the formula inserted temporarily.
3337 (set-marker e nil
)))))))
3339 (defun org-table-TBLFM-begin ()
3340 "Find the beginning of the TBLFM lines and return its position.
3341 Return nil when the beginning of TBLFM line was not found."
3343 (when (progn (forward-line 1)
3344 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3345 (line-beginning-position 2))))
3347 (defun org-table-expand-lhs-ranges (equations)
3348 "Expand list of formulas.
3349 If some of the RHS in the formulas are ranges or a row reference, expand
3350 them to individual field equations for each field."
3352 (dolist (e equations
(nreverse res
))
3356 ((string-match "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3357 ;; This just refers to one fixed field.
3359 ((string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3360 ;; This just refers to one fixed named field.
3362 ((string-match "\\`@[0-9]+\\'" lhs
)
3363 (dotimes (ic org-table-current-ncol
)
3364 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3368 (let* ((range (org-table-get-range
3369 lhs org-table-current-begin-pos
1 nil
'corners
))
3370 (r1 (org-table-line-to-dline (nth 0 range
)))
3372 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3374 (loop for ir from r1 to r2 do
3375 (loop for ic from c1 to c2 do
3377 (cons (propertize (format "@%d$%d" ir ic
) :orig-eqn e
)
3381 (defun org-table-formula-handle-first/last-rc
(s)
3382 "Replace @<, @>, $<, $> with first/last row/column of the table.
3383 So @< and $< will always be replaced with @1 and $1, respectively.
3384 The advantage of these special markers are that structure editing of
3385 the table will not change them, while @1 and $1 will be modified
3386 when a line/row is swapped out of that privileged position. So for
3387 formulas that use a range of rows or columns, it may often be better
3388 to anchor the formula with \"I\" row markers, or to offset from the
3389 borders of the table using the @< @> $< $> makers."
3390 (let (n nmax len char
(start 0))
3391 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3394 (setq start
(match-end 3))
3395 (setq nmax
(if (equal (match-string 1 s
) "@")
3396 (1- (length org-table-dlines
))
3397 org-table-current-ncol
)
3398 len
(- (match-end 2) (match-beginning 2))
3399 char
(string-to-char (match-string 2 s
))
3403 (if (or (< n
1) (> n nmax
))
3404 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3405 (match-string 0 s
) s
))
3406 (setq start
(match-beginning 0))
3407 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3410 (defun org-table-formula-substitute-names (f)
3411 "Replace $const with values in string F."
3413 (pp (/= (string-to-char f
) ?
'))
3414 (duration (org-string-match-p ";.*[Tt].*\\'" f
))
3415 (new (replace-regexp-in-string ; Check for column names.
3416 org-table-column-name-regexp
3418 (concat "$" (cdr (assoc (match-string 1 m
)
3419 org-table-column-names
))))
3421 ;; Parameters and constants.
3424 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3426 (if (match-end 2) (setq start
(match-end 2))
3428 ;; When a duration is expected, convert value on the fly.
3431 (let ((v (org-table-get-constant (match-string 1 new
))))
3432 (if (and (org-string-nw-p v
) duration
)
3433 (org-table-time-string-to-seconds v
)
3436 (setq new
(replace-match
3437 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3438 (if org-table-formula-debug
(org-propertize new
:orig-formula f
)) new
))
3440 (defun org-table-get-constant (const)
3441 "Find the value for a parameter or constant in a formula.
3442 Parameters get priority."
3443 (or (cdr (assoc const org-table-local-parameters
))
3444 (cdr (assoc const org-table-formula-constants-local
))
3445 (cdr (assoc const org-table-formula-constants
))
3446 (and (fboundp 'constants-get
) (constants-get const
))
3447 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3448 (org-entry-get nil
(substring const
5) 'inherit
))
3451 (defvar org-table-fedit-map
3452 (let ((map (make-sparse-keymap)))
3453 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3454 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3455 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3456 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3457 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3458 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3459 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3460 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3461 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3462 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3463 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3464 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3465 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3466 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3467 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3468 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3469 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3470 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3471 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3472 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3475 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3477 ["Finish and Install" org-table-fedit-finish t
]
3478 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3479 ["Abort" org-table-fedit-abort t
]
3481 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3482 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3484 "Shift Reference at Point"
3485 ["Up" org-table-fedit-ref-up t
]
3486 ["Down" org-table-fedit-ref-down t
]
3487 ["Left" org-table-fedit-ref-left t
]
3488 ["Right" org-table-fedit-ref-right t
]
3490 "Change Test Row for Column Formulas"
3491 ["Up" org-table-fedit-line-up t
]
3492 ["Down" org-table-fedit-line-down t
]
3494 ["Scroll Table Window" org-table-fedit-scroll t
]
3495 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3496 ["Show Table Grid" org-table-fedit-toggle-coordinates
3497 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3498 org-table-overlay-coordinates
)]
3500 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3501 :style toggle
:selected org-table-buffer-is-an
]))
3506 (defun org-table-edit-formulas ()
3507 "Edit the formulas of the current table in a separate buffer."
3509 (when (save-excursion (beginning-of-line)
3510 (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3511 (beginning-of-line 0))
3512 (unless (org-at-table-p) (user-error "Not at a table"))
3514 (let ((key (org-table-current-field-formula 'key
'noerror
))
3515 (eql (sort (org-table-get-stored-formulas 'noerror
)
3516 #'org-table-formula-less-p
))
3517 (pos (point-marker))
3519 (wc (current-window-configuration))
3520 (sel-win (selected-window))
3521 (titles '((column .
"# Column Formulas\n")
3522 (field .
"# Field and Range Formulas\n")
3523 (named .
"# Named Field Formulas\n"))))
3524 (org-switch-to-buffer-other-window "*Edit Formulas*")
3526 ;; Keep global-font-lock-mode from turning on font-lock-mode
3527 (let ((font-lock-global-modes '(not fundamental-mode
)))
3529 (setq-local font-lock-global-modes
(list 'not major-mode
))
3530 (setq-local org-pos pos
)
3531 (setq-local org-window-configuration wc
)
3532 (setq-local org-selected-window sel-win
)
3533 (use-local-map org-table-fedit-map
)
3534 (org-add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3535 (easy-menu-add org-table-fedit-menu
)
3536 (setq startline
(org-current-line))
3539 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3540 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3541 ((string-match "\\'[0-9]" (car entry
)) 'column
)
3543 (title (assq type titles
)))
3545 (unless (bobp) (insert "\n"))
3546 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3547 (setq titles
(remove title titles
)))
3548 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3549 (let ((s (concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3550 (car entry
) " = " (cdr entry
) "\n")))
3551 (remove-text-properties 0 (length s
) '(face nil
) s
)
3553 (when (eq org-table-use-standard-references t
)
3554 (org-table-fedit-toggle-ref-type))
3555 (org-goto-line startline
)
3557 (substitute-command-keys "\\<org-mode-map>\
3558 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3559 See menu for more commands."))))
3561 (defun org-table-fedit-post-command ()
3562 (when (not (memq this-command
'(lisp-complete-symbol)))
3563 (let ((win (selected-window)))
3565 (ignore-errors (org-table-show-reference))
3566 (select-window win
)))))
3568 (defun org-table-formula-to-user (s)
3569 "Convert a formula from internal to user representation."
3570 (if (eq org-table-use-standard-references t
)
3571 (org-table-convert-refs-to-an s
)
3574 (defun org-table-formula-from-user (s)
3575 "Convert a formula from user to internal representation."
3576 (if org-table-use-standard-references
3577 (org-table-convert-refs-to-rc s
)
3580 (defun org-table-convert-refs-to-rc (s)
3581 "Convert spreadsheet references from A7 to @7$28.
3582 Works for single references, but also for entire formulas and even the
3585 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3588 ;; format match, just advance
3589 (setq start
(match-end 0)))
3590 ((and (> (match-beginning 0) 0)
3591 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3592 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3593 ;; 3.e5 or something like this.
3594 (setq start
(match-end 0)))
3595 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3596 ;; (member (match-string 1 s)
3597 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3599 ;; function name, just advance
3600 (setq start
(match-end 0)))
3602 (setq start
(match-beginning 0)
3604 (if (equal (match-string 2 s
) "&")
3605 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3607 (string-to-number (match-string 2 s
))
3608 (org-letters-to-number (match-string 1 s
))))
3612 (defun org-table-convert-refs-to-an (s)
3613 "Convert spreadsheet references from to @7$28 to AB7.
3614 Works for single references, but also for entire formulas and even the
3616 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3617 (setq s
(replace-match
3619 (org-number-to-letters
3620 (string-to-number (match-string 2 s
)))
3621 (string-to-number (match-string 1 s
)))
3623 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3624 (setq s
(replace-match (concat "\\1"
3625 (org-number-to-letters
3626 (string-to-number (match-string 2 s
))) "&")
3630 (defun org-letters-to-number (s)
3631 "Convert a base 26 number represented by letters into an integer.
3632 For example: AB -> 28."
3635 (while (> (length s
) 0)
3636 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3640 (defun org-number-to-letters (n)
3641 "Convert an integer into a base 26 number represented by letters.
3642 For example: 28 -> AB."
3645 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3649 (defun org-table-time-string-to-seconds (s)
3650 "Convert a time string into numerical duration in seconds.
3651 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3652 If S is a string representing a number, keep this number."
3655 (let (hour minus min sec res
)
3657 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3658 (setq minus
(< 0 (length (match-string 1 s
)))
3659 hour
(string-to-number (match-string 2 s
))
3660 min
(string-to-number (match-string 3 s
))
3661 sec
(string-to-number (match-string 4 s
)))
3663 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3664 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3665 ((and (not (string-match org-ts-regexp-both s
))
3666 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3667 (setq minus
(< 0 (length (match-string 1 s
)))
3668 hour
(string-to-number (match-string 2 s
))
3669 min
(string-to-number (match-string 3 s
)))
3671 (setq res
(- (+ (* hour
3600) (* min
60))))
3672 (setq res
(+ (* hour
3600) (* min
60)))))
3673 (t (setq res
(string-to-number s
))))
3674 (number-to-string res
))))
3676 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3677 "Convert a number of seconds to a time string.
3678 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3679 minutes or seconds."
3680 (let* ((secs0 (abs secs
))
3682 (cond ((eq output-format
'days
)
3683 (format "%.3f" (/ (float secs0
) 86400)))
3684 ((eq output-format
'hours
)
3685 (format "%.2f" (/ (float secs0
) 3600)))
3686 ((eq output-format
'minutes
)
3687 (format "%.1f" (/ (float secs0
) 60)))
3688 ((eq output-format
'seconds
)
3689 (format "%d" secs0
))
3690 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3691 (if (< secs
0) (concat "-" res
) res
)))
3693 (defun org-table-fedit-convert-buffer (function)
3694 "Convert all references in this buffer, using FUNCTION."
3695 (let ((origin (copy-marker (line-beginning-position))))
3696 (goto-char (point-min))
3698 (insert (funcall function
(buffer-substring (point) (line-end-position))))
3699 (delete-region (point) (line-end-position))
3702 (set-marker origin nil
)))
3704 (defun org-table-fedit-toggle-ref-type ()
3705 "Convert all references in the buffer from B3 to @3$2 and back."
3707 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
3708 (org-table-fedit-convert-buffer
3709 (if org-table-buffer-is-an
3710 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3711 (message "Reference type switched to %s"
3712 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3714 (defun org-table-fedit-ref-up ()
3715 "Shift the reference at point one row/hline up."
3717 (org-table-fedit-shift-reference 'up
))
3718 (defun org-table-fedit-ref-down ()
3719 "Shift the reference at point one row/hline down."
3721 (org-table-fedit-shift-reference 'down
))
3722 (defun org-table-fedit-ref-left ()
3723 "Shift the reference at point one field to the left."
3725 (org-table-fedit-shift-reference 'left
))
3726 (defun org-table-fedit-ref-right ()
3727 "Shift the reference at point one field to the right."
3729 (org-table-fedit-shift-reference 'right
))
3731 (defun org-table-fedit-shift-reference (dir)
3733 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3734 (if (memq dir
'(left right
))
3735 (org-rematch-and-replace 1 (eq dir
'left
))
3736 (user-error "Cannot shift reference in this direction")))
3737 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3738 ;; A B3-like reference
3739 (if (memq dir
'(up down
))
3740 (org-rematch-and-replace 2 (eq dir
'up
))
3741 (org-rematch-and-replace 1 (eq dir
'left
))))
3743 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3744 ;; An internal reference
3745 (if (memq dir
'(up down
))
3746 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3747 (org-rematch-and-replace 5 (eq dir
'left
))))))
3749 (defun org-rematch-and-replace (n &optional decr hline
)
3750 "Re-match the group N, and replace it with the shifted reference."
3751 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3752 (goto-char (match-beginning n
))
3753 (and (looking-at (regexp-quote (match-string n
)))
3754 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3757 (defun org-table-shift-refpart (ref &optional decr hline
)
3758 "Shift a reference part REF.
3759 If DECR is set, decrease the references row/column, else increase.
3760 If HLINE is set, this may be a hline reference, it certainly is not
3761 a translation reference."
3763 (let* ((sign (string-match "^[-+]" ref
)) n
)
3765 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3767 ((and hline
(string-match "^I+" ref
))
3768 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3769 (setq n
(+ n
(if decr -
1 1)))
3770 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3772 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3774 (concat sign
(make-string n ?I
)))
3776 ((string-match "^[0-9]+" ref
)
3777 (setq n
(string-to-number (concat sign ref
)))
3778 (setq n
(+ n
(if decr -
1 1)))
3780 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3781 (number-to-string (max 1 n
))))
3783 ((string-match "^[a-zA-Z]+" ref
)
3784 (org-number-to-letters
3785 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3787 (t (user-error "Cannot shift reference"))))))
3789 (defun org-table-fedit-toggle-coordinates ()
3790 "Toggle the display of coordinates in the referenced table."
3792 (let ((pos (marker-position org-pos
)))
3793 (with-current-buffer (marker-buffer org-pos
)
3796 (org-table-toggle-coordinate-overlays)))))
3798 (defun org-table-fedit-finish (&optional arg
)
3799 "Parse the buffer for formula definitions and install them.
3800 With prefix ARG, apply the new formulas to the table."
3802 (org-table-remove-rectangle-highlight)
3803 (if org-table-use-standard-references
3805 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3806 (setq org-table-buffer-is-an nil
)))
3807 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3808 (goto-char (point-min))
3809 (while (re-search-forward
3810 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3812 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3813 form
(match-string 3))
3814 (setq form
(org-trim form
))
3815 (when (not (equal form
""))
3816 (while (string-match "[ \t]*\n[ \t]*" form
)
3817 (setq form
(replace-match " " t t form
)))
3818 (when (assoc var eql
)
3819 (user-error "Double formulas for %s" var
))
3820 (push (cons var form
) eql
)))
3822 (set-window-configuration org-window-configuration
)
3823 (select-window sel-win
)
3825 (unless (org-at-table-p)
3826 (user-error "Lost table position - cannot install formulas"))
3827 (org-table-store-formulas eql
)
3828 (move-marker pos nil
)
3829 (kill-buffer "*Edit Formulas*")
3831 (org-table-recalculate 'all
)
3832 (message "New formulas installed - press C-u C-c C-c to apply."))))
3834 (defun org-table-fedit-abort ()
3835 "Abort editing formulas, without installing the changes."
3837 (org-table-remove-rectangle-highlight)
3838 (let ((pos org-pos
) (sel-win org-selected-window
))
3839 (set-window-configuration org-window-configuration
)
3840 (select-window sel-win
)
3842 (move-marker pos nil
)
3843 (message "Formula editing aborted without installing changes")))
3845 (defun org-table-fedit-lisp-indent ()
3846 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3848 (let ((pos (point)) beg end ind
)
3849 (beginning-of-line 1)
3851 ((looking-at "[ \t]")
3853 (call-interactively 'lisp-indent-line
))
3854 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3855 ((not (fboundp 'pp-buffer
))
3856 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3857 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3858 (goto-char (- (match-end 0) 2))
3860 (setq ind
(make-string (current-column) ?\
))
3861 (condition-case nil
(forward-sexp 1)
3863 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3866 (narrow-to-region beg end
)
3867 (if (eq last-command this-command
)
3869 (goto-char (point-min))
3870 (setq this-command nil
)
3871 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3872 (replace-match " ")))
3874 (untabify (point-min) (point-max))
3875 (goto-char (1+ (point-min)))
3876 (while (re-search-forward "^." nil t
)
3877 (beginning-of-line 1)
3879 (goto-char (point-max))
3880 (org-delete-backward-char 1)))
3884 (defvar org-show-positions nil
)
3886 (defun org-table-show-reference (&optional local
)
3887 "Show the location/value of the $ expression at point."
3889 (org-table-remove-rectangle-highlight)
3890 (when local
(org-table-analyze))
3892 (let ((pos (if local
(point) org-pos
))
3893 (table-start (if local org-table-current-begin-pos
(org-table-begin)))
3895 (org-inhibit-highlight-removal t
)
3896 (win (selected-window))
3897 (org-show-positions nil
)
3898 var name e what match dest
)
3900 ((org-in-regexp "^@[0-9]+[ \t=]")
3901 (setq match
(concat (substring (match-string 0) 0 -
1)
3903 (substring (match-string 0) 0 -
1)
3906 ((or (org-in-regexp org-table-range-regexp2
)
3907 (org-in-regexp org-table-translate-regexp
)
3908 (org-in-regexp org-table-range-regexp
))
3911 (org-table-convert-refs-to-rc (match-string 0))))
3913 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3914 ((org-in-regexp "\\$[0-9]+") 'column
)
3916 (t (user-error "No reference at point")))
3917 match
(and what
(or match
(match-string 0))))
3918 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3919 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3920 'secondary-selection
))
3921 (org-add-hook 'before-change-functions
3922 #'org-table-remove-rectangle-highlight
)
3923 (when (eq what
'name
) (setq var
(substring match
1)))
3924 (when (eq what
'range
)
3925 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3926 (setq match
(org-table-formula-substitute-names match
)))
3930 (re-search-backward "^\\S-" nil t
)
3932 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
3933 \\([0-9]+\\|&\\)\\) *=")
3936 (org-table-convert-refs-to-rc (match-string 1))))
3937 (org-table-add-rectangle-overlay
3938 (match-beginning 1) (match-end 1) face2
))))
3939 (if (and (markerp pos
) (marker-buffer pos
))
3940 (if (get-buffer-window (marker-buffer pos
))
3941 (select-window (get-buffer-window (marker-buffer pos
)))
3942 (org-switch-to-buffer-other-window (get-buffer-window
3943 (marker-buffer pos
)))))
3945 (org-table-force-dataline)
3947 (setq name
(substring dest
1))
3949 ((org-string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3950 (org-table-goto-field dest
))
3951 ((org-string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
3953 (org-table-goto-field dest
))
3954 (t (org-table-goto-column (string-to-number name
))))
3955 (move-marker pos
(point))
3956 (org-table-highlight-rectangle nil nil face2
))
3958 ((equal dest match
))
3961 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
3962 ((setq e
(assoc var org-table-named-field-locations
))
3963 (org-table-goto-field var
)
3964 (org-table-highlight-rectangle)
3965 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3966 ((setq e
(assoc var org-table-column-names
))
3967 (org-table-goto-column (string-to-number (cdr e
)))
3968 (org-table-highlight-rectangle)
3969 (goto-char table-start
)
3970 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3973 (goto-char (match-beginning 1))
3974 (org-table-highlight-rectangle)
3975 (message "Named column (column %s)" (cdr e
)))
3976 (user-error "Column name not found")))
3979 (org-table-goto-column (string-to-number (substring match
1)))
3980 (org-table-highlight-rectangle)
3981 (message "Column %s" (substring match
1)))
3982 ((setq e
(assoc var org-table-local-parameters
))
3983 (goto-char table-start
)
3984 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3986 (goto-char (match-beginning 1))
3987 (org-table-highlight-rectangle)
3988 (message "Local parameter."))
3989 (user-error "Parameter not found")))
3990 ((not var
) (user-error "No reference at point"))
3991 ((setq e
(assoc var org-table-formula-constants-local
))
3992 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3994 ((setq e
(assoc var org-table-formula-constants
))
3995 (message "Constant: $%s=%s in `org-table-formula-constants'."
3997 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3998 (message "Constant: $%s=%s, from `constants.el'%s."
3999 var e
(format " (%s units)" constants-unit-system
)))
4000 (t (user-error "Undefined name $%s" var
)))
4002 (when (and org-show-positions
4003 (not (memq this-command
'(org-table-fedit-scroll
4004 org-table-fedit-scroll-down
))))
4005 (push pos org-show-positions
)
4006 (push table-start org-show-positions
)
4007 (let ((min (apply 'min org-show-positions
))
4008 (max (apply 'max org-show-positions
)))
4009 (set-window-start (selected-window) min
)
4011 (or (pos-visible-in-window-p max
)
4012 (set-window-start (selected-window) max
))))
4013 (select-window win
))))
4015 (defun org-table-force-dataline ()
4016 "Make sure the cursor is in a dataline in a table."
4017 (unless (save-excursion
4018 (beginning-of-line 1)
4019 (looking-at org-table-dataline-regexp
))
4020 (let* ((re org-table-dataline-regexp
)
4021 (p1 (save-excursion (re-search-forward re nil
'move
)))
4022 (p2 (save-excursion (re-search-backward re nil
'move
))))
4024 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4026 ((or p1 p2
) (goto-char (or p1 p2
)))
4027 (t (user-error "No table dataline around here"))))))
4029 (defun org-table-fedit-line-up ()
4030 "Move cursor one line up in the window showing the table."
4032 (org-table-fedit-move 'previous-line
))
4034 (defun org-table-fedit-line-down ()
4035 "Move cursor one line down in the window showing the table."
4037 (org-table-fedit-move 'next-line
))
4039 (defun org-table-fedit-move (command)
4040 "Move the cursor in the window showing the table.
4041 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4042 (let ((org-table-allow-automatic-line-recalculation nil
)
4043 (pos org-pos
) (win (selected-window)) p
)
4044 (select-window (get-buffer-window (marker-buffer org-pos
)))
4046 (call-interactively command
)
4047 (while (and (org-at-table-p)
4048 (org-at-table-hline-p))
4049 (call-interactively command
))
4050 (or (org-at-table-p) (goto-char p
))
4051 (move-marker pos
(point))
4052 (select-window win
)))
4054 (defun org-table-fedit-scroll (N)
4056 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4057 (scroll-other-window N
)))
4059 (defun org-table-fedit-scroll-down (N)
4061 (org-table-fedit-scroll (- N
)))
4063 (defvar org-table-rectangle-overlays nil
)
4065 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4066 "Add a new overlay."
4067 (let ((ov (make-overlay beg end
)))
4068 (overlay-put ov
'face
(or face
'secondary-selection
))
4069 (push ov org-table-rectangle-overlays
)))
4071 (defun org-table-highlight-rectangle (&optional beg end face
)
4072 "Highlight rectangular region in a table.
4073 When buffer positions BEG and END are provided, use them to
4074 delimit the region to highlight. Otherwise, refer to point. Use
4075 FACE, when non-nil, for the highlight."
4076 (let* ((beg (or beg
(point)))
4077 (end (or end
(point)))
4083 (cons (line-beginning-position) (org-table-current-column))))
4087 (cons (line-beginning-position) (org-table-current-column)))))
4088 (when (boundp 'org-show-positions
)
4089 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4090 (goto-char (car start-coordinates
))
4091 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
4092 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
4093 (last-row (car end-coordinates
)))
4094 (while (<= (point) last-row
)
4095 (when (looking-at org-table-dataline-regexp
)
4096 (org-table-goto-column column-start
)
4097 (skip-chars-backward "^|\n")
4099 (org-table-goto-column column-end
)
4100 (skip-chars-forward "^|\n")
4101 (org-table-add-rectangle-overlay p
(point) face
)))
4103 (goto-char (car start-coordinates
)))
4104 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
4106 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
4107 "Remove the rectangle overlays."
4108 (unless org-inhibit-highlight-removal
4109 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4110 (mapc 'delete-overlay org-table-rectangle-overlays
)
4111 (setq org-table-rectangle-overlays nil
)))
4113 (defvar-local org-table-coordinate-overlays nil
4114 "Collects the coordinate grid overlays, so that they can be removed.")
4116 (defun org-table-overlay-coordinates ()
4117 "Add overlays to the table at point, to show row/column coordinates."
4119 (mapc 'delete-overlay org-table-coordinate-overlays
)
4120 (setq org-table-coordinate-overlays nil
)
4122 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4123 (goto-char (org-table-begin))
4124 (while (org-at-table-p)
4125 (setq eol
(point-at-eol))
4126 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4127 (push ov org-table-coordinate-overlays
)
4128 (setq hline
(looking-at org-table-hline-regexp
))
4129 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4130 (format "%4d" (setq id
(1+ id
)))))
4131 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4134 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4135 (setq beg
(1+ (match-beginning 0))
4137 s1
(concat "$" (int-to-string ic
))
4138 s2
(org-number-to-letters ic
)
4139 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4140 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4141 (push ov org-table-coordinate-overlays
)
4142 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4143 (beginning-of-line 2)))))
4146 (defun org-table-toggle-coordinate-overlays ()
4147 "Toggle the display of Row/Column numbers in tables."
4149 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4150 (message "Tables Row/Column numbers display turned %s"
4151 (if org-table-overlay-coordinates
"on" "off"))
4152 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4154 (unless org-table-overlay-coordinates
4155 (mapc 'delete-overlay org-table-coordinate-overlays
)
4156 (setq org-table-coordinate-overlays nil
)))
4159 (defun org-table-toggle-formula-debugger ()
4160 "Toggle the formula debugger in tables."
4162 (setq org-table-formula-debug
(not org-table-formula-debug
))
4163 (message "Formula debugging has been turned %s"
4164 (if org-table-formula-debug
"on" "off")))
4166 ;;; The orgtbl minor mode
4168 ;; Define a minor mode which can be used in other modes in order to
4169 ;; integrate the org-mode table editor.
4171 ;; This is really a hack, because the org-mode table editor uses several
4172 ;; keys which normally belong to the major mode, for example the TAB and
4173 ;; RET keys. Here is how it works: The minor mode defines all the keys
4174 ;; necessary to operate the table editor, but wraps the commands into a
4175 ;; function which tests if the cursor is currently inside a table. If that
4176 ;; is the case, the table editor command is executed. However, when any of
4177 ;; those keys is used outside a table, the function uses `key-binding' to
4178 ;; look up if the key has an associated command in another currently active
4179 ;; keymap (minor modes, major mode, global), and executes that command.
4180 ;; There might be problems if any of the keys used by the table editor is
4181 ;; otherwise used as a prefix key.
4183 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4184 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4185 ;; addresses this by checking explicitly for both bindings.
4187 ;; The optimized version (see variable `orgtbl-optimized') takes over
4188 ;; all keys which are bound to `self-insert-command' in the *global map*.
4189 ;; Some modes bind other commands to simple characters, for example
4190 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4191 ;; active, this binding is ignored inside tables and replaced with a
4192 ;; modified self-insert.
4195 (defvar orgtbl-mode-map
(make-keymap)
4196 "Keymap for `orgtbl-mode'.")
4198 (defvar org-old-auto-fill-inhibit-regexp nil
4199 "Local variable used by `orgtbl-mode'.")
4201 (defconst orgtbl-line-start-regexp
4202 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4203 "Matches a line belonging to an orgtbl.")
4205 (defconst orgtbl-extra-font-lock-keywords
4206 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4207 0 (quote 'org-table
) 'prepend
))
4208 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4210 ;; Install it as a minor mode.
4211 (put 'orgtbl-mode
:included t
)
4212 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4215 (define-minor-mode orgtbl-mode
4216 "The `org-mode' table editor as a minor mode for use in other modes."
4217 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4218 (org-load-modules-maybe)
4220 ((derived-mode-p 'org-mode
)
4221 ;; Exit without error, in case some hook functions calls this
4222 ;; by accident in org-mode.
4223 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4225 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4226 ;; Make sure we are first in minor-mode-map-alist
4227 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4228 ;; FIXME: maybe it should use emulation-mode-map-alists?
4229 (and c
(setq minor-mode-map-alist
4230 (cons c
(delq c minor-mode-map-alist
)))))
4231 (setq-local org-table-may-need-update t
)
4232 (org-add-hook 'before-change-functions
'org-before-change-function
4234 (setq-local org-old-auto-fill-inhibit-regexp
4235 auto-fill-inhibit-regexp
)
4236 (setq-local auto-fill-inhibit-regexp
4237 (if auto-fill-inhibit-regexp
4238 (concat orgtbl-line-start-regexp
"\\|"
4239 auto-fill-inhibit-regexp
)
4240 orgtbl-line-start-regexp
))
4241 (add-to-invisibility-spec '(org-cwidth))
4242 (when (fboundp 'font-lock-add-keywords
)
4243 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4244 (org-restart-font-lock))
4245 (easy-menu-add orgtbl-mode-menu
))
4247 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4248 (org-table-cleanup-narrow-column-properties)
4249 (org-remove-from-invisibility-spec '(org-cwidth))
4250 (remove-hook 'before-change-functions
'org-before-change-function t
)
4251 (when (fboundp 'font-lock-remove-keywords
)
4252 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4253 (org-restart-font-lock))
4254 (easy-menu-remove orgtbl-mode-menu
)
4255 (force-mode-line-update 'all
))))
4257 (defun org-table-cleanup-narrow-column-properties ()
4258 "Remove all properties related to narrow-column invisibility."
4259 (let ((s (point-min)))
4260 (while (setq s
(text-property-any s
(point-max)
4261 'display org-narrow-column-arrow
))
4262 (remove-text-properties s
(1+ s
) '(display t
)))
4263 (setq s
(point-min))
4264 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4265 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4266 (setq s
(point-min))
4267 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4268 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4270 (defun orgtbl-make-binding (fun n
&rest keys
)
4271 "Create a function for binding in the table minor mode.
4272 FUN is the command to call inside a table. N is used to create a unique
4273 command name. KEYS are keys that should be checked in for a command
4274 to execute outside of tables."
4277 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4279 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4280 "Outside of tables, run the binding of `"
4281 (mapconcat #'key-description keys
"' or `")
4286 (list 'call-interactively
(list 'quote fun
))
4287 (list 'let
'(orgtbl-mode)
4288 (list 'call-interactively
4291 (list 'key-binding k
))
4293 '('orgtbl-error
))))))))
4295 (defun orgtbl-error ()
4296 "Error when there is no default binding for a table key."
4298 (user-error "This key has no function outside tables"))
4300 (defun orgtbl-setup ()
4301 "Setup orgtbl keymaps."
4304 '(([(meta shift left
)] org-table-delete-column
)
4305 ([(meta left
)] org-table-move-column-left
)
4306 ([(meta right
)] org-table-move-column-right
)
4307 ([(meta shift right
)] org-table-insert-column
)
4308 ([(meta shift up
)] org-table-kill-row
)
4309 ([(meta shift down
)] org-table-insert-row
)
4310 ([(meta up
)] org-table-move-row-up
)
4311 ([(meta down
)] org-table-move-row-down
)
4312 ("\C-c\C-w" org-table-cut-region
)
4313 ("\C-c\M-w" org-table-copy-region
)
4314 ("\C-c\C-y" org-table-paste-rectangle
)
4315 ("\C-c\C-w" org-table-wrap-region
)
4316 ("\C-c-" org-table-insert-hline
)
4317 ("\C-c}" org-table-toggle-coordinate-overlays
)
4318 ("\C-c{" org-table-toggle-formula-debugger
)
4319 ("\C-m" org-table-next-row
)
4320 ([(shift return
)] org-table-copy-down
)
4321 ("\C-c?" org-table-field-info
)
4322 ("\C-c " org-table-blank-field
)
4323 ("\C-c+" org-table-sum
)
4324 ("\C-c=" org-table-eval-formula
)
4325 ("\C-c'" org-table-edit-formulas
)
4326 ("\C-c`" org-table-edit-field
)
4327 ("\C-c*" org-table-recalculate
)
4328 ("\C-c^" org-table-sort-lines
)
4329 ("\M-a" org-table-beginning-of-field
)
4330 ("\M-e" org-table-end-of-field
)
4331 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4333 (while (setq elt
(pop bindings
))
4334 (setq nfunc
(1+ nfunc
))
4335 (setq key
(org-key (car elt
))
4337 cmd
(orgtbl-make-binding fun nfunc key
))
4338 (org-defkey orgtbl-mode-map key cmd
))
4340 ;; Special treatment needed for TAB and RET
4341 (org-defkey orgtbl-mode-map
[(return)]
4342 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4343 (org-defkey orgtbl-mode-map
"\C-m"
4344 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4346 (org-defkey orgtbl-mode-map
[(tab)]
4347 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4348 (org-defkey orgtbl-mode-map
"\C-i"
4349 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4351 (org-defkey orgtbl-mode-map
[(shift tab
)]
4352 (orgtbl-make-binding 'org-table-previous-field
104
4353 [(shift tab
)] [(tab)] "\C-i"))
4356 (unless (featurep 'xemacs
)
4357 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4358 (orgtbl-make-binding 'org-table-previous-field
107
4359 [S-iso-lefttab
] [backtab] [(shift tab)]
4362 (org-defkey orgtbl-mode-map [backtab]
4363 (orgtbl-make-binding 'org-table-previous-field
108
4364 [backtab] [S-iso-lefttab] [(shift tab)]
4367 (org-defkey orgtbl-mode-map "\M-\C-m"
4368 (orgtbl-make-binding 'org-table-wrap-region 105
4369 "\M-\C-m" [(meta return)]))
4370 (org-defkey orgtbl-mode-map [(meta return)]
4371 (orgtbl-make-binding 'org-table-wrap-region 106
4372 [(meta return)] "\M-\C-m"))
4374 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4375 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4377 (when orgtbl-optimized
4378 ;; If the user wants maximum table support, we need to hijack
4379 ;; some standard editing functions
4380 (org-remap orgtbl-mode-map
4381 'self-insert-command 'orgtbl-self-insert-command
4382 'delete-char 'org-delete-char
4383 'delete-backward-char 'org-delete-backward-char)
4384 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4385 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4387 ["Create or convert" org-table-create-or-convert-from-region
4388 :active (not (org-at-table-p)) :keys "C-c |" ]
4390 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4391 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4392 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4393 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4395 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4396 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4397 ["Copy Field from Above"
4398 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4401 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4402 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4403 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4404 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4406 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4407 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4408 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4409 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4410 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4412 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4414 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4415 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4416 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4417 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4420 ["Insert table template" orgtbl-insert-radio-table
4421 (assq major-mode orgtbl-radio-table-templates)]
4422 ["Comment/uncomment table" orgtbl-toggle-comment t])
4424 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4425 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4426 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4427 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4428 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4429 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4430 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4431 ["Sum Column/Rectangle" org-table-sum
4432 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4433 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4435 org-table-toggle-formula-debugger :active (org-at-table-p)
4437 :style toggle :selected org-table-formula-debug]
4438 ["Show Col/Row Numbers"
4439 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4441 :style toggle :selected org-table-overlay-coordinates]
4444 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4445 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4448 (defun orgtbl-ctrl-c-ctrl-c (arg)
4449 "If the cursor is inside a table, realign the table.
4450 If it is a table to be sent away to a receiver, do it.
4451 With prefix arg, also recompute table."
4453 (let ((case-fold-search t) (pos (point)) action)
4455 (beginning-of-line 1)
4457 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4458 ((looking-at "[ \t]*|") pos)
4459 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4463 (org-table-maybe-eval-formula)
4465 (call-interactively 'org-table-recalculate)
4466 (org-table-maybe-recalculate-line))
4467 (call-interactively 'org-table-align)
4468 (when (orgtbl-send-table 'maybe)
4469 (run-hooks 'orgtbl-after-send-table-hook)))
4470 ((eq action 'recalc)
4472 (beginning-of-line 1)
4473 (skip-chars-backward " \r\n\t")
4474 (if (org-at-table-p)
4475 (org-call-with-arg 'org-table-recalculate t))))
4476 (t (let (orgtbl-mode)
4477 (call-interactively (key-binding "\C-c\C-c")))))))
4479 (defun orgtbl-create-or-convert-from-region (_arg)
4480 "Create table or convert region to table, if no conflicting binding.
4481 This installs the table binding `C-c |', but only if there is no
4482 conflicting binding to this key outside orgtbl-mode."
4484 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4486 (call-interactively cmd)
4487 (call-interactively 'org-table-create-or-convert-from-region))))
4489 (defun orgtbl-tab (arg)
4490 "Justification and field motion for `orgtbl-mode'."
4492 (if arg (org-table-edit-field t)
4493 (org-table-justify-field-maybe)
4494 (org-table-next-field)))
4496 (defun orgtbl-ret ()
4497 "Justification and field motion for `orgtbl-mode'."
4501 (org-table-justify-field-maybe)
4502 (org-table-next-row)))
4504 (defun orgtbl-self-insert-command (N)
4505 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4506 If the cursor is in a table looking at whitespace, the whitespace is
4507 overwritten, and the table is not marked as requiring realignment."
4509 (if (and (org-at-table-p)
4511 (and org-table-auto-blank-field
4512 (member last-command
4513 '(orgtbl-hijacker-command-100
4514 orgtbl-hijacker-command-101
4515 orgtbl-hijacker-command-102
4516 orgtbl-hijacker-command-103
4517 orgtbl-hijacker-command-104
4518 orgtbl-hijacker-command-105
4520 (org-table-blank-field))
4523 (looking-at "[^|\n]* +|"))
4524 (let (org-table-may-need-update)
4525 (goto-char (1- (match-end 0)))
4526 (org-delete-backward-char 1)
4527 (goto-char (match-beginning 0))
4528 (self-insert-command N))
4529 (setq org-table-may-need-update t)
4532 (cmd (or (key-binding
4533 (or (and (listp function-key-map)
4534 (setq a (assoc last-input-event function-key-map))
4536 (vector last-input-event)))
4537 'self-insert-command)))
4538 (call-interactively cmd)
4539 (if (and org-self-insert-cluster-for-undo
4540 (eq cmd 'self-insert-command))
4541 (if (not (eq last-command 'orgtbl-self-insert-command))
4542 (setq org-self-insert-command-undo-counter 1)
4543 (if (>= org-self-insert-command-undo-counter 20)
4544 (setq org-self-insert-command-undo-counter 1)
4545 (and (> org-self-insert-command-undo-counter 0)
4547 (not (cadr buffer-undo-list)) ; remove nil entry
4548 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4549 (setq org-self-insert-command-undo-counter
4550 (1+ org-self-insert-command-undo-counter))))))))
4553 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4554 "Regular expression matching exponentials as produced by calc.")
4556 (defun orgtbl-gather-send-defs ()
4557 "Gather a plist of :name, :transform, :params for each destination before
4560 (goto-char (org-table-begin))
4562 (beginning-of-line 0)
4563 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4564 (let ((name (org-no-properties (match-string 1)))
4565 (transform (intern (match-string 2)))
4566 (params (if (match-end 3)
4567 (read (concat "(" (match-string 3) ")")))))
4568 (push (list :name name :transform transform :params params)
4570 (beginning-of-line 0)))
4573 (defun orgtbl-send-replace-tbl (name txt)
4574 "Find and replace table NAME with TXT."
4576 (goto-char (point-min))
4577 (unless (re-search-forward
4578 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4579 (user-error "Don't know where to insert translated table"))
4580 (let ((beg (line-beginning-position 2)))
4581 (unless (re-search-forward
4582 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4583 (user-error "Cannot find end of insertion region"))
4585 (delete-region beg (point)))
4589 (defun org-table-to-lisp (&optional txt)
4590 "Convert the table at point to a Lisp structure.
4591 The structure will be a list. Each item is either the symbol `hline'
4592 for a horizontal separator line, or a list of field values as strings.
4593 The table is taken from the parameter TXT, or from the buffer at point."
4594 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4596 (buffer-substring-no-properties (org-table-begin)
4599 (if (string-match org-table-hline-regexp x) 'hline
4600 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4601 (org-split-string txt "[ \t]*\n[ \t]*"))))
4603 (defun orgtbl-send-table (&optional maybe)
4604 "Send a transformed version of table at point to the receiver position.
4605 With argument MAYBE, fail quietly if no transformation is defined
4609 (unless (org-at-table-p) (user-error "Not at a table"))
4610 ;; when non-interactive, we assume align has just happened.
4611 (when (org-called-interactively-p 'any) (org-table-align))
4612 (let ((dests (orgtbl-gather-send-defs))
4613 (table (org-table-to-lisp
4614 (buffer-substring-no-properties (org-table-begin)
4618 (if maybe (throw 'exit nil)
4619 (user-error "Don't know how to transform this table")))
4620 (dolist (dest dests)
4621 (let ((name (plist-get dest :name))
4622 (transform (plist-get dest :transform))
4623 (params (plist-get dest :params)))
4624 (unless (fboundp transform)
4625 (user-error "No such transformation function %s" transform))
4626 (orgtbl-send-replace-tbl name (funcall transform table params)))
4628 (message "Table converted and installed at %d receiver location%s"
4629 ntbl (if (> ntbl 1) "s" ""))
4630 (and (> ntbl 0) ntbl))))
4632 (defun org-remove-by-index (list indices &optional i0)
4633 "Remove the elements in LIST with indices in INDICES.
4634 First element has index 0, or I0 if given."
4637 (if (integerp indices) (setq indices (list indices)))
4638 (setq i0 (1- (or i0 0)))
4639 (delq :rm (mapcar (lambda (x)
4641 (if (memq i0 indices) :rm x))
4644 (defun orgtbl-toggle-comment ()
4645 "Comment or uncomment the orgtbl at point."
4647 (let* ((case-fold-search t)
4648 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4649 (re2 (concat "^" orgtbl-line-start-regexp))
4650 (commented (save-excursion (beginning-of-line 1)
4651 (cond ((looking-at re1) t)
4652 ((looking-at re2) nil)
4653 (t (user-error "Not at an org table")))))
4654 (re (if commented re1 re2))
4657 (beginning-of-line 1)
4658 (while (looking-at re) (beginning-of-line 0))
4659 (beginning-of-line 2)
4661 (while (looking-at re) (beginning-of-line 2))
4663 (comment-region beg end (if commented '(4) nil))))
4665 (defun orgtbl-insert-radio-table ()
4666 "Insert a radio table template appropriate for this major mode."
4668 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4671 (unless e (user-error "No radio table setup defined for %s" major-mode))
4672 (setq name (read-string "Table name: "))
4673 (while (string-match "%n" txt)
4674 (setq txt (replace-match name t t txt)))
4675 (or (bolp) (insert "\n"))
4681 (defun orgtbl-to-generic (table params)
4682 "Convert the orgtbl-mode TABLE to some other format.
4684 This generic routine can be used for many standard cases.
4686 TABLE is a list, each entry either the symbol `hline' for
4687 a horizontal separator line, or a list of fields for that
4688 line. PARAMS is a property list of parameters that can
4689 influence the conversion.
4691 Valid parameters are:
4695 Export back-end used as a basis to transcode elements of the
4696 table, when no specific parameter applies to it. It is also
4697 used to translate cells contents. You can prevent this by
4698 setting :raw property to a non-nil value.
4702 When non-nil, only convert rows, not the table itself. This is
4703 equivalent to setting to the empty string both :tstart
4704 and :tend, which see.
4708 When set to an integer N, skip the first N lines of the table.
4709 Horizontal separation lines do count for this parameter!
4713 List of columns that should be skipped. If the table has
4714 a column with calculation marks, that column is automatically
4715 discarded beforehand.
4719 String to be inserted on horizontal separation lines. May be
4720 nil to ignore these lines altogether.
4724 Separator between two fields, as a string.
4726 Each in the following group may be either a string or a function
4727 of no arguments returning a string:
4731 Strings to start and end the table. Ignored when :splice is t.
4735 Strings to start and end a new table line.
4739 Strings to start and end the last table line. Default,
4740 respectively, to :lstart and :lend.
4742 Each in the following group may be a string or a function of one
4743 argument (either the cells in the current row, as a list of
4744 strings, or the current cell) returning a string:
4748 Format string for an entire row, with enough %s to capture all
4749 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4753 Format for the entire last line, defaults to :lfmt.
4757 A format to be used to wrap the field, should contain %s for
4758 the original field value. For example, to wrap everything in
4759 dollars, you could use :fmt \"$%s$\". This may also be
4760 a property list with column numbers and format strings, or
4763 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4765 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4767 Same as above, specific for the header lines in the table.
4768 All lines before the first hline are treated as header. If
4769 any of these is not present, the data line value is used.
4771 This may be either a string or a function of two arguments:
4775 Use this format to print numbers with exponential. The format
4776 should have %s twice for inserting mantissa and exponent, for
4777 example \"%s\\\\times10^{%s}\". This may also be a property
4778 list with column numbers and format strings or functions.
4779 :fmt will still be applied after :efmt."
4780 ;; Make sure `org-export-create-backend' is available.
4782 (let* ((backend (plist-get params :backend))
4784 ;; Build a custom back-end according to PARAMS. Before
4785 ;; defining a translator, check if there is anything to do.
4786 ;; When there isn't, let BACKEND handle the element.
4787 (org-export-create-backend
4788 :parent (or backend 'org)
4790 `((table . ,(org-table--to-generic-table params))
4791 (table-row . ,(org-table--to-generic-row params))
4792 (table-cell . ,(org-table--to-generic-cell params))
4793 ;; Macros are not going to be expanded. However, no
4794 ;; regular back-end has a transcoder for them. We
4795 ;; provide one so they are not ignored, but displayed
4797 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
4799 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
4800 ;; Initialize communication channel in INFO.
4802 (let ((org-inhibit-startup t)) (org-mode))
4803 (let ((standard-output (current-buffer)))
4805 (cond ((eq e 'hline) (princ "|--\n"))
4807 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4810 (org-element-map (org-element-parse-buffer) 'table
4812 (setq info (org-export-get-environment backend nil params)))
4813 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4814 (user-error "Unknown :backend value"))
4815 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
4816 ;; Handle :skip parameter.
4817 (let ((skip (plist-get info :skip)))
4819 (unless (wholenump skip) (user-error "Wrong :skip value"))
4821 (org-element-map data 'table-row
4824 (org-element-extract-element row)
4828 ;; Handle :skipcols parameter.
4829 (let ((skipcols (plist-get info :skipcols)))
4831 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4832 (org-element-map data 'table
4834 (let ((specialp (org-export-table-has-special-column-p table)))
4835 (dolist (row (org-element-contents table))
4836 (when (eq (org-element-property :type row) 'standard)
4838 (dolist (cell (nthcdr (if specialp 1 0)
4839 (org-element-contents row)))
4840 (when (memq c skipcols)
4841 (org-element-extract-element cell))
4843 ;; Since we are going to export using a low-level mechanism,
4844 ;; ignore special column and special rows manually.
4845 (let ((special? (org-export-table-has-special-column-p data))
4847 (org-element-map data (if special? '(table-cell table-row) 'table-row)
4849 (when (if (eq (org-element-type datum) 'table-row)
4850 (org-export-table-row-is-special-p datum nil)
4851 (org-export-first-sibling-p datum nil))
4852 (push datum ignore))))
4853 (setq info (plist-put info :ignore-list ignore)))
4854 ;; We use a low-level mechanism to export DATA so as to skip all
4855 ;; usual pre-processing and post-processing, i.e., hooks, filters,
4856 ;; Babel code evaluation, include keywords and macro expansion,
4858 (let ((output (org-export-data-with-backend data custom-backend info)))
4859 ;; Remove final newline.
4860 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
4862 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4863 (cond ((null value) nil)
4864 ((functionp value) `(funcall ',value ,@args))
4866 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4867 (args `(format ,value ,@args))
4869 ((and with-cons (consp value))
4870 `(let ((val (cadr (memq column ',value))))
4871 (cond ((null val) contents)
4872 ((stringp val) (format val ,@args))
4873 ((functionp val) (funcall val ,@args))
4874 (t (user-error "Wrong %s value" ,name)))))
4875 (t (user-error "Wrong %s value" name))))
4877 (defun org-table--to-generic-table (params)
4878 "Return custom table transcoder according to PARAMS.
4879 PARAMS is a plist. See `orgtbl-to-generic' for more
4881 (let ((backend (plist-get params :backend))
4882 (splice (plist-get params :splice))
4883 (tstart (plist-get params :tstart))
4884 (tend (plist-get params :tend)))
4885 `(lambda (table contents info)
4887 ,(and tstart (not splice)
4888 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4889 ,(if (or (not backend) tstart tend splice) 'contents
4890 `(org-export-with-backend ',backend table contents info))
4891 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4893 (defun org-table--to-generic-row (params)
4894 "Return custom table row transcoder according to PARAMS.
4895 PARAMS is a plist. See `orgtbl-to-generic' for more
4897 (let* ((backend (plist-get params :backend))
4898 (lstart (plist-get params :lstart))
4899 (llstart (plist-get params :llstart))
4900 (hlstart (plist-get params :hlstart))
4901 (hllstart (plist-get params :hllstart))
4902 (lend (plist-get params :lend))
4903 (llend (plist-get params :llend))
4904 (hlend (plist-get params :hlend))
4905 (hllend (plist-get params :hllend))
4906 (lfmt (plist-get params :lfmt))
4907 (llfmt (plist-get params :llfmt))
4908 (hlfmt (plist-get params :hlfmt))
4909 (hllfmt (plist-get params :hllfmt)))
4910 `(lambda (row contents info)
4911 (if (eq (org-element-property :type row) 'rule)
4913 ((plist-member params :hline)
4914 (org-table--generic-apply (plist-get params :hline) ":hline"))
4915 (backend `(org-export-with-backend ',backend row nil info)))
4916 (let ((headerp (org-export-table-row-in-header-p row info))
4917 (lastp (not (org-export-get-next-element row info)))
4918 (last-header-p (org-export-table-row-ends-header-p row info)))
4920 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4921 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4922 ;; `:lstart', `:lend' and their relatives.
4924 '(org-element-map row 'table-cell
4926 ;; Export all cells, without separators.
4928 ;; Use `org-export-data-with-backend'
4929 ;; instead of `org-export-data' to eschew
4930 ;; cached values, which
4931 ;; ignore :orgtbl-ignore-sep parameter.
4932 (org-export-data-with-backend
4934 (plist-get info :back-end)
4935 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4939 `(last-header-p ,(org-table--generic-apply
4940 hllfmt ":hllfmt" nil cells)))
4942 `(headerp ,(org-table--generic-apply
4943 hlfmt ":hlfmt" nil cells)))
4945 `(lastp ,(org-table--generic-apply
4946 llfmt ":llfmt" nil cells)))
4948 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4952 (or hllstart hllend)
4955 ,(org-table--generic-apply hllstart ":hllstart")
4957 ,(org-table--generic-apply hllend ":hllend"))))
4962 ,(org-table--generic-apply hlstart ":hlstart")
4964 ,(org-table--generic-apply hlend ":hlend"))))
4969 ,(org-table--generic-apply llstart ":llstart")
4971 ,(org-table--generic-apply llend ":llend"))))
4976 ,(org-table--generic-apply lstart ":lstart")
4978 ,(org-table--generic-apply lend ":lend")))
4980 `(org-export-with-backend
4981 ',backend row contents info))
4982 (t 'contents)))))))))))))))
4984 (defun org-table--to-generic-cell (params)
4985 "Return custom table cell transcoder according to PARAMS.
4986 PARAMS is a plist. See `orgtbl-to-generic' for more
4988 (let* ((backend (plist-get params :backend))
4989 (efmt (plist-get params :efmt))
4990 (fmt (plist-get params :fmt))
4991 (hfmt (plist-get params :hfmt))
4992 (sep (plist-get params :sep))
4993 (hsep (plist-get params :hsep)))
4994 `(lambda (cell contents info)
4995 (let ((headerp (org-export-table-row-in-header-p
4996 (org-export-get-parent-element cell) info))
4997 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4998 ;; Make sure that contents are exported as Org data when :raw
4999 ;; parameter is non-nil.
5000 ,(when (and backend (plist-get params :raw))
5002 ;; Since we don't know what are the pseudo object
5003 ;; types defined in backend, we cannot pass them to
5004 ;; `org-element-interpret-data'. As a consequence,
5005 ;; they will be treated as pseudo elements, and
5006 ;; will have newlines appended instead of spaces.
5007 ;; Therefore, we must make sure :post-blank value
5008 ;; is really turned into spaces.
5009 (replace-regexp-in-string
5012 (org-element-interpret-data
5013 (org-element-contents cell))))))
5015 ;; Check if we can apply `:efmt' on CONTENTS.
5017 `(when (string-match orgtbl-exp-regexp contents)
5018 (let ((mantissa (match-string 1 contents))
5019 (exponent (match-string 2 contents)))
5020 (setq contents ,(org-table--generic-apply
5021 efmt ":efmt" t 'mantissa 'exponent)))))
5022 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5024 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5025 hfmt ":hfmt" t 'contents))))
5026 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5027 fmt ":fmt" t 'contents))))))
5028 ;; If a separator is provided, use it instead of BACKEND's.
5029 ;; Separators are ignored when LFMT (or equivalent) is
5033 `(if (or ,(and (not sep) '(not headerp))
5034 (plist-get info :orgtbl-ignore-sep)
5035 (not (org-export-get-next-element cell info)))
5036 ,(if (not backend) 'contents
5037 `(org-export-with-backend ',backend cell contents info))
5039 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5041 (backend `(org-export-with-backend ',backend cell contents info))
5045 (defun orgtbl-to-tsv (table params)
5046 "Convert the orgtbl-mode table to TAB separated material."
5047 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5050 (defun orgtbl-to-csv (table params)
5051 "Convert the orgtbl-mode table to CSV material.
5052 This does take care of the proper quoting of fields with comma or quotes."
5053 (orgtbl-to-generic table
5054 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5058 (defun orgtbl-to-latex (table params)
5059 "Convert the orgtbl-mode TABLE to LaTeX.
5061 TABLE is a list, each entry either the symbol `hline' for
5062 a horizontal separator line, or a list of fields for that line.
5063 PARAMS is a property list of parameters that can influence the
5064 conversion. All parameters from `orgtbl-to-generic' are
5065 supported. It is also possible to use the following ones:
5069 When non-nil, use formal \"booktabs\" style.
5073 Specify environment to use, as a string. If you use
5074 \"longtable\", you may also want to specify :language property,
5075 as a string, to get proper continuation strings."
5080 ;; Provide sane default values.
5081 (list :backend 'latex
5082 :latex-default-table-mode 'table
5083 :latex-tables-centered nil
5084 :latex-tables-booktabs (plist-get params :booktabs)
5085 :latex-table-scientific-notation nil
5086 :latex-default-table-environment
5087 (or (plist-get params :environment) "tabular"))
5091 (defun orgtbl-to-html (table params)
5092 "Convert the orgtbl-mode TABLE to HTML.
5094 TABLE is a list, each entry either the symbol `hline' for
5095 a horizontal separator line, or a list of fields for that line.
5096 PARAMS is a property list of parameters that can influence the
5097 conversion. All parameters from `orgtbl-to-generic' are
5098 supported. It is also possible to use the following one:
5102 Attributes and values, as a plist, which will be used in
5108 ;; Provide sane default values.
5109 (list :backend 'html
5110 :html-table-data-tags '("<td%s>" . "</td>")
5111 :html-table-use-header-tags-for-first-column nil
5112 :html-table-align-individual-fields t
5113 :html-table-row-tags '("<tr>" . "</tr>")
5114 :html-table-attributes
5115 (if (plist-member params :attributes)
5116 (plist-get params :attributes)
5117 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5122 (defun orgtbl-to-texinfo (table params)
5123 "Convert the orgtbl-mode TABLE to Texinfo.
5125 TABLE is a list, each entry either the symbol `hline' for
5126 a horizontal separator line, or a list of fields for that line.
5127 PARAMS is a property list of parameters that can influence the
5128 conversion. All parameters from `orgtbl-to-generic' are
5129 supported. It is also possible to use the following one:
5133 Column widths, as a string. When providing column fractions,
5134 \"@columnfractions\" command can be omitted."
5135 (require 'ox-texinfo)
5140 (list :backend 'texinfo
5141 :texinfo-tables-verbatim nil
5142 :texinfo-table-scientific-notation nil)
5144 (columns (let ((w (plist-get params :columns)))
5146 ((org-string-match-p "{\\|@columnfractions " w) w)
5147 (t (concat "@columnfractions " w))))))
5148 (if (not columns) output
5149 (replace-regexp-in-string
5150 "@multitable \\(.*\\)" columns output t nil 1))))
5153 (defun orgtbl-to-orgtbl (table params)
5154 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5156 TABLE is a list, each entry either the symbol `hline' for
5157 a horizontal separator line, or a list of fields for that line.
5158 PARAMS is a property list of parameters that can influence the
5159 conversion. All parameters from `orgtbl-to-generic' are
5162 Useful when slicing one table into many. The :hline, :sep,
5163 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5164 be set to provide ORGTBL directives for the generated table."
5166 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5168 (defun orgtbl-to-table.el (table params)
5169 "Convert the orgtbl-mode TABLE into a table.el table.
5170 TABLE is a list, each entry either the symbol `hline' for
5171 a horizontal separator line, or a list of fields for that line.
5172 PARAMS is a property list of parameters that can influence the
5173 conversion. All parameters from `orgtbl-to-generic' are
5176 (insert (orgtbl-to-orgtbl table params))
5178 (replace-regexp-in-string
5180 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5182 (defun orgtbl-to-unicode (table params)
5183 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5185 TABLE is a list, each entry either the symbol `hline' for
5186 a horizontal separator line, or a list of fields for that line.
5187 PARAMS is a property list of parameters that can influence the
5188 conversion. All parameters from `orgtbl-to-generic' are
5189 supported. It is also possible to use the following ones:
5193 When non-nil, use \"ascii-art-to-unicode\" package to translate
5194 the table. You can download it here:
5195 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5199 When non-nil, narrow columns width than provided width cookie,
5200 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5205 (list :backend 'ascii
5206 :ascii-charset 'utf-8
5207 :ascii-table-widen-columns (not (plist-get params :narrow))
5208 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5211 ;; Put the cursor in a column containing numerical values
5212 ;; of an Org-Mode table,
5214 ;; A new column is added with a bar plot.
5215 ;; When the table is refreshed (C-u C-c *),
5216 ;; the plot is updated to reflect the new values.
5218 (defun orgtbl-ascii-draw (value min max &optional width characters)
5219 "Draw an ascii bar in a table.
5220 VALUE is a the value to plot, the width of the bar to draw. A
5221 value equal to MIN will be displayed as empty (zero width bar).
5222 A value equal to MAX will draw a bar filling all the WIDTH.
5223 WIDTH is the expected width in characters of the column.
5224 CHARACTERS is a string that will compose the bar, with shades of
5225 grey from pure white to pure black. It defaults to a 10
5226 characters string of regular ascii characters."
5227 (let* ((characters (or characters " .:;c!lhVHW"))
5228 (width (or width 12))
5229 (value (if (numberp value) value (string-to-number value)))
5230 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5232 ((< value 0) "too small")
5233 ((> value width) "too large")
5235 (let ((len (1- (length characters))))
5237 (make-string (floor value) (elt characters len))
5238 (string (elt characters
5239 (floor (* (- value (floor value)) len))))))))))
5242 (defun orgtbl-ascii-plot (&optional ask)
5243 "Draw an ascii bar plot in a column.
5244 With cursor in a column containing numerical values, this
5245 function will draw a plot in a new column.
5246 ASK, if given, is a numeric prefix to override the default 12
5247 characters width of the plot. ASK may also be the
5248 \\[universal-argument] prefix, which will prompt for the width."
5250 (let ((col (org-table-current-column))
5251 (min 1e999) ; 1e999 will be converted to infinity
5252 (max -1e999) ; which is the desired result
5253 (table (org-table-to-lisp))
5256 (read-number "Length of column " 12))
5259 ;; Skip any hline a the top of table.
5260 (while (eq (car table) 'hline) (setq table (cdr table)))
5261 ;; Skip table header if any.
5262 (dolist (x (or (cdr (memq 'hline table)) table))
5264 (setq x (nth (1- col) x))
5266 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5268 (setq x (string-to-number x))
5269 (when (> min x) (setq min x))
5270 (when (< max x) (setq max x)))))
5271 (org-table-insert-column)
5272 (org-table-move-column-right)
5273 (org-table-store-formulas
5276 (number-to-string (1+ col))
5277 (format "'(%s $%s %s %s %s)"
5278 "orgtbl-ascii-draw" col min max length))
5279 (org-table-get-stored-formulas)))
5280 (org-table-recalculate t)))
5282 ;; Example of extension: unicode characters
5283 ;; Here are two examples of different styles.
5285 ;; Unicode block characters are used to give a smooth effect.
5286 ;; See http://en.wikipedia.org/wiki/Block_Elements
5287 ;; Use one of those drawing functions
5288 ;; - orgtbl-ascii-draw (the default ascii)
5289 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5290 ;; - orgtbl-uc-draw-cont (smooth unicode)
5292 ;; This is best viewed with the "DejaVu Sans Mono" font
5293 ;; (use M-x set-default-font).
5295 (defun orgtbl-uc-draw-grid (value min max &optional width)
5296 "Draw a bar in a table using block unicode characters.
5297 It is a variant of orgtbl-ascii-draw with Unicode block
5298 characters, for a smooth display. Bars appear as grids (to the
5299 extent the font allows)."
5300 ;; http://en.wikipedia.org/wiki/Block_Elements
5301 ;; best viewed with the "DejaVu Sans Mono" font.
5302 (orgtbl-ascii-draw value min max width
5303 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5305 (defun orgtbl-uc-draw-cont (value min max &optional width)
5306 "Draw a bar in a table using block unicode characters.
5307 It is a variant of orgtbl-ascii-draw with Unicode block
5308 characters, for a smooth display. Bars are solid (to the extent
5310 (orgtbl-ascii-draw value min max width
5311 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5313 (defun org-table-get-remote-range (name-or-id form)
5314 "Get a field value or a list of values in a range from table at ID.
5316 NAME-OR-ID may be the name of a table in the current file as set
5317 by a \"#+NAME:\" directive. The first table following this line
5318 will then be used. Alternatively, it may be an ID referring to
5319 any entry, also in a different file. In this case, the first
5320 table in that entry will be referenced.
5321 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5322 \"@I$2..@II$2\". All the references must be absolute, not relative.
5324 The return value is either a single string for a single field, or a
5325 list of the fields in the rectangle."
5327 (let ((case-fold-search t) (id-loc nil)
5328 ;; Protect a bunch of variables from being overwritten by
5329 ;; the context of the remote table.
5330 org-table-column-names org-table-column-name-regexp
5331 org-table-local-parameters org-table-named-field-locations
5332 org-table-current-line-types
5333 org-table-current-begin-pos org-table-dlines
5334 org-table-current-ncol
5335 org-table-hlines org-table-last-alignment
5336 org-table-last-column-widths org-table-last-alignment
5337 org-table-last-column-widths
5339 (setq form (org-table-convert-refs-to-rc form))
5340 (org-with-wide-buffer
5341 (goto-char (point-min))
5342 (if (re-search-forward
5343 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5344 (regexp-quote name-or-id) "[ \t]*$")
5346 (setq buffer (current-buffer) loc (match-beginning 0))
5347 (setq id-loc (org-id-find name-or-id 'marker))
5348 (unless (and id-loc (markerp id-loc))
5349 (user-error "Can't find remote table \"%s\"" name-or-id))
5350 (setq buffer (marker-buffer id-loc)
5351 loc (marker-position id-loc))
5352 (move-marker id-loc nil))
5353 (with-current-buffer buffer
5354 (org-with-wide-buffer
5357 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5358 (not (match-beginning 1)))
5359 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5361 (setq form (org-table-formula-substitute-names
5362 (org-table-formula-handle-first/last-rc form)))
5363 (if (and (string-match org-table-range-regexp form)
5364 (> (length (match-string 0 form)) 1))
5365 (org-table-get-range
5366 (match-string 0 form) org-table-current-begin-pos 1)
5369 (defun org-table-remote-reference-indirection (form)
5370 "Return formula with table remote references substituted by indirection.
5371 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5372 This indirection works only with the format @ROW$COLUMN. The
5373 format \"B3\" is not supported because it can not be
5374 distinguished from a plain table name or ID."
5376 (while (string-match (concat
5377 ;; Same as in `org-table-eval-formula'.
5378 "\\<remote([ \t]*\\("
5379 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5381 ;; Same as in `org-table-eval-formula'.
5382 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5385 ;; The position of the character as far as possible to the right
5386 ;; that will not be replaced and particularly not be shifted by
5388 (setq start (match-beginning 1))
5389 ;; Substitute the remote reference with the value found in the
5394 (org-table-get-range (org-table-formula-handle-first/last-rc
5395 (match-string 1 form))))
5399 (defmacro org-define-lookup-function (mode)
5400 (let ((mode-str (symbol-name mode))
5401 (first-p (equal mode 'first))
5402 (all-p (equal mode 'all)))
5403 (let ((plural-str (if all-p "s" "")))
5404 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5405 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5406 If R-LIST is nil, return matching element%s of S-LIST.
5407 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5408 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5409 This function is generated by a call to the macro `org-define-lookup-function'."
5410 mode-str plural-str plural-str plural-str)
5411 (let ,(let ((lvars '((p (or predicate 'equal))
5413 (rl (or r-list s-list))
5415 (if first-p (cons '(match-p nil) lvars) lvars))
5416 (while ,(if first-p '(and (not match-p) sl) 'sl)
5417 (when (funcall p val (car sl))
5418 ,(when first-p '(setq match-p t))
5419 (let ((rval (car rl)))
5420 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
5421 (setq sl (cdr sl) rl (cdr rl)))
5424 (org-define-lookup-function first)
5425 (org-define-lookup-function last)
5426 (org-define-lookup-function all)
5428 (provide 'org-table)
5431 ;; generated-autoload-file: "org-loaddefs.el"
5434 ;;; org-table.el ends here