1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2014 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.
41 (declare-function org-export-string-as
"ox"
42 (string backend
&optional body-only ext-plist
))
43 (declare-function org-export-create-backend
"ox")
44 (declare-function org-export-get-backend
"ox" (name))
46 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
48 (defvar orgtbl-mode
) ; defined below
49 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
50 (defvar constants-unit-system
)
51 (defvar org-table-follow-field-mode
)
53 (defvar orgtbl-after-send-table-hook nil
54 "Hook for functions attaching to `C-c C-c', if the table is sent.
55 This can be used to add additional functionality after the table is sent
56 to the receiver position, otherwise, if table is not sent, the functions
59 (defvar org-table-TBLFM-begin-regexp
"|\n[ \t]*#\\+TBLFM: ")
61 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
62 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
63 In the optimized version, the table editor takes over all simple keys that
64 normally just insert a character. In tables, the characters are inserted
65 in a way to minimize disturbing the table structure (i.e. in overwrite mode
66 for empty fields). Outside tables, the correct binding of the keys is
69 The default for this option is t if the optimized version is also used in
70 Org-mode. See the variable `org-enable-table-editor' for details. Changing
71 this variable requires a restart of Emacs to become effective."
75 (defcustom orgtbl-radio-table-templates
76 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
77 % END RECEIVE ORGTBL %n
79 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
82 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
83 @c END RECEIVE ORGTBL %n
85 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
88 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
89 <!-- END RECEIVE ORGTBL %n -->
91 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
94 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
95 #+ END RECEIVE ORGTBL %n
97 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
100 "Templates for radio tables in different major modes.
101 Each template must define lines that will be treated as a comment and that
102 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
103 lines where \"%n\" will be replaced with the name of the table during
104 insertion of the template. The transformed table will later be inserted
107 The template should also contain a minimal table in a multiline comment.
108 If multiline comments are not possible in the buffer language,
109 you can pack it into a string that will not be used when the code
110 is compiled or executed. Above the table will you need a line with
111 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
112 convert the table into a data structure useful in the
113 language of the buffer. Check the manual for the section on
114 \"Translator functions\", and more generally check out
115 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
117 All occurrences of %n in a template will be replaced with the name of the
118 table, obtained by prompting the user."
121 (list (symbol :tag
"Major mode")
122 (string :tag
"Format"))))
124 (defgroup org-table-settings nil
125 "Settings for tables in Org-mode."
126 :tag
"Org Table Settings"
129 (defcustom org-table-default-size
"5x2"
130 "The default size for newly created tables, Columns x Rows."
131 :group
'org-table-settings
134 (defcustom org-table-number-regexp
135 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
136 "Regular expression for recognizing numbers in table columns.
137 If a table column contains mostly numbers, it will be aligned to the
138 right. If not, it will be aligned to the left.
140 The default value of this option is a regular expression which allows
141 anything which looks remotely like a number as used in scientific
142 context. For example, all of the following will be considered a
144 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
146 Other options offered by the customize interface are more restrictive."
147 :group
'org-table-settings
149 (const :tag
"Positive Integers"
151 (const :tag
"Integers"
153 (const :tag
"Floating Point Numbers"
154 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
155 (const :tag
"Floating Point Number or Integer"
156 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
157 (const :tag
"Exponential, Floating point, Integer"
158 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
159 (const :tag
"Very General Number-Like, including hex and Calc radix"
160 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
161 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
162 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
163 (string :tag
"Regexp:")))
165 (defcustom org-table-number-fraction
0.5
166 "Fraction of numbers in a column required to make the column align right.
167 In a column all non-white fields are considered. If at least
168 this fraction of fields is matched by `org-table-number-regexp',
169 alignment to the right border applies."
170 :group
'org-table-settings
173 (defgroup org-table-editing nil
174 "Behavior of tables during editing in Org-mode."
175 :tag
"Org Table Editing"
178 (defcustom org-table-automatic-realign t
179 "Non-nil means automatically re-align table when pressing TAB or RETURN.
180 When nil, aligning is only done with \\[org-table-align], or after column
182 :group
'org-table-editing
185 (defcustom org-table-auto-blank-field t
186 "Non-nil means automatically blank table field when starting to type into it.
187 This only happens when typing immediately after a field motion
188 command (TAB, S-TAB or RET).
189 Only relevant when `org-enable-table-editor' is equal to `optimized'."
190 :group
'org-table-editing
193 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
194 "Non-nil means automatically exit the follow mode.
195 When nil, the follow mode will stay on and be active in any table
196 the cursor enters. Since the table follow filed mode messes with the
197 window configuration, it is not recommended to set this variable to nil,
198 except maybe locally in a special file that has mostly tables with long
204 (defcustom org-table-fix-formulas-confirm nil
205 "Whether the user should confirm when Org fixes formulas."
206 :group
'org-table-editing
209 (const :tag
"with yes-or-no" yes-or-no-p
)
210 (const :tag
"with y-or-n" y-or-n-p
)
211 (const :tag
"no confirmation" nil
)))
212 (put 'org-table-fix-formulas-confirm
214 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
216 (defcustom org-table-tab-jumps-over-hlines t
217 "Non-nil means tab in the last column of a table with jump over a hline.
218 If a horizontal separator line is following the current line,
219 `org-table-next-field' can either create a new row before that line, or jump
220 over the line. When this option is nil, a new line will be created before
222 :group
'org-table-editing
225 (defgroup org-table-calculation nil
226 "Options concerning tables in Org-mode."
227 :tag
"Org Table Calculation"
230 (defcustom org-table-use-standard-references
'from
231 "Should org-mode work with table references like B3 instead of @3$2?
234 from accept as input, do not present for editing
235 t accept as input and present for editing"
236 :group
'org-table-calculation
238 (const :tag
"Never, don't even check user input for them" nil
)
239 (const :tag
"Always, both as user input, and when editing" t
)
240 (const :tag
"Convert user input, don't offer during editing" from
)))
242 (defcustom org-table-copy-increment t
243 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
244 :group
'org-table-calculation
246 :package-version
'(Org .
"8.3")
248 (const :tag
"Use the difference between the current and the above fields" t
)
249 (integer :tag
"Use a number" 1)
250 (const :tag
"Don't increment the value when copying a field" nil
)))
252 (defcustom org-calc-default-modes
253 '(calc-internal-prec 12
254 calc-float-format
(float 8)
257 calc-symbolic-mode nil
258 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
259 calc-display-working-message t
261 "List with Calc mode settings for use in `calc-eval' for table formulas.
262 The list must contain alternating symbols (Calc modes variables and values).
263 Don't remove any of the default settings, just change the values. Org-mode
264 relies on the variables to be present in the list."
265 :group
'org-table-calculation
268 (defcustom org-table-duration-custom-format
'hours
269 "Format for the output of calc computations like $1+$2;t.
270 The default value is 'hours, and will output the results as a
271 number of hours. Other allowed values are 'seconds, 'minutes and
272 'days, and the output will be a fraction of seconds, minutes or
274 :group
'org-table-calculation
276 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
277 (symbol :tag
"Minutes" 'minutes
)
278 (symbol :tag
"Hours " 'hours
)
279 (symbol :tag
"Days " 'days
)))
281 (defcustom org-table-formula-field-format
"%s"
282 "Format for fields which contain the result of a formula.
283 For example, using \"~%s~\" will display the result within tilde
284 characters. Beware that modifying the display can prevent the
285 field from being used in another formula."
286 :group
'org-table-settings
290 (defcustom org-table-formula-evaluate-inline t
291 "Non-nil means TAB and RET evaluate a formula in current table field.
292 If the current field starts with an equal sign, it is assumed to be a formula
293 which should be evaluated as described in the manual and in the documentation
294 string of the command `org-table-eval-formula'. This feature requires the
296 When this variable is nil, formula calculation is only available through
297 the command \\[org-table-eval-formula]."
298 :group
'org-table-calculation
301 (defcustom org-table-formula-use-constants t
302 "Non-nil means interpret constants in formulas in tables.
303 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
304 by the value given in `org-table-formula-constants', or by a value obtained
305 from the `constants.el' package."
306 :group
'org-table-calculation
309 (defcustom org-table-formula-constants nil
310 "Alist with constant names and values, for use in table formulas.
311 The car of each element is a name of a constant, without the `$' before it.
312 The cdr is the value as a string. For example, if you'd like to use the
313 speed of light in a formula, you would configure
315 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
317 and then use it in an equation like `$1*$c'.
319 Constants can also be defined on a per-file basis using a line like
321 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
322 :group
'org-table-calculation
324 (cons (string :tag
"name")
325 (string :tag
"value"))))
327 (defcustom org-table-allow-automatic-line-recalculation t
328 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
329 Automatically means when TAB or RET or C-c C-c are pressed in the line."
330 :group
'org-table-calculation
333 (defcustom org-table-error-on-row-ref-crossing-hline t
334 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
338 (defcustom org-table-relative-ref-may-cross-hline t
339 "Non-nil means relative formula references may cross hlines.
340 Here are the allowed values:
342 nil Relative references may not cross hlines. They will reference the
343 field next to the hline instead. Coming from below, the reference
344 will be to the field below the hline. Coming from above, it will be
346 t Relative references may cross hlines.
347 error An attempt to cross a hline will throw an error.
349 It is probably good to never set this variable to nil, for the sake of
350 portability of tables."
351 :group
'org-table-calculation
353 (const :tag
"Allow to cross" t
)
354 (const :tag
"Stick to hline" nil
)
355 (const :tag
"Error on attempt to cross" error
)))
357 (defcustom org-table-formula-create-columns nil
358 "Non-nil means that evaluation of a field formula can add new
359 columns if an out-of-bounds field is being set."
360 :group
'org-table-calculation
362 :package-version
'(Org .
"8.3")
364 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
365 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
366 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
367 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
369 (defgroup org-table-import-export nil
370 "Options concerning table import and export in Org-mode."
371 :tag
"Org Table Import Export"
374 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
375 "Default export parameters for `org-table-export'.
376 These can be overridden for a specific table by setting the
377 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
378 radio tables for the different export transformations and
379 available parameters."
380 :group
'org-table-import-export
383 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
384 "Detects a table line marked for automatic recalculation.")
385 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
386 "Detects a table line marked for automatic recalculation.")
387 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
388 "Detects a table line marked for automatic recalculation.")
389 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
390 "Searching from within a table (any type) this finds the first line outside the table.")
391 (defvar org-table-last-highlighted-reference nil
)
392 (defvar org-table-formula-history nil
)
394 (defvar org-table-column-names nil
395 "Alist with column names, derived from the `!' line.")
396 (defvar org-table-column-name-regexp nil
397 "Regular expression matching the current column names.")
398 (defvar org-table-local-parameters nil
399 "Alist with parameter names, derived from the `$' line.")
400 (defvar org-table-named-field-locations nil
401 "Alist with locations of named fields.")
403 (defvar org-table-current-line-types nil
404 "Table row types, non-nil only for the duration of a command.")
405 (defvar org-table-current-begin-line nil
406 "Table begin line, non-nil only for the duration of a command.")
407 (defvar org-table-current-begin-pos nil
408 "Table begin position, non-nil only for the duration of a command.")
409 (defvar org-table-current-ncol nil
410 "Number of columns in table, non-nil only for the duration of a command.")
411 (defvar org-table-dlines nil
412 "Vector of data line line numbers in the current table.")
413 (defvar org-table-hlines nil
414 "Vector of hline line numbers in the current table.")
416 (defconst org-table-range-regexp
417 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
419 "Regular expression for matching ranges in formulas.")
421 (defconst org-table-range-regexp2
423 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
425 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
426 "Match a range for reference display.")
428 (defun org-table-colgroup-line-p (line)
429 "Is this a table line colgroup information?"
431 (and (string-match "[<>]\\|&[lg]t;" line
)
432 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
438 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
439 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
441 (defun org-table-cookie-line-p (line)
442 "Is this a table line with only alignment/width cookies?"
444 (and (string-match "[<>]\\|&[lg]t;" line
)
446 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
447 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
448 (not (delq nil
(mapcar
450 (not (or (equal s
"")
452 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
454 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
456 (org-split-string (match-string 1 line
)
457 "[ \t]*|[ \t]*")))))))
459 (defconst org-table-translate-regexp
460 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
461 "Match a reference that needs translation, for reference display.")
464 (defun org-table-create-with-table.el
()
465 "Use the table.el package to insert a new table.
466 If there is already a table at point, convert between Org-mode tables
467 and table.el tables."
472 (if (y-or-n-p "Convert table to Org-mode table? ")
473 (org-table-convert)))
475 (when (y-or-n-p "Convert table to table.el table? ")
477 (org-table-convert)))
478 (t (call-interactively 'table-insert
))))
481 (defun org-table-create-or-convert-from-region (arg)
482 "Convert region to table, or create an empty table.
483 If there is an active region, convert it to a table, using the function
484 `org-table-convert-region'. See the documentation of that function
485 to learn how the prefix argument is interpreted to determine the field
487 If there is no such region, create an empty table with `org-table-create'."
489 (if (org-region-active-p)
490 (org-table-convert-region (region-beginning) (region-end) arg
)
491 (org-table-create arg
)))
494 (defun org-table-create (&optional size
)
495 "Query for a size and insert a table skeleton.
496 SIZE is a string Columns x Rows like for example \"3x2\"."
499 (setq size
(read-string
500 (concat "Table size Columns x Rows [e.g. "
501 org-table-default-size
"]: ")
502 "" nil org-table-default-size
)))
505 (indent (make-string (current-column) ?\
))
506 (split (org-split-string size
" *x *"))
507 (rows (string-to-number (nth 1 split
)))
508 (columns (string-to-number (car split
)))
509 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
511 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
512 (point-at-bol) (point)))
513 (beginning-of-line 1)
515 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
516 (dotimes (i rows
) (insert line
))
519 ;; Insert a hline after the first row.
527 (defun org-table-convert-region (beg0 end0
&optional separator
)
528 "Convert region to a table.
529 The region goes from BEG0 to END0, but these borders will be moved
530 slightly, to make sure a beginning of line in the first line is included.
532 SEPARATOR specifies the field separator in the lines. It can have the
535 '(4) Use the comma as a field separator
536 '(16) Use a TAB as field separator
537 '(64) Prompt for a regular expression as field separator
538 integer When a number, use that many spaces as field separator
539 regexp When a regular expression, use it to match the separator
540 nil When nil, the command tries to be smart and figure out the
541 separator in the following way:
542 - when each line contains a TAB, assume TAB-separated material
543 - when each line contains a comma, assume CSV material
544 - else, assume one or more SPACE characters as separator."
546 (let* ((beg (min beg0 end0
))
547 (end (max beg0 end0
))
549 (if (equal separator
'(64))
550 (setq separator
(read-regexp "Regexp for field separator")))
552 (beginning-of-line 1)
553 (setq beg
(point-marker))
555 (if (bolp) (backward-char 1) (end-of-line 1))
556 (setq end
(point-marker))
557 ;; Get the right field separator
562 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
563 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
566 (if (equal separator
'(4))
567 (while (< (point) end
)
568 ;; parse the csv stuff
570 ((looking-at "^") (insert "| "))
571 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
572 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
573 (replace-match "\\1")
574 (if (looking-at "\"") (insert "\"")))
575 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
576 ((looking-at "[ \t]*,") (replace-match " | "))
577 (t (beginning-of-line 2))))
579 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
580 ((equal separator
'(16)) "^\\|\t")
581 ((integerp separator
)
583 (user-error "Number of spaces in separator must be >= 1")
584 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
586 (format "^ *\\|%s" separator
))
587 (t (error "This should not happen"))))
588 (while (re-search-forward re end t
)
589 (replace-match "| " t t
)))
594 (defun org-table-import (file arg
)
595 "Import FILE as a table.
596 The file is assumed to be tab-separated. Such files can be produced by most
597 spreadsheet and database applications. If no tabs (at least one per line)
598 are found, lines will be split on whitespace into fields."
600 (or (bolp) (newline))
603 (insert-file-contents file
)
604 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
608 (defun org-table-export (&optional file format
)
609 "Export table to a file, with configurable format.
610 Such a file can be imported into usual spreadsheet programs.
612 FILE can be the output file name. If not given, it will be taken
613 from a TABLE_EXPORT_FILE property in the current entry or higher
614 up in the hierarchy, or the user will be prompted for a file
615 name. FORMAT can be an export format, of the same kind as it
616 used when `orgtbl-mode' sends a table in a different format.
618 The command suggests a format depending on TABLE_EXPORT_FORMAT,
619 whether it is set locally or up in the hierarchy, then on the
620 extension of the given file name, and finally on the variable
621 `org-table-export-default-format'."
623 (unless (org-at-table-p) (user-error "No table at point"))
624 (org-table-align) ; Make sure we have everything we need.
625 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
627 (setq file
(read-file-name "Export table to: "))
628 (unless (or (not (file-exists-p file
))
629 (y-or-n-p (format "Overwrite file %s? " file
)))
630 (user-error "File not written")))
631 (when (file-directory-p file
)
632 (user-error "This is a directory path, not a file"))
633 (when (and (buffer-file-name (buffer-base-buffer))
636 (file-truename (buffer-file-name (buffer-base-buffer)))))
637 (user-error "Please specify a file name that is different from current"))
638 (let ((fileext (concat (file-name-extension file
) "$"))
639 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
641 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
642 "orgtbl-to-html" "orgtbl-to-generic"
643 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
644 "orgtbl-to-unicode"))
646 (replace-regexp-in-string
648 (replace-regexp-in-string
653 (and (org-string-match-p fileext f
) f
))
655 org-table-export-default-format
)
659 "Format: " formats nil nil deffmt-readable
))))
660 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
661 (let ((transform (intern (match-string 1 format
)))
662 (params (and (match-end 2)
663 (read (concat "(" (match-string 2 format
) ")"))))
664 (table (org-table-to-lisp
665 (buffer-substring-no-properties
666 (org-table-begin) (org-table-end)))))
667 (unless (fboundp transform
)
668 (user-error "No such transformation function %s" transform
))
670 (with-current-buffer (find-file-noselect file
)
671 (setq buf
(current-buffer))
674 (insert (funcall transform table params
) "\n")
677 (message "Export done."))
678 (user-error "TABLE_EXPORT_FORMAT invalid")))))
680 (defvar org-table-aligned-begin-marker
(make-marker)
681 "Marker at the beginning of the table last aligned.
682 Used to check if cursor still is in that table, to minimize realignment.")
683 (defvar org-table-aligned-end-marker
(make-marker)
684 "Marker at the end of the table last aligned.
685 Used to check if cursor still is in that table, to minimize realignment.")
686 (defvar org-table-last-alignment nil
687 "List of flags for flushright alignment, from the last re-alignment.
688 This is being used to correctly align a single field after TAB or RET.")
689 (defvar org-table-last-column-widths nil
690 "List of max width of fields in each column.
691 This is being used to correctly align a single field after TAB or RET.")
692 (defvar org-table-formula-debug nil
693 "Non-nil means debug table formulas.
694 When nil, simply write \"#ERROR\" in corrupted fields.")
695 (make-variable-buffer-local 'org-table-formula-debug
)
696 (defvar org-table-overlay-coordinates nil
697 "Overlay coordinates after each align of a table.")
698 (make-variable-buffer-local 'org-table-overlay-coordinates
)
700 (defvar org-last-recalc-line nil
)
701 (defvar org-table-do-narrow t
) ; for dynamic scoping
702 (defconst org-narrow-column-arrow
"=>"
703 "Used as display property in narrowed table columns.")
706 (defun org-table-align ()
707 "Align the table at point by aligning all vertical bars."
711 (beg (org-table-begin))
712 (end (org-table-end))
713 ;; Current cursor position
714 (linepos (org-current-line))
715 (colpos (org-table-current-column))
716 (winstart (window-start))
717 (winstartline (org-current-line (min winstart
(1- (point-max)))))
718 lines
(new "") lengths l typenums ty fields maxfields i
726 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
728 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
729 emptystrings links dates emph raise narrow
730 falign falign1 fmax f1 f2 len c e space
)
732 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
733 ;; Check if we have links or dates
735 (setq links
(re-search-forward org-bracket-link-regexp end t
))
737 (setq emph
(and org-hide-emphasis-markers
738 (re-search-forward org-emph-re end t
)))
740 (setq raise
(and org-use-sub-superscripts
741 (re-search-forward org-match-substring-regexp end t
)))
743 (setq dates
(and org-display-custom-times
744 (re-search-forward org-ts-regexp-both end t
)))
745 ;; Make sure the link properties are right
746 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
747 ;; Make sure the date properties are right
748 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
749 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
750 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
752 ;; Check if we are narrowing any columns
754 (setq narrow
(and org-table-do-narrow
755 org-format-transports-properties-p
756 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
758 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
761 (setq lines
(org-split-string
762 (buffer-substring beg end
) "\n"))
763 ;; Store the indentation of the first line
764 (if (string-match "^ *" (car lines
))
765 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
766 ;; Mark the hlines by setting the corresponding element to nil
767 ;; At the same time, we remove trailing space.
768 (setq lines
(mapcar (lambda (l)
769 (if (string-match "^ *|-" l
)
771 (if (string-match "[ \t]+$" l
)
772 (substring l
0 (match-beginning 0))
775 ;; Get the data fields by splitting the lines.
778 (org-split-string l
" *| *"))
779 (delq nil
(copy-sequence lines
))))
780 ;; How many fields in the longest line?
782 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
784 (kill-region beg end
)
785 (org-table-create org-table-default-size
)
786 (user-error "Empty table - created default table")))
787 ;; A list of empty strings to fill any short rows on output
788 (setq emptystrings
(make-list maxfields
""))
789 ;; Check for special formatting.
791 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
792 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
793 ;; Check if there is an explicit width specified
795 (when (or narrow falign
)
796 (setq c column fmax nil falign1 nil
)
799 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
800 (if (match-end 1) (setq falign1
(match-string 1 e
)))
801 (if (and org-table-do-narrow
(match-end 2))
802 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
803 ;; Find fields that are wider than fmax, and shorten them
805 (loop for xx in column do
806 (when (and (stringp xx
)
807 (> (org-string-width xx
) fmax
))
808 (org-add-props xx nil
810 (concat "Clipped table field, use C-c ` to edit. Full value is:\n"
811 (org-no-properties (copy-sequence xx
))))
812 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
814 (user-error "Cannot narrow field starting with wide link \"%s\""
815 (match-string 0 xx
)))
816 (setq f2
(length xx
))
817 (if (= (org-string-width xx
)
821 (while (< (org-string-width (substring xx
0 f2
))
824 (add-text-properties f2
(length xx
) (list 'org-cwidth t
) xx
)
825 (add-text-properties (if (>= (string-width (substring xx
(1- f2
) f2
)) 2)
827 (list 'display org-narrow-column-arrow
)
829 ;; Get the maximum width for each column
830 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
832 ;; Get the fraction of numbers, to decide about alignment of the column
834 (push (equal (downcase falign1
) "r") typenums
)
835 (setq cnt
0 frac
0.0)
836 (loop for x in column do
839 (setq frac
( / (+ (* frac cnt
)
840 (if (string-match org-table-number-regexp x
) 1 0))
841 (setq cnt
(1+ cnt
))))))
842 (push (>= frac org-table-number-fraction
) typenums
)))
843 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
845 ;; Store the alignment of this table, for later editing of single fields
846 (setq org-table-last-alignment typenums
847 org-table-last-column-widths lengths
)
849 ;; With invisible characters, `format' does not get the field width right
850 ;; So we need to make these fields wide by hand.
851 (when (or links emph raise
)
852 (loop for i from
0 upto
(1- maxfields
) do
853 (setq len
(nth i lengths
))
854 (loop for j from
0 upto
(1- (length fields
)) do
855 (setq c
(nthcdr i
(car (nthcdr j fields
))))
856 (if (and (stringp (car c
))
857 (or (text-property-any 0 (length (car c
))
858 'invisible
'org-link
(car c
))
859 (text-property-any 0 (length (car c
))
860 'org-dwidth t
(car c
)))
861 (< (org-string-width (car c
)) len
))
863 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
864 (setcar c
(if (nth i typenums
)
865 (concat space
(car c
))
866 (concat (car c
) space
))))))))
868 ;; Compute the formats needed for output of the table
869 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
870 (while (setq l
(pop lengths
))
871 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
872 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
873 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
874 (setq rfmt
(concat rfmt
"\n")
875 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
879 (if l
(apply 'format rfmt
880 (append (pop fields
) emptystrings
))
883 (move-marker org-table-aligned-begin-marker
(point))
885 ;; Replace the old one
886 (delete-region (point) end
)
887 (move-marker end nil
)
888 (move-marker org-table-aligned-end-marker
(point))
889 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
890 (goto-char org-table-aligned-begin-marker
)
891 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
892 ;; Try to move to the old location
893 (org-goto-line winstartline
)
894 (setq winstart
(point-at-bol))
895 (org-goto-line linepos
)
896 (when (eq (window-buffer (selected-window)) (current-buffer))
897 (set-window-start (selected-window) winstart
'noforce
))
898 (org-table-goto-column colpos
)
899 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
900 (setq org-table-may-need-update nil
)
904 (defun org-table-begin (&optional table-type
)
905 "Find the beginning of the table and return its position.
906 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
908 (if (not (re-search-backward
909 (if table-type org-table-any-border-regexp
910 org-table-border-regexp
)
912 (progn (goto-char (point-min)) (point))
913 (goto-char (match-beginning 0))
914 (beginning-of-line 2)
918 (defun org-table-end (&optional table-type
)
919 "Find the end of the table and return its position.
920 With argument TABLE-TYPE, go to the end of a table.el-type table."
922 (if (not (re-search-forward
923 (if table-type org-table-any-border-regexp
924 org-table-border-regexp
)
926 (goto-char (point-max))
927 (goto-char (match-beginning 0)))
931 (defun org-table-justify-field-maybe (&optional new
)
932 "Justify the current field, text to left, number to right.
933 Optional argument NEW may specify text to replace the current field content."
935 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
936 ((org-at-table-hline-p))
938 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
940 (< (point) org-table-aligned-begin-marker
)
941 (>= (point) org-table-aligned-end-marker
)))
942 ;; This is not the same table, force a full re-align
943 (setq org-table-may-need-update t
))
944 (t ;; realign the current field, based on previous full realign
945 (let* ((pos (point)) s
946 (col (org-table-current-column))
947 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
950 (skip-chars-backward "^|\n")
951 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
953 (setq s
(match-string 1)
957 (buffer-substring-no-properties
958 (match-end 0) (match-beginning 0))) 3))
959 e
(not (= (match-beginning 2) (match-end 2))))
960 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
961 l
(if e
"|" (setq org-table-may-need-update t
) ""))
964 (if (<= (org-string-width new
) l
)
965 (setq n
(format f new
))
966 (setq n
(concat new
"|") org-table-may-need-update t
)))
967 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
969 (let (org-table-may-need-update)
970 (replace-match n t t
))))
971 (setq org-table-may-need-update t
))
975 (defun org-table-next-field ()
976 "Go to the next field in the current table, creating new lines as needed.
977 Before doing so, re-align the table if necessary."
979 (org-table-maybe-eval-formula)
980 (org-table-maybe-recalculate-line)
981 (if (and org-table-automatic-realign
982 org-table-may-need-update
)
984 (let ((end (org-table-end)))
985 (if (org-at-table-hline-p)
989 (re-search-forward "|" end
)
990 (if (looking-at "[ \t]*$")
991 (re-search-forward "|" end
))
992 (if (and (looking-at "-")
993 org-table-tab-jumps-over-hlines
994 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
995 (goto-char (match-beginning 1)))
998 (beginning-of-line 0)
999 (org-table-insert-row 'below
))
1000 (if (looking-at " ") (forward-char 1))))
1002 (org-table-insert-row 'below
)))))
1005 (defun org-table-previous-field ()
1006 "Go to the previous field in the table.
1007 Before doing so, re-align the table if necessary."
1009 (org-table-justify-field-maybe)
1010 (org-table-maybe-recalculate-line)
1011 (if (and org-table-automatic-realign
1012 org-table-may-need-update
)
1014 (if (org-at-table-hline-p)
1018 (re-search-backward "|" (org-table-begin))
1019 (re-search-backward "|" (org-table-begin)))
1020 (error (user-error "Cannot move to previous table field")))
1021 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1022 (re-search-backward "|" (org-table-begin)))
1023 (if (looking-at "| ?")
1024 (goto-char (match-end 0))))
1026 (defun org-table-beginning-of-field (&optional n
)
1027 "Move to the end of the current table field.
1028 If already at or after the end, move to the end of the next table field.
1029 With numeric argument N, move N-1 fields forward first."
1031 (let ((pos (point)))
1034 (org-table-previous-field))
1035 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1036 (user-error "No more table fields before the current")
1037 (goto-char (match-end 0))
1038 (and (looking-at " ") (forward-char 1)))
1039 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1041 (defun org-table-end-of-field (&optional n
)
1042 "Move to the beginning of the current table field.
1043 If already at or before the beginning, move to the beginning of the
1045 With numeric argument N, move N-1 fields backward first."
1047 (let ((pos (point)))
1050 (org-table-next-field))
1051 (when (re-search-forward "|" (point-at-eol 1) t
)
1053 (skip-chars-backward " ")
1054 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1056 (if (<= (point) pos
) (org-table-end-of-field 2))))
1059 (defun org-table-next-row ()
1060 "Go to the next row (same column) in the current table.
1061 Before doing so, re-align the table if necessary."
1063 (org-table-maybe-eval-formula)
1064 (org-table-maybe-recalculate-line)
1065 (if (or (looking-at "[ \t]*$")
1066 (save-excursion (skip-chars-backward " \t") (bolp)))
1068 (if (and org-table-automatic-realign
1069 org-table-may-need-update
)
1071 (let ((col (org-table-current-column)))
1072 (beginning-of-line 2)
1073 (if (or (not (org-at-table-p))
1074 (org-at-table-hline-p))
1076 (beginning-of-line 0)
1077 (org-table-insert-row 'below
)))
1078 (org-table-goto-column col
)
1079 (skip-chars-backward "^|\n\r")
1080 (if (looking-at " ") (forward-char 1)))))
1083 (defun org-table-copy-down (n)
1084 "Copy the value of the current field one row below.
1086 If the field at the cursor is empty, copy the content of the
1087 nearest non-empty field above. With argument N, use the Nth
1090 If the current field is not empty, it is copied down to the next
1091 row, and the cursor is moved with it. Therefore, repeating this
1092 command causes the column to be filled row-by-row.
1094 If the variable `org-table-copy-increment' is non-nil and the
1095 field is an integer or a timestamp, it will be incremented while
1096 copying. By default, increment by the difference between the
1097 value in the current field and the one in the field above. To
1098 increment using a fixed integer, set `org-table-copy-increment'
1099 to a number. In the case of a timestamp, increment by days."
1101 (let* ((colpos (org-table-current-column))
1102 (col (current-column))
1103 (field (save-excursion (org-table-get-field)))
1104 (field-up (or (save-excursion
1105 (org-table-get (1- (org-table-current-line))
1106 (org-table-current-column))) ""))
1107 (non-empty (string-match "[^ \t]" field
))
1108 (non-empty-up (string-match "[^ \t]" field-up
))
1109 (beg (org-table-begin))
1112 (org-table-check-inside-data-field)
1117 (while (progn (beginning-of-line 1)
1118 (re-search-backward org-table-dataline-regexp
1120 (org-table-goto-column colpos t
)
1121 (if (and (looking-at
1122 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1123 (<= (setq n
(1- n
)) 0))
1124 (throw 'exit
(match-string 1))))))
1127 (while (progn (beginning-of-line 1)
1128 (re-search-backward org-table-dataline-regexp
1130 (org-table-goto-column colpos t
)
1131 (if (and (looking-at
1132 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1133 (<= (setq n
(1- n
)) 0))
1134 (throw 'exit
(match-string 1))))))
1135 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1136 ;; Above field was not empty, go down to the next row
1137 (setq txt
(org-trim field
))
1138 (org-table-next-row)
1139 (org-table-blank-field))
1140 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1142 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1143 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1144 (string-match org-ts-regexp3 txt
))
1145 (- (org-time-string-to-absolute txt
)
1146 (org-time-string-to-absolute txt-up
)))
1147 ((string-match org-ts-regexp3 txt
) 1)
1148 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1149 (- (string-to-number txt
)
1150 (string-to-number (match-string 0 txt-up
))))
1154 (user-error "No non-empty field found")
1155 (if (and org-table-copy-increment
1156 (not (equal orig-n
0))
1157 (string-match "^[-+^/*0-9eE.]+$" txt
)
1158 (< (string-to-number txt
) 100000000))
1159 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1161 (org-move-to-column col
)
1162 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1163 (org-timestamp-up-day inc
)
1164 (org-table-maybe-recalculate-line))
1166 (org-move-to-column col
))))
1168 (defun org-table-check-inside-data-field (&optional noerror
)
1169 "Is point inside a table data field?
1170 I.e. not on a hline or before the first or after the last column?
1171 This actually throws an error, so it aborts the current command."
1172 (if (or (not (org-at-table-p))
1173 (= (org-table-current-column) 0)
1174 (org-at-table-hline-p)
1175 (looking-at "[ \t]*$"))
1178 (user-error "Not in table data field"))
1181 (defvar org-table-clip nil
1182 "Clipboard for table regions.")
1184 (defun org-table-get (line column
)
1185 "Get the field in table line LINE, column COLUMN.
1186 If LINE is larger than the number of data lines in the table, the function
1187 returns nil. However, if COLUMN is too large, we will simply return an
1189 If LINE is nil, use the current line.
1190 If COLUMN is nil, use the current column."
1191 (setq column
(or column
(org-table-current-column)))
1193 (and (or (not line
) (org-table-goto-line line
))
1194 (org-trim (org-table-get-field column
)))))
1196 (defun org-table-put (line column value
&optional align
)
1197 "Put VALUE into line LINE, column COLUMN.
1198 When ALIGN is set, also realign the table."
1199 (setq column
(or column
(org-table-current-column)))
1200 (prog1 (save-excursion
1201 (and (or (not line
) (org-table-goto-line line
))
1202 (progn (org-table-goto-column column nil
'force
) t
)
1203 (org-table-get-field column value
)))
1204 (and align
(org-table-align))))
1206 (defun org-table-current-line ()
1207 "Return the index of the current data line."
1208 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1210 (goto-char (org-table-begin))
1211 (while (and (re-search-forward org-table-dataline-regexp end t
)
1213 (< (point-at-eol) pos
))))
1216 (defun org-table-goto-line (N)
1217 "Go to the Nth data line in the current table.
1218 Return t when the line exists, nil if it does not exist."
1219 (goto-char (org-table-begin))
1220 (let ((end (org-table-end)) (cnt 0))
1221 (while (and (re-search-forward org-table-dataline-regexp end t
)
1222 (< (setq cnt
(1+ cnt
)) N
)))
1226 (defun org-table-blank-field ()
1227 "Blank the current table field or active region."
1229 (org-table-check-inside-data-field)
1230 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1231 (let (org-table-clip)
1232 (org-table-cut-region (region-beginning) (region-end)))
1233 (skip-chars-backward "^|")
1235 (if (looking-at "|[^|\n]+")
1236 (let* ((pos (match-beginning 0))
1237 (match (match-string 0))
1238 (len (org-string-width match
)))
1239 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1240 (goto-char (+ 2 pos
))
1241 (substring match
1)))))
1243 (defun org-table-get-field (&optional n replace
)
1244 "Return the value of the field in column N of current row.
1245 N defaults to current field.
1246 If REPLACE is a string, replace field with this value. The return value
1247 is always the old value."
1248 (and n
(org-table-goto-column n
))
1249 (skip-chars-backward "^|\n")
1251 (if (looking-at "|[^|\r\n]*")
1252 (let* ((pos (match-beginning 0))
1253 (val (buffer-substring (1+ pos
) (match-end 0))))
1255 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1257 (goto-char (min (point-at-eol) (+ 2 pos
)))
1259 (forward-char 1) ""))
1262 (defun org-table-field-info (arg)
1263 "Show info about the current field, and highlight any reference at point."
1265 (unless (org-at-table-p) (user-error "Not at a table"))
1266 (org-table-get-specials)
1268 (let* ((pos (point))
1269 (col (org-table-current-column))
1270 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1271 (name (car (rassoc (list (org-current-line) col
)
1272 org-table-named-field-locations
)))
1273 (eql (org-table-expand-lhs-ranges
1276 (cons (org-table-formula-handle-first/last-rc
1278 (org-table-get-stored-formulas))))
1279 (dline (org-table-current-dline))
1280 (ref (format "@%d$%d" dline col
))
1281 (ref1 (org-table-convert-refs-to-an ref
))
1282 (fequation (or (assoc name eql
) (assoc ref eql
)))
1283 (cequation (assoc (int-to-string col
) eql
))
1284 (eqn (or fequation cequation
)))
1285 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1286 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1289 (org-table-show-reference 'local
)
1291 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1293 (if cname
(concat " or $" cname
) "")
1295 (if name
(concat " or $" name
) "")
1296 ;; FIXME: formula info not correct if special table line
1298 (concat ", formula: "
1299 (org-table-formula-to-user
1301 (if (string-match "^[$@]"(car eqn
)) "" "$")
1302 (car eqn
) "=" (cdr eqn
))))
1305 (defun org-table-current-column ()
1306 "Find out which column we are in."
1308 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1310 (let ((cnt 0) (pos (point)))
1311 (beginning-of-line 1)
1312 (while (search-forward "|" pos t
)
1313 (setq cnt
(1+ cnt
)))
1314 (when (org-called-interactively-p 'interactive
)
1315 (message "In table column %d" cnt
))
1319 (defun org-table-current-dline ()
1320 "Find out what table data line we are in.
1321 Only data lines count for this."
1323 (when (org-called-interactively-p 'any
)
1324 (org-table-check-inside-data-field))
1326 (let ((cnt 0) (pos (point)))
1327 (goto-char (org-table-begin))
1328 (while (<= (point) pos
)
1329 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1330 (beginning-of-line 2))
1331 (when (org-called-interactively-p 'any
)
1332 (message "This is table line %d" cnt
))
1336 (defun org-table-goto-column (n &optional on-delim force
)
1337 "Move the cursor to the Nth column in the current table line.
1338 With optional argument ON-DELIM, stop with point before the left delimiter
1340 If there are less than N fields, just go to after the last delimiter.
1341 However, when FORCE is non-nil, create new columns if necessary."
1343 (beginning-of-line 1)
1345 (while (and (> (setq n
(1- n
)) -
1)
1346 (or (search-forward "|" (point-at-eol) t
)
1348 (progn (end-of-line 1)
1349 (skip-chars-backward "^|")
1352 (when (and force
(not (looking-at ".*|")))
1353 (save-excursion (end-of-line 1) (insert " | ")))
1356 (if (looking-at " ") (forward-char 1)))))
1359 (defun org-table-insert-column ()
1360 "Insert a new column into the table."
1362 (if (not (org-at-table-p))
1363 (user-error "Not at a table"))
1364 (org-table-find-dataline)
1365 (let* ((col (max 1 (org-table-current-column)))
1366 (beg (org-table-begin))
1367 (end (org-table-end))
1368 ;; Current cursor position
1369 (linepos (org-current-line))
1372 (while (< (point) end
)
1373 (if (org-at-table-hline-p)
1375 (org-table-goto-column col t
)
1377 (beginning-of-line 2))
1378 (move-marker end nil
)
1379 (org-goto-line linepos
)
1380 (org-table-goto-column colpos
)
1382 (when (or (not org-table-fix-formulas-confirm
)
1383 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1384 (org-table-fix-formulas "$" nil
(1- col
) 1)
1385 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1387 (defun org-table-find-dataline ()
1388 "Find a data line in the current table, which is needed for column commands."
1389 (if (and (org-at-table-p)
1390 (not (org-at-table-hline-p)))
1392 (let ((col (current-column))
1393 (end (org-table-end)))
1394 (org-move-to-column col
)
1395 (while (and (< (point) end
)
1396 (or (not (= (current-column) col
))
1397 (org-at-table-hline-p)))
1398 (beginning-of-line 2)
1399 (org-move-to-column col
))
1400 (if (and (org-at-table-p)
1401 (not (org-at-table-hline-p)))
1404 "Please position cursor in a data line for column operations")))))
1406 (defun org-table-line-to-dline (line &optional above
)
1407 "Turn a buffer line number into a data line number.
1408 If there is no data line in this line, return nil.
1409 If there is no matching dline (most likely te reference was a hline), the
1410 first dline below it is used. When ABOVE is non-nil, the one above is used."
1412 (let ((ll (length org-table-dlines
))
1418 (if (<= (aref org-table-dlines i
) line
)
1423 (if (>= (aref org-table-dlines i
) line
)
1429 (defun org-table-delete-column ()
1430 "Delete a column from the table."
1432 (if (not (org-at-table-p))
1433 (user-error "Not at a table"))
1434 (org-table-find-dataline)
1435 (org-table-check-inside-data-field)
1436 (let* ((col (org-table-current-column))
1437 (beg (org-table-begin))
1438 (end (org-table-end))
1439 ;; Current cursor position
1440 (linepos (org-current-line))
1443 (while (< (point) end
)
1444 (if (org-at-table-hline-p)
1446 (org-table-goto-column col t
)
1447 (and (looking-at "|[^|\n]+|")
1448 (replace-match "|")))
1449 (beginning-of-line 2))
1450 (move-marker end nil
)
1451 (org-goto-line linepos
)
1452 (org-table-goto-column colpos
)
1454 (when (or (not org-table-fix-formulas-confirm
)
1455 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1456 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1458 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1462 (defun org-table-move-column-right ()
1463 "Move column to the right."
1465 (org-table-move-column nil
))
1467 (defun org-table-move-column-left ()
1468 "Move column to the left."
1470 (org-table-move-column 'left
))
1473 (defun org-table-move-column (&optional left
)
1474 "Move the current column to the right. With arg LEFT, move to the left."
1476 (if (not (org-at-table-p))
1477 (user-error "Not at a table"))
1478 (org-table-find-dataline)
1479 (org-table-check-inside-data-field)
1480 (let* ((col (org-table-current-column))
1481 (col1 (if left
(1- col
) col
))
1482 (beg (org-table-begin))
1483 (end (org-table-end))
1484 ;; Current cursor position
1485 (linepos (org-current-line))
1486 (colpos (if left
(1- col
) (1+ col
))))
1487 (if (and left
(= col
1))
1488 (user-error "Cannot move column further left"))
1489 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1490 (user-error "Cannot move column further right"))
1492 (while (< (point) end
)
1493 (if (org-at-table-hline-p)
1495 (org-table-goto-column col1 t
)
1496 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1497 (replace-match "|\\2|\\1|")))
1498 (beginning-of-line 2))
1499 (move-marker end nil
)
1500 (org-goto-line linepos
)
1501 (org-table-goto-column colpos
)
1503 (when (or (not org-table-fix-formulas-confirm
)
1504 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1505 (org-table-fix-formulas
1506 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1507 (cons (number-to-string colpos
) (number-to-string col
))))
1508 (org-table-fix-formulas
1509 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1510 (cons (number-to-string colpos
) (number-to-string col
)))))))
1513 (defun org-table-move-row-down ()
1514 "Move table row down."
1516 (org-table-move-row nil
))
1518 (defun org-table-move-row-up ()
1519 "Move table row up."
1521 (org-table-move-row 'up
))
1524 (defun org-table-move-row (&optional up
)
1525 "Move the current table line down. With arg UP, move it up."
1527 (let* ((col (current-column))
1529 (hline1p (save-excursion (beginning-of-line 1)
1530 (looking-at org-table-hline-regexp
)))
1531 (dline1 (org-table-current-dline))
1532 (dline2 (+ dline1
(if up -
1 1)))
1535 (beginning-of-line tonew
)
1536 (unless (org-at-table-p)
1538 (user-error "Cannot move row further"))
1539 (setq hline2p
(looking-at org-table-hline-regexp
))
1541 (beginning-of-line 1)
1543 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1544 (delete-region (point) (1+ (point-at-eol)))
1545 (beginning-of-line tonew
)
1547 (beginning-of-line 0)
1548 (org-move-to-column col
)
1549 (unless (or hline1p hline2p
1550 (not (or (not org-table-fix-formulas-confirm
)
1551 (funcall org-table-fix-formulas-confirm
1552 "Fix formulas? "))))
1553 (org-table-fix-formulas
1554 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1555 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1558 (defun org-table-insert-row (&optional arg
)
1559 "Insert a new row above the current line into the table.
1560 With prefix ARG, insert below the current line."
1562 (if (not (org-at-table-p))
1563 (user-error "Not at a table"))
1564 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1565 (new (org-table-clean-line line
)))
1566 ;; Fix the first field if necessary
1567 (if (string-match "^[ \t]*| *[#$] *|" line
)
1568 (setq new
(replace-match (match-string 0 line
) t t new
)))
1569 (beginning-of-line (if arg
2 1))
1570 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1571 (beginning-of-line 0)
1572 (re-search-forward "| ?" (point-at-eol) t
)
1573 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1575 (when (or (not org-table-fix-formulas-confirm
)
1576 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1577 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1580 (defun org-table-insert-hline (&optional above
)
1581 "Insert a horizontal-line below the current line into the table.
1582 With prefix ABOVE, insert above the current line."
1584 (if (not (org-at-table-p))
1585 (user-error "Not at a table"))
1586 (when (eobp) (insert "\n") (backward-char 1))
1587 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1589 (let ((line (org-table-clean-line
1590 (buffer-substring (point-at-bol) (point-at-eol))))
1591 (col (current-column)))
1592 (while (string-match "|\\( +\\)|" line
)
1593 (setq line
(replace-match
1594 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1595 ?-
) "|") t t line
)))
1596 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1597 (beginning-of-line (if above
1 2))
1599 (beginning-of-line (if above
1 -
1))
1600 (org-move-to-column col
)
1601 (and org-table-overlay-coordinates
(org-table-align))))
1604 (defun org-table-hline-and-move (&optional same-column
)
1605 "Insert a hline and move to the row below that line."
1607 (let ((col (org-table-current-column)))
1608 (org-table-maybe-eval-formula)
1609 (org-table-maybe-recalculate-line)
1610 (org-table-insert-hline)
1612 (if (looking-at "\n[ \t]*|-")
1613 (progn (insert "\n|") (org-table-align))
1614 (org-table-next-field))
1615 (if same-column
(org-table-goto-column col
))))
1617 (defun org-table-clean-line (s)
1618 "Convert a table line S into a string with only \"|\" and space.
1619 In particular, this does handle wide and invisible characters."
1620 (if (string-match "^[ \t]*|-" s
)
1621 ;; It's a hline, just map the characters
1622 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1623 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1624 (setq s
(replace-match
1625 (concat "|" (make-string (org-string-width (match-string 1 s
))
1631 (defun org-table-kill-row ()
1632 "Delete the current row or horizontal line from the table."
1634 (if (not (org-at-table-p))
1635 (user-error "Not at a table"))
1636 (let ((col (current-column))
1637 (dline (org-table-current-dline)))
1638 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1639 (if (not (org-at-table-p)) (beginning-of-line 0))
1640 (org-move-to-column col
)
1641 (when (or (not org-table-fix-formulas-confirm
)
1642 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1643 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1647 (defun org-table-sort-lines (with-case &optional sorting-type
)
1648 "Sort table lines according to the column at point.
1650 The position of point indicates the column to be used for
1651 sorting, and the range of lines is the range between the nearest
1652 horizontal separator lines, or the entire table of no such lines
1653 exist. If point is before the first column, you will be prompted
1654 for the sorting column. If there is an active region, the mark
1655 specifies the first line and the sorting column, while point
1656 should be in the last line to be included into the sorting.
1658 The command then prompts for the sorting type which can be
1659 alphabetically, numerically, or by time (as given in a time stamp
1660 in the field, or as a HH:MM value). Sorting in reverse order is
1663 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1665 If SORTING-TYPE is specified when this function is called from a Lisp
1666 program, no prompting will take place. SORTING-TYPE must be a character,
1667 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1668 should be done in reverse order."
1670 (let* ((thisline (org-current-line))
1671 (thiscol (org-table-current-column))
1672 (otc org-table-overlay-coordinates
)
1673 beg end bcol ecol tend tbeg column lns pos
)
1674 (when (equal thiscol
0)
1675 (if (org-called-interactively-p 'any
)
1678 (read-string "Use column N for sorting: ")))
1680 (org-table-goto-column thiscol
))
1681 (org-table-check-inside-data-field)
1682 (if (org-region-active-p)
1684 (setq beg
(region-beginning) end
(region-end))
1686 (setq column
(org-table-current-column)
1689 (setq end
(point-at-bol 2)))
1690 (setq column
(org-table-current-column)
1692 tbeg
(org-table-begin)
1693 tend
(org-table-end))
1694 (if (re-search-backward org-table-hline-regexp tbeg t
)
1695 (setq beg
(point-at-bol 2))
1697 (setq beg
(point-at-bol 1)))
1699 (if (re-search-forward org-table-hline-regexp tend t
)
1700 (setq end
(point-at-bol 1))
1702 (setq end
(point-at-bol))))
1703 (setq beg
(move-marker (make-marker) beg
)
1704 end
(move-marker (make-marker) end
))
1707 (org-table-goto-column column
)
1708 (skip-chars-backward "^|")
1709 (setq bcol
(current-column))
1710 (org-table-goto-column (1+ column
))
1711 (skip-chars-backward "^|")
1712 (setq ecol
(1- (current-column)))
1713 (org-table-goto-column column
)
1714 (setq lns
(mapcar (lambda(x) (cons
1715 (org-sort-remove-invisible
1717 (org-split-string x
"[ \t]*|[ \t]*")))
1719 (org-split-string (buffer-substring beg end
) "\n")))
1720 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1721 (when org-table-overlay-coordinates
1722 (org-table-toggle-coordinate-overlays))
1723 (delete-region beg end
)
1724 (move-marker beg nil
)
1725 (move-marker end nil
)
1726 (insert (mapconcat 'cdr lns
"\n") "\n")
1727 (org-goto-line thisline
)
1728 (org-table-goto-column thiscol
)
1729 (when otc
(org-table-toggle-coordinate-overlays))
1730 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1733 (defun org-table-cut-region (beg end
)
1734 "Copy region in table to the clipboard and blank all relevant fields.
1735 If there is no active region, use just the field at point."
1737 (if (org-region-active-p) (region-beginning) (point))
1738 (if (org-region-active-p) (region-end) (point))))
1739 (org-table-copy-region beg end
'cut
))
1742 (defun org-table-copy-region (beg end
&optional cut
)
1743 "Copy rectangular region in table to clipboard.
1744 A special clipboard is used which can only be accessed
1745 with `org-table-paste-rectangle'."
1747 (if (org-region-active-p) (region-beginning) (point))
1748 (if (org-region-active-p) (region-end) (point))
1749 current-prefix-arg
))
1750 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1752 (rpl (if cut
" " nil
)))
1754 (org-table-check-inside-data-field)
1755 (setq l01
(org-current-line)
1756 c01
(org-table-current-column))
1758 (org-table-check-inside-data-field)
1759 (setq l02
(org-current-line)
1760 c02
(org-table-current-column))
1761 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1762 c1
(min c01 c02
) c2
(max c01 c02
))
1766 (if (> l1 l2
) (throw 'exit t
))
1768 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1769 (setq cols nil ic1 c1 ic2 c2
)
1770 (while (< ic1
(1+ ic2
))
1771 (push (org-table-get-field ic1 rpl
) cols
)
1772 (setq ic1
(1+ ic1
)))
1773 (push (nreverse cols
) region
)
1774 (setq l1
(1+ l1
)))))
1775 (setq org-table-clip
(nreverse region
))
1776 (if cut
(org-table-align))
1780 (defun org-table-paste-rectangle ()
1781 "Paste a rectangular region into a table.
1782 The upper right corner ends up in the current field. All involved fields
1783 will be overwritten. If the rectangle does not fit into the present table,
1784 the table is enlarged as needed. The process ignores horizontal separator
1787 (unless (and org-table-clip
(listp org-table-clip
))
1788 (user-error "First cut/copy a region to paste!"))
1789 (org-table-check-inside-data-field)
1790 (let* ((clip org-table-clip
)
1791 (line (org-current-line))
1792 (col (org-table-current-column))
1793 (org-enable-table-editor t
)
1794 (org-table-automatic-realign nil
)
1796 (while (setq cols
(pop clip
))
1797 (while (org-at-table-hline-p) (beginning-of-line 2))
1798 (if (not (org-at-table-p))
1799 (progn (end-of-line 0) (org-table-next-field)))
1801 (while (setq field
(pop cols
))
1802 (org-table-goto-column c nil
'force
)
1803 (org-table-get-field nil field
)
1805 (beginning-of-line 2))
1806 (org-goto-line line
)
1807 (org-table-goto-column col
)
1811 (defun org-table-convert ()
1812 "Convert from `org-mode' table to table.el and back.
1813 Obviously, this only works within limits. When an Org-mode table is
1814 converted to table.el, all horizontal separator lines get lost, because
1815 table.el uses these as cell boundaries and has no notion of horizontal lines.
1816 A table.el table can be converted to an Org-mode table only if it does not
1817 do row or column spanning. Multiline cells will become multiple cells.
1818 Beware, Org-mode does not test if the table can be successfully converted - it
1819 blindly applies a recipe that works for simple tables."
1822 (if (org-at-table.el-p
)
1823 ;; convert to Org-mode table
1824 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1825 (end (move-marker (make-marker) (org-table-end t
))))
1826 (table-unrecognize-region beg end
)
1828 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1831 (if (org-at-table-p)
1832 ;; convert to table.el table
1833 (let ((beg (move-marker (make-marker) (org-table-begin)))
1834 (end (move-marker (make-marker) (org-table-end))))
1835 ;; first, get rid of all horizontal lines
1837 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1839 ;; insert a hline before first
1841 (org-table-insert-hline 'above
)
1842 (beginning-of-line -
1)
1843 ;; insert a hline after each line
1844 (while (progn (beginning-of-line 3) (< (point) end
))
1845 (org-table-insert-hline))
1847 (setq end
(move-marker end
(org-table-end)))
1848 ;; replace "+" at beginning and ending of hlines
1849 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1850 (replace-match "\\1+-"))
1852 (while (re-search-forward "-|[ \t]*$" end t
)
1853 (replace-match "-+"))
1856 (defun org-table-transpose-table-at-point ()
1857 "Transpose Org table at point and eliminate hlines.
1865 will be transposed as
1872 Note that horizontal lines disappear."
1874 (let* ((table (delete 'hline
(org-table-to-lisp)))
1875 (dline_old (org-table-current-line))
1876 (col_old (org-table-current-column))
1877 (contents (mapcar (lambda (p)
1883 (setq tp
(cdr tp
))))
1886 (goto-char (org-table-begin))
1887 (re-search-forward "|")
1889 (delete-region (point) (org-table-end))
1892 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1894 (org-table-goto-line col_old
)
1895 (org-table-goto-column dline_old
))
1899 (defun org-table-wrap-region (arg)
1900 "Wrap several fields in a column like a paragraph.
1901 This is useful if you'd like to spread the contents of a field over several
1902 lines, in order to keep the table compact.
1904 If there is an active region, and both point and mark are in the same column,
1905 the text in the column is wrapped to minimum width for the given number of
1906 lines. Generally, this makes the table more compact. A prefix ARG may be
1907 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1908 formats the selected text to two lines. If the region was longer than two
1909 lines, the remaining lines remain empty. A negative prefix argument reduces
1910 the current number of lines by that amount. The wrapped text is pasted back
1911 into the table. If you formatted it to more lines than it was before, fields
1912 further down in the table get overwritten - so you might need to make space in
1915 If there is no region, the current field is split at the cursor position and
1916 the text fragment to the right of the cursor is prepended to the field one
1919 If there is no region, but you specify a prefix ARG, the current field gets
1920 blank, and the content is appended to the field above."
1922 (org-table-check-inside-data-field)
1923 (if (org-region-active-p)
1924 ;; There is a region: fill as a paragraph
1925 (let* ((beg (region-beginning))
1926 (cline (save-excursion (goto-char beg
) (org-current-line)))
1927 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1929 (org-table-cut-region (region-beginning) (region-end))
1930 (if (> (length (car org-table-clip
)) 1)
1931 (user-error "Region must be limited to single column"))
1932 (setq nlines
(if arg
1934 (+ (length org-table-clip
) arg
)
1936 (length org-table-clip
)))
1937 (setq org-table-clip
1938 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1940 (org-goto-line cline
)
1941 (org-table-goto-column ccol
)
1942 (org-table-paste-rectangle))
1943 ;; No region, split the current field at point
1944 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1945 (skip-chars-forward "^\r\n|"))
1947 ;; combine with field above
1948 (let ((s (org-table-blank-field))
1949 (col (org-table-current-column)))
1950 (beginning-of-line 0)
1951 (while (org-at-table-hline-p) (beginning-of-line 0))
1952 (org-table-goto-column col
)
1953 (skip-chars-forward "^|")
1954 (skip-chars-backward " ")
1955 (insert " " (org-trim s
))
1958 (if (looking-at "\\([^|]+\\)+|")
1959 (let ((s (match-string 1)))
1960 (replace-match " |")
1961 (goto-char (match-beginning 0))
1962 (org-table-next-row)
1963 (insert (org-trim s
) " ")
1965 (org-table-next-row)))))
1967 (defvar org-field-marker nil
)
1970 (defun org-table-edit-field (arg)
1971 "Edit table field in a different window.
1972 This is mainly useful for fields that contain hidden parts.
1973 When called with a \\[universal-argument] prefix, just make the full field visible so that
1974 it can be edited in place."
1978 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1980 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1981 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1982 (remove-text-properties b e
'(org-cwidth t invisible t
1983 display t intangible t
))
1984 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1985 (font-lock-fontify-block))))
1987 (let ((pos (point-marker))
1989 (if (eq org-table-use-standard-references t
)
1990 (concat (org-number-to-letters (org-table-current-column))
1991 (int-to-string (org-table-current-dline)))
1992 (concat "@" (int-to-string (org-table-current-dline))
1993 "$" (int-to-string (org-table-current-column)))))
1994 (field (org-table-get-field))
1995 (cw (current-window-configuration))
1998 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1999 (when (and (local-variable-p 'org-field-marker
)
2000 (markerp org-field-marker
))
2001 (move-marker org-field-marker nil
))
2003 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2004 (let ((org-inhibit-startup t
)) (org-mode))
2006 (setq truncate-lines nil
)
2008 (goto-char (setq p
(point-max)))
2009 (insert (org-trim field
))
2010 (remove-text-properties p
(point-max)
2011 '(invisible t org-cwidth t display t
2014 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
2015 (org-set-local 'org-window-configuration cw
)
2016 (org-set-local 'org-field-marker pos
)
2017 (message "Edit and finish with C-c C-c")))))
2019 (defun org-table-finish-edit-field ()
2020 "Finish editing a table data field.
2021 Remove all newline characters, insert the result into the table, realign
2022 the table and kill the editing buffer."
2023 (let ((pos org-field-marker
)
2024 (cw org-window-configuration
)
2025 (cb (current-buffer))
2027 (goto-char (point-min))
2028 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2029 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2030 (replace-match " "))
2031 (setq text
(org-trim (buffer-string)))
2032 (set-window-configuration cw
)
2034 (select-window (get-buffer-window (marker-buffer pos
)))
2036 (move-marker pos nil
)
2037 (org-table-check-inside-data-field)
2038 (org-table-get-field nil text
)
2040 (message "New field value inserted")))
2042 (define-minor-mode org-table-follow-field-mode
2043 "Minor mode to make the table field editor window follow the cursor.
2044 When this mode is active, the field editor window will always show the
2045 current field. The mode exits automatically when the cursor leaves the
2046 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2047 nil
" TblFollow" nil
2048 (if org-table-follow-field-mode
2049 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2051 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2052 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2053 (win (and buf
(get-buffer-window buf
))))
2054 (when win
(delete-window win
))
2056 (with-current-buffer buf
2057 (move-marker org-field-marker nil
))
2058 (kill-buffer buf
)))))
2060 (defun org-table-follow-fields-with-editor ()
2061 (if (and org-table-exit-follow-field-mode-when-leaving-table
2062 (not (org-at-table-p)))
2063 ;; We have left the table, exit the follow mode
2064 (org-table-follow-field-mode -
1)
2065 (when (org-table-check-inside-data-field 'noerror
)
2066 (let ((win (selected-window)))
2067 (org-table-edit-field nil
)
2068 (org-fit-window-to-buffer)
2069 (select-window win
)))))
2071 (defvar org-timecnt
) ; dynamically scoped parameter
2074 (defun org-table-sum (&optional beg end nlast
)
2075 "Sum numbers in region of current table column.
2076 The result will be displayed in the echo area, and will be available
2077 as kill to be inserted with \\[yank].
2079 If there is an active region, it is interpreted as a rectangle and all
2080 numbers in that rectangle will be summed. If there is no active
2081 region and point is located in a table column, sum all numbers in that
2084 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2085 numbers are assumed to be times as well (in decimal hours) and the
2086 numbers are added as such.
2088 If NLAST is a number, only the NLAST fields will actually be summed."
2091 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2093 ((and beg end
)) ; beg and end given explicitly
2094 ((org-region-active-p)
2095 (setq beg
(region-beginning) end
(region-end)))
2097 (setq col
(org-table-current-column))
2098 (goto-char (org-table-begin))
2099 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2100 (user-error "No table data"))
2101 (org-table-goto-column col
)
2103 (goto-char (org-table-end))
2104 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2105 (user-error "No table data"))
2106 (org-table-goto-column col
)
2107 (setq end
(point))))
2108 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2109 (items1 (cond ((not nlast
) items
)
2110 ((>= nlast
(length items
)) items
)
2111 (t (setq items
(reverse items
))
2112 (setcdr (nthcdr (1- nlast
) items
) nil
)
2114 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2116 (res (apply '+ numbers
))
2117 (sres (if (= org-timecnt
0)
2118 (number-to-string res
)
2119 (setq diff
(* 3600 res
)
2120 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2121 m
(floor (/ diff
60)) diff
(mod diff
60)
2123 (format "%.0f:%02.0f:%02.0f" h m s
))))
2125 (if (org-called-interactively-p 'interactive
)
2127 (substitute-command-keys
2128 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2129 (length numbers
) sres
))))
2132 (defun org-table-get-number-for-summing (s)
2134 (if (string-match "^ *|? *" s
)
2135 (setq s
(replace-match "" nil nil s
)))
2136 (if (string-match " *|? *$" s
)
2137 (setq s
(replace-match "" nil nil s
)))
2138 (setq n
(string-to-number s
))
2140 ((and (string-match "0" s
)
2141 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2142 ((string-match "\\`[ \t]+\\'" s
) nil
)
2143 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2144 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2145 (m (string-to-number (or (match-string 2 s
) "0")))
2146 (s (string-to-number (or (match-string 4 s
) "0"))))
2147 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2148 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2152 (defun org-table-current-field-formula (&optional key noerror
)
2153 "Return the formula active for the current field.
2154 Assumes that specials are in place.
2155 If KEY is given, return the key to this formula.
2156 Otherwise return the formula preceded with \"=\" or \":=\"."
2157 (let* ((name (car (rassoc (list (org-current-line)
2158 (org-table-current-column))
2159 org-table-named-field-locations
)))
2160 (col (org-table-current-column))
2161 (scol (int-to-string col
))
2162 (ref (format "@%d$%d" (org-table-current-dline) col
))
2163 (stored-list (org-table-get-stored-formulas noerror
))
2164 (ass (or (assoc name stored-list
)
2165 (assoc ref stored-list
)
2166 (assoc scol stored-list
))))
2169 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2172 (defun org-table-get-formula (&optional equation named
)
2173 "Read a formula from the minibuffer, offer stored formula as default.
2174 When NAMED is non-nil, look for a named equation."
2175 (let* ((stored-list (org-table-get-stored-formulas))
2176 (name (car (rassoc (list (org-current-line)
2177 (org-table-current-column))
2178 org-table-named-field-locations
)))
2179 (ref (format "@%d$%d" (org-table-current-dline)
2180 (org-table-current-column)))
2181 (refass (assoc ref stored-list
))
2182 (nameass (assoc name stored-list
))
2184 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2187 (int-to-string (org-table-current-column))))
2188 (dummy (and (or nameass refass
) (not named
)
2189 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2190 (message "Formula not replaced")))
2191 (name (or name ref
))
2192 (org-table-may-need-update nil
)
2193 (stored (cdr (assoc scol stored-list
)))
2195 ((and stored equation
(string-match "^ *=? *$" equation
))
2199 (t (org-table-formula-from-user
2201 (org-table-formula-to-user
2202 (format "%s formula %s%s="
2203 (if named
"Field" "Column")
2204 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2206 (if stored
(org-table-formula-to-user stored
) "")
2207 'org-table-formula-history
2210 (when (not (string-match "\\S-" eq
))
2212 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2213 (org-table-store-formulas stored-list
)
2214 (user-error "Formula removed"))
2215 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2216 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2217 (if (and name
(not named
))
2218 ;; We set the column equation, delete the named one.
2219 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2222 (setcdr (assoc scol stored-list
) eq
)
2223 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2224 (if (or mustsave
(not (equal stored eq
)))
2225 (org-table-store-formulas stored-list
))
2228 (defun org-table-store-formulas (alist)
2229 "Store the list of formulas below the current table."
2230 (setq alist
(sort alist
'org-table-formula-less-p
))
2231 (let ((case-fold-search t
))
2233 (goto-char (org-table-end))
2234 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2236 ;; don't overwrite TBLFM, we might use text properties to store stuff
2237 (goto-char (match-beginning 3))
2238 (delete-region (match-beginning 3) (match-end 0)))
2240 (insert (or (match-string 2) "#+TBLFM:")))
2242 (mapconcat (lambda (x)
2244 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2245 (car x
) "=" (cdr x
)))
2249 (defsubst org-table-formula-make-cmp-string
(a)
2250 (when (string-match "\\`$[<>]" a
)
2251 (let ((arrow (string-to-char (substring a
1))))
2252 ;; Fake a high number to make sure this is sorted at the end.
2253 (setq a
(org-table-formula-handle-first/last-rc a
))
2254 (setq a
(format "$%d" (+ 10000
2255 (if (= arrow ?
<) -
1000 0)
2256 (string-to-number (substring a
1)))))))
2258 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2262 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2264 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2266 (concat "@@" (match-string 5 a
))))))
2268 (defun org-table-formula-less-p (a b
)
2269 "Compare two formulas for sorting."
2270 (let ((as (org-table-formula-make-cmp-string (car a
)))
2271 (bs (org-table-formula-make-cmp-string (car b
))))
2272 (and as bs
(string< as bs
))))
2275 (defun org-table-get-stored-formulas (&optional noerror
)
2276 "Return an alist with the stored formulas directly after current table."
2277 (interactive) ;; FIXME interactive?
2278 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2280 (goto-char (org-table-end))
2281 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2282 (setq strings
(org-split-string (org-match-string-no-properties 2)
2284 (while (setq string
(pop strings
))
2285 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2286 (setq scol
(if (match-end 2)
2287 (match-string 2 string
)
2288 (match-string 1 string
))
2289 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2290 (concat "$" scol
) scol
)
2291 eq
(match-string 3 string
)
2292 eq-alist
(cons (cons scol eq
) eq-alist
))
2293 (if (member scol seen
)
2296 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2299 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2300 (push scol seen
))))))
2301 (nreverse eq-alist
)))
2303 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2304 "Modify the equations after the table structure has been edited.
2305 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2306 For all numbers larger than LIMIT, shift them by DELTA."
2308 (goto-char (org-table-end))
2309 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2310 (let ((msg "The formulas in #+TBLFM have been updated")
2311 (re (concat key
"\\([0-9]+\\)"))
2314 (if (or (equal key
"$") (equal key
"$LR"))
2315 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2316 (regexp-quote key
) remove
)
2317 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2320 (while (re-search-forward re2
(point-at-eol) t
)
2321 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2322 (if (equal (char-before (match-beginning 0)) ?.
)
2324 "Change makes TBLFM term %s invalid, use undo to recover"
2326 (replace-match "")))))
2327 (while (re-search-forward re
(point-at-eol) t
)
2328 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2329 (setq s
(match-string 1) n
(string-to-number s
))
2331 ((setq a
(assoc s replace
))
2332 (replace-match (concat key
(cdr a
)) t t
)
2334 ((and limit
(> n limit
))
2335 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2339 (defun org-table-get-specials ()
2340 "Get the column names and local parameters for this table."
2342 (let ((beg (org-table-begin)) (end (org-table-end))
2343 names name fields fields1 field cnt
2344 c v l line col types dlines hlines last-dline
)
2345 (setq org-table-column-names nil
2346 org-table-local-parameters nil
2347 org-table-named-field-locations nil
2348 org-table-current-begin-line nil
2349 org-table-current-begin-pos nil
2350 org-table-current-line-types nil
2351 org-table-current-ncol
0)
2353 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2354 (setq names
(org-split-string (match-string 1) " *| *")
2356 (while (setq name
(pop names
))
2358 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2359 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2360 (setq org-table-column-names
(nreverse org-table-column-names
))
2361 (setq org-table-column-name-regexp
2362 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2364 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2365 (setq fields
(org-split-string (match-string 1) " *| *"))
2366 (while (setq field
(pop fields
))
2367 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2368 (push (cons (match-string 1 field
) (match-string 2 field
))
2369 org-table-local-parameters
))))
2371 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2372 (setq c
(match-string 1)
2373 fields
(org-split-string (match-string 2) " *| *"))
2375 (beginning-of-line (if (equal c
"_") 2 0))
2376 (setq line
(org-current-line) col
1)
2377 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2378 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2379 (while (and fields1
(setq field
(pop fields
)))
2380 (setq v
(pop fields1
) col
(1+ col
))
2381 (when (and (stringp field
) (stringp v
)
2382 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2383 (push (cons field v
) org-table-local-parameters
)
2384 (push (list field line col
) org-table-named-field-locations
))))
2385 ;; Analyse the line types
2387 (setq org-table-current-begin-line
(org-current-line)
2388 org-table-current-begin-pos
(point)
2389 l org-table-current-begin-line
)
2390 (while (looking-at "[ \t]*|\\(-\\)?")
2391 (push (if (match-end 1) 'hline
'dline
) types
)
2392 (if (match-end 1) (push l hlines
) (push l dlines
))
2393 (beginning-of-line 2)
2395 (push 'hline types
) ;; add an imaginary extra hline to the end
2396 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2397 last-dline
(car dlines
)
2398 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2399 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2400 (org-goto-line last-dline
)
2401 (let* ((l last-dline
)
2402 (fields (org-split-string
2403 (buffer-substring (point-at-bol) (point-at-eol))
2405 (nfields (length fields
))
2407 (setq org-table-current-ncol nfields
)
2408 (loop for i from
1 to nfields do
2409 (push (list (format "LR%d" i
) l i
) al
)
2410 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2411 (setq org-table-named-field-locations
2412 (append org-table-named-field-locations al
))
2413 (setq org-table-local-parameters
2414 (append org-table-local-parameters al2
))))))
2417 (defun org-table-maybe-eval-formula ()
2418 "Check if the current field starts with \"=\" or \":=\".
2419 If yes, store the formula and apply it."
2420 ;; We already know we are in a table. Get field will only return a formula
2421 ;; when appropriate. It might return a separator line, but no problem.
2422 (when org-table-formula-evaluate-inline
2423 (let* ((field (org-trim (or (org-table-get-field) "")))
2425 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2426 (setq named
(equal (string-to-char field
) ?
:)
2427 eq
(match-string 1 field
))
2428 (if (or (fboundp 'calc-eval
)
2429 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2430 (org-table-eval-formula (if named
'(4) nil
)
2431 (org-table-formula-from-user eq
))
2432 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2434 (defvar org-recalc-commands nil
2435 "List of commands triggering the recalculation of a line.
2436 Will be filled automatically during use.")
2438 (defvar org-recalc-marks
2439 '((" " .
"Unmarked: no special line, no automatic recalculation")
2440 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2441 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2442 ("!" .
"Column name definition line. Reference in formula as $name.")
2443 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2444 ("_" .
"Names for values in row below this one.")
2445 ("^" .
"Names for values in row above this one.")))
2448 (defun org-table-rotate-recalc-marks (&optional newchar
)
2449 "Rotate the recalculation mark in the first column.
2450 If in any row, the first field is not consistent with a mark,
2451 insert a new column for the markers.
2452 When there is an active region, change all the lines in the region,
2453 after prompting for the marking character.
2454 After each change, a message will be displayed indicating the meaning
2457 (unless (org-at-table-p) (user-error "Not at a table"))
2458 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2459 (beg (org-table-begin))
2460 (end (org-table-end))
2461 (l (org-current-line))
2462 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2463 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2467 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2468 (col (org-table-current-column))
2469 (forcenew (car (assoc newchar org-recalc-marks
)))
2472 (message "Change region to what mark? Type # * ! $ or SPC: ")
2473 (setq newchar
(char-to-string (read-char-exclusive))
2474 forcenew
(car (assoc newchar org-recalc-marks
))))
2475 (if (and newchar
(not forcenew
))
2476 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2478 (if l1
(org-goto-line l1
))
2480 (beginning-of-line 1)
2481 (unless (looking-at org-table-dataline-regexp
)
2482 (user-error "Not at a table data line")))
2484 (org-table-goto-column 1)
2485 (org-table-insert-column)
2486 (org-table-goto-column (1+ col
)))
2487 (setq epos
(point-at-eol))
2489 (beginning-of-line 1)
2490 (org-table-get-field
2491 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2493 (setq new
(or forcenew
2494 (cadr (member (match-string 1) marks
))))
2500 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2501 (and (looking-at org-table-dataline-regexp
)
2502 (org-table-get-field 1 (concat " " new
" "))))
2503 (org-goto-line l1
)))
2504 (if (not (= epos
(point-at-eol))) (org-table-align))
2506 (and (org-called-interactively-p 'interactive
)
2507 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2510 (defun org-table-maybe-recalculate-line ()
2511 "Recompute the current line if marked for it, and if we haven't just done it."
2513 (and org-table-allow-automatic-line-recalculation
2514 (not (and (memq last-command org-recalc-commands
)
2515 (equal org-last-recalc-line
(org-current-line))))
2516 (save-excursion (beginning-of-line 1)
2517 (looking-at org-table-auto-recalculate-regexp
))
2518 (org-table-recalculate) t
))
2520 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2521 (defsubst org-set-calc-mode
(var &optional value
)
2523 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2524 ("R" calc-angle-mode rad
)
2525 ("F" calc-prefer-frac t
)
2526 ("S" calc-symbolic-mode t
)))
2527 value
(nth 2 var
) var
(nth 1 var
)))
2528 (if (memq var org-tbl-calc-modes
)
2529 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2530 (cons var
(cons value org-tbl-calc-modes
)))
2534 (defun org-table-eval-formula (&optional arg equation
2535 suppress-align suppress-const
2536 suppress-store suppress-analysis
)
2537 "Replace the table field value at the cursor by the result of a calculation.
2539 This function makes use of Dave Gillespie's Calc package, in my view the
2540 most exciting program ever written for GNU Emacs. So you need to have Calc
2541 installed in order to use this function.
2543 In a table, this command replaces the value in the current field with the
2544 result of a formula. It also installs the formula as the \"current\" column
2545 formula, by storing it in a special line below the table. When called
2546 with a `C-u' prefix, the current field must be a named field, and the
2547 formula is installed as valid in only this specific field.
2549 When called with two `C-u' prefixes, insert the active equation
2550 for the field back into the current field, so that it can be
2551 edited there. This is useful in order to use \\[org-table-show-reference]
2552 to check the referenced fields.
2554 When called, the command first prompts for a formula, which is read in
2555 the minibuffer. Previously entered formulas are available through the
2556 history list, and the last used formula is offered as a default.
2557 These stored formulas are adapted correctly when moving, inserting, or
2558 deleting columns with the corresponding commands.
2560 The formula can be any algebraic expression understood by the Calc package.
2561 For details, see the Org-mode manual.
2563 This function can also be called from Lisp programs and offers
2564 additional arguments: EQUATION can be the formula to apply. If this
2565 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2566 used to speed-up recursive calls by by-passing unnecessary aligns.
2567 SUPPRESS-CONST suppresses the interpretation of constants in the
2568 formula, assuming that this has been done already outside the function.
2569 SUPPRESS-STORE means the formula should not be stored, either because
2570 it is already stored, or because it is a modified equation that should
2571 not overwrite the stored one."
2573 (org-table-check-inside-data-field)
2574 (or suppress-analysis
(org-table-get-specials))
2575 (if (equal arg
'(16))
2576 (let ((eq (org-table-current-field-formula)))
2577 (or eq
(user-error "No equation active for current field"))
2578 (org-table-get-field nil eq
)
2580 (setq org-table-may-need-update t
))
2582 (ndown (if (integerp arg
) arg
1))
2583 (org-table-automatic-realign nil
)
2584 (case-fold-search nil
)
2586 (formula (if (and equation suppress-store
)
2588 (org-table-get-formula equation
(equal arg
'(4)))))
2589 (n0 (org-table-current-column))
2590 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2591 (numbers nil
) ; was a variable, now fixed default
2593 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2594 duration duration-output-format
)
2595 ;; Parse the format string. Since we have a lot of modes, this is
2596 ;; a lot of work. However, I think calc still uses most of the time.
2597 (if (string-match ";" formula
)
2598 (let ((tmp (org-split-string formula
";")))
2599 (setq formula
(car tmp
)
2600 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2602 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2603 (setq c
(string-to-char (match-string 1 fmt
))
2604 n
(string-to-number (match-string 2 fmt
)))
2606 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2607 (setq org-tbl-calc-modes
2610 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2611 (?s . sci
) (?e . eng
))))
2613 (setq fmt
(replace-match "" t t fmt
)))
2614 (if (string-match "T" fmt
)
2615 (setq duration t numbers t
2616 duration-output-format nil
2617 fmt
(replace-match "" t t fmt
)))
2618 (if (string-match "t" fmt
)
2620 duration-output-format org-table-duration-custom-format
2622 fmt
(replace-match "" t t fmt
)))
2623 (if (string-match "N" fmt
)
2625 fmt
(replace-match "" t t fmt
)))
2626 (if (string-match "L" fmt
)
2628 fmt
(replace-match "" t t fmt
)))
2629 (if (string-match "E" fmt
)
2631 fmt
(replace-match "" t t fmt
)))
2632 (while (string-match "[DRFS]" fmt
)
2633 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2634 (setq fmt
(replace-match "" t t fmt
)))
2635 (unless (string-match "\\S-" fmt
)
2637 (if (and (not suppress-const
) org-table-formula-use-constants
)
2638 (setq formula
(org-table-formula-substitute-names formula
)))
2639 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2641 (setq fields
(org-split-string
2642 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2644 ;; replace fields with duration values if relevant
2647 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2650 (setq fields
(mapcar
2652 (if (string-match "\\S-" x
)
2653 (number-to-string (string-to-number x
))
2656 (setq ndown
(1- ndown
))
2657 (setq form
(copy-sequence formula
)
2658 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2659 (if (and lispp literal
) (setq lispp
'literal
))
2661 ;; Insert row and column number of formula result field
2662 (while (string-match "[@$]#" form
)
2667 (if (equal (substring form
(match-beginning 0)
2668 (1+ (match-beginning 0)))
2670 (org-table-current-dline)
2671 (org-table-current-column))))
2674 ;; Check for old vertical references
2675 (setq form
(org-table-rewrite-old-row-references form
))
2676 ;; Insert remote references
2677 (setq form
(org-table-remote-reference-indirection form
))
2678 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2682 (org-table-make-reference
2683 (let ((rmtrng (org-table-get-remote-range
2684 (match-string 1 form
) (match-string 2 form
))))
2687 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2688 (org-table-time-string-to-seconds rmtrng
))
2690 keep-empty numbers lispp
))
2692 ;; Insert complex ranges
2693 (while (and (string-match org-table-range-regexp form
)
2694 (> (length (match-string 0 form
)) 1))
2695 (setq formrg
(save-match-data
2696 (org-table-get-range (match-string 0 form
) nil n0
)))
2699 (org-table-make-reference
2700 ;; possibly handle durations
2703 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2704 (org-table-time-string-to-seconds formrg
))
2706 keep-empty numbers lispp
)))
2707 (if (not (save-match-data
2708 (string-match (regexp-quote form
) formrpl
)))
2709 (setq form
(replace-match formrpl t t form
))
2710 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2711 ;; Insert simple ranges
2712 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2716 (org-table-make-reference
2718 fields
(string-to-number (match-string 1 form
))
2719 (string-to-number (match-string 2 form
)))
2720 keep-empty numbers lispp
))
2723 ;; Insert the references to fields in same row
2724 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2725 (setq n
(+ (string-to-number (match-string 1 form
))
2726 (if (match-end 2) n0
0))
2727 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2728 formrpl
(save-match-data
2729 (org-table-make-reference
2730 x keep-empty numbers lispp
)))
2733 (string-match (regexp-quote formula
) formrpl
)))
2734 (user-error "Invalid field specifier \"%s\""
2735 (match-string 0 form
)))
2736 (setq form
(replace-match formrpl t t form
)))
2739 (setq ev
(condition-case nil
2740 (eval (eval (read form
)))
2742 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2743 ev
(if duration
(org-table-time-seconds-to-string
2744 (string-to-number ev
)
2745 duration-output-format
) ev
))
2746 (or (fboundp 'calc-eval
)
2747 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2748 ;; Use <...> time-stamps so that Calc can handle them
2749 (while (string-match (concat "\\[" org-ts-regexp1
"\\]") form
)
2750 (setq form
(replace-match "<\\1>" nil nil form
)))
2751 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2752 (when (string-match org-ts-regexp2 form
)
2753 (let* ((ts (match-string 0 form
))
2754 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2755 (system-time-locale "C")
2756 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2757 (cdr org-time-stamp-formats
))
2758 (car org-time-stamp-formats
))))
2759 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2761 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2763 (calc-eval (cons form org-tbl-calc-modes
)
2764 (when (and (not keep-empty
) numbers
) 'num
)))
2765 ev
(if duration
(org-table-time-seconds-to-string
2766 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2767 (string-to-number (org-table-time-string-to-seconds ev
))
2768 (string-to-number ev
))
2769 duration-output-format
)
2772 (when org-table-formula-debug
2773 (with-output-to-temp-buffer "*Substitution History*"
2774 (princ (format "Substitution history of formula
2778 $1-> %s\n" orig formula form0 form
))
2780 (princ (format " %s^\nError: %s"
2781 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2782 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2784 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2785 (setq bw
(get-buffer-window "*Substitution History*"))
2786 (org-fit-window-to-buffer bw
)
2787 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2788 (unless (let (inhibit-redisplay)
2789 (y-or-n-p "Debugging Formula. Continue to next? "))
2791 (user-error "Abort"))
2794 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2795 (org-table-justify-field-maybe
2796 (format org-table-formula-field-format
2797 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2798 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2799 (call-interactively 'org-return
)
2801 (and down
(org-table-maybe-recalculate-line))
2802 (or suppress-align
(and org-table-may-need-update
2803 (org-table-align))))))
2805 (defun org-table-put-field-property (prop value
)
2807 (put-text-property (progn (skip-chars-backward "^|") (point))
2808 (progn (skip-chars-forward "^|") (point))
2811 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2812 "Get a calc vector from a column, according to descriptor DESC.
2813 Optional arguments TBEG and COL can give the beginning of the table and
2814 the current column, to avoid unnecessary parsing.
2816 HIGHLIGHT means just highlight the range.
2818 When CORNERS-ONLY is set, only return the corners of the range as
2819 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2820 in the buffer and column1 and column2 are table column numbers."
2821 (if (not (equal (string-to-char desc
) ?
@))
2822 (setq desc
(concat "@" desc
)))
2824 (or tbeg
(setq tbeg
(org-table-begin)))
2825 (or col
(setq col
(org-table-current-column)))
2826 (let ((thisline (org-current-line))
2827 beg end c1 c2 r1 r2 rangep tmp
)
2828 (unless (string-match org-table-range-regexp desc
)
2829 (user-error "Invalid table range specifier `%s'" desc
))
2830 (setq rangep
(match-end 3)
2831 r1
(and (match-end 1) (match-string 1 desc
))
2832 r2
(and (match-end 4) (match-string 4 desc
))
2833 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2834 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2836 (and c1
(setq c1
(+ (string-to-number c1
)
2837 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2838 (and c2
(setq c2
(+ (string-to-number c2
)
2839 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2840 (if (equal r1
"") (setq r1 nil
))
2841 (if (equal r2
"") (setq r2 nil
))
2842 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2843 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2844 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2845 (if (not r1
) (setq r1 thisline
))
2846 (if (not r2
) (setq r2 thisline
))
2847 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2848 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2849 (if (and (not corners-only
)
2850 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2854 (while (not (looking-at org-table-dataline-regexp
))
2855 (beginning-of-line 2))
2856 (prog1 (org-trim (org-table-get-field c1
))
2857 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2858 ;; A range, return a vector
2859 ;; First sort the numbers to get a regular rectangle
2860 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2861 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2863 ;; Only return the corners of the range
2865 ;; Copy the range values into a list
2867 (while (not (looking-at org-table-dataline-regexp
))
2868 (beginning-of-line 2))
2869 (org-table-goto-column c1
)
2872 (while (not (looking-at org-table-dataline-regexp
))
2873 (beginning-of-line 0))
2874 (org-table-goto-column c2
)
2877 (org-table-highlight-rectangle
2878 beg
(progn (skip-chars-forward "^|\n") (point))))
2879 ;; return string representation of calc vector
2881 (apply 'append
(org-table-copy-region beg end
))))))))
2883 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2884 "Analyze descriptor DESC and retrieve the corresponding line number.
2885 The cursor is currently in line CLINE, the table begins in line BLINE,
2886 and TABLE is a vector with line types."
2887 (if (string-match "^[0-9]+$" desc
)
2888 (aref org-table-dlines
(string-to-number desc
))
2889 (setq cline
(or cline
(org-current-line))
2890 bline
(or bline org-table-current-begin-line
)
2891 table
(or table org-table-current-line-types
))
2893 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2895 (and (not (match-end 3)) (not (match-end 6)))
2896 (and (match-end 3) (match-end 6) (not (match-end 5))))
2897 (user-error "Invalid row descriptor `%s'" desc
))
2898 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2899 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2900 (odir (and (match-end 5) (match-string 5 desc
)))
2901 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2903 (rel (and (match-end 6)
2904 (or (and (match-end 1) (not (match-end 3)))
2906 (if (and hn
(not hdir
))
2909 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2910 (if (and (not hn
) on
(not odir
))
2911 (user-error "Should never happen");;(aref org-table-dlines on)
2912 (if (and hn
(> hn
0))
2913 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2914 nil hn cline desc
)))
2916 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2917 rel on cline desc
)))
2920 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2921 "FIXME: Needs more documentation."
2922 (let ((l (length table
)))
2924 (while (and (setq i
(+ i
(if backwards -
1 1)))
2926 (not (eq (aref table i
) type
))
2927 (if (and relative
(eq (aref table i
) 'hline
))
2929 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2930 ((eq org-table-relative-ref-may-cross-hline
'error
)
2931 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2932 (t (setq i
(- i
(if backwards -
1 1))
2937 (if (or (< i
0) (>= i l
))
2938 (user-error "Row descriptor %s used in line %d leads outside table"
2942 (defun org-table-rewrite-old-row-references (s)
2943 (if (string-match "&[-+0-9I]" s
)
2944 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2947 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2948 "Convert list ELEMENTS to something appropriate to insert into formula.
2949 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2950 NUMBERS indicates that everything should be converted to numbers.
2951 LISPP non-nil means to return something appropriate for a Lisp
2952 list, 'literal is for the format specifier L."
2953 ;; Calc nan (not a number) is used for the conversion of the empty
2954 ;; field to a reference for several reasons: (i) It is accepted in a
2955 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2956 ;; (ii) In a single field (not in range) it can be distinguished
2957 ;; from "(nan)" which is the reference made from a single field
2958 ;; containing "nan".
2959 (if (stringp elements
)
2962 (if (eq lispp
'literal
)
2964 (if (and (eq elements
"") (not keep-empty
))
2967 (if numbers
(string-to-number elements
) elements
))))
2968 (if (string-match "\\S-" elements
)
2970 (when numbers
(setq elements
(number-to-string
2971 (string-to-number elements
))))
2972 (concat "(" elements
")"))
2973 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2978 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2980 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
2984 (if (eq lispp
'literal
)
2986 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2988 (concat "[" (mapconcat
2990 (if (string-match "\\S-" x
)
2992 (number-to-string (string-to-number x
))
2994 (if (or (not keep-empty
) numbers
) "0" "nan")))
2999 (defun org-table-set-constants ()
3000 "Set `org-table-formula-constants-local' in the current buffer."
3001 (let (cst consts const-str
)
3003 (goto-char (point-min))
3004 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
3005 (setq const-str
(substring-no-properties (match-string 1)))
3006 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
3009 (while (setq e
(pop consts
))
3010 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
3011 (if (assoc-string (match-string 1 e
) cst
)
3012 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
3013 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
3014 (setq org-table-formula-constants-local cst
)))))))
3017 (defun org-table-recalculate (&optional all noalign
)
3018 "Recalculate the current table line by applying all stored formulas.
3019 With prefix arg ALL, do this for all lines in the table.
3020 With the prefix argument ALL is `(16)' \
3021 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3022 it is the symbol `iterate', recompute the table until it no longer changes.
3023 If NOALIGN is not nil, do not re-align the table after the computations
3024 are done. This is typically used internally to save time, if it is
3025 known that the table will be realigned a little later anyway."
3027 (or (memq this-command org-recalc-commands
)
3028 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
3029 (unless (org-at-table-p) (user-error "Not at a table"))
3030 (if (or (eq all
'iterate
) (equal all
'(16)))
3032 (org-table-get-specials)
3033 (let* ((eqlist (sort (org-table-get-stored-formulas)
3034 (lambda (a b
) (string< (car a
) (car b
)))))
3035 (eqlist1 (copy-sequence eqlist
))
3036 (inhibit-redisplay (not debug-on-error
))
3037 (line-re org-table-dataline-regexp
)
3038 (thisline (org-current-line))
3039 (thiscol (org-table-current-column))
3041 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3042 ;; Insert constants in all formulas
3045 (if (string-match "^@-?I+" (car x
))
3046 (user-error "Can't assign to hline relative reference"))
3047 (when (string-match "\\`$[<>]" (car x
))
3049 (setq x
(cons (substring
3050 (org-table-formula-handle-first/last-rc
3053 (if (assoc (car x
) eqlist1
)
3054 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3057 (org-table-formula-handle-first/last-rc
(car x
))
3058 (org-table-formula-substitute-names
3059 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3061 ;; Split the equation list
3062 (while (setq eq
(pop eqlist
))
3063 (if (<= (string-to-char (car eq
)) ?
9)
3066 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3067 ;; Expand ranges in lhs of formulas
3068 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3070 ;; Get the correct line range to process
3073 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3074 (goto-char (setq beg
(org-table-begin)))
3075 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3076 ;; This is a table with marked lines, compute selected lines
3077 (setq line-re org-table-recalculate-regexp
)
3078 ;; Move forward to the first non-header line
3079 (if (and (re-search-forward org-table-dataline-regexp end t
)
3080 (re-search-forward org-table-hline-regexp end t
)
3081 (re-search-forward org-table-dataline-regexp end t
))
3082 (setq beg
(match-beginning 0))
3083 nil
))) ;; just leave beg where it is
3084 (setq beg
(point-at-bol)
3085 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3087 (and all
(message "Re-applying formulas to full table..."))
3089 ;; First find the named fields, and mark them untouchable.
3090 ;; Also check if several field/range formulas try to set the same field.
3091 (remove-text-properties beg end
'(org-untouchable t
))
3092 (while (setq eq
(pop eqlname
))
3094 a
(assoc name org-table-named-field-locations
))
3096 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3098 (when (member name1 seen-fields
)
3099 (user-error "Several field/range formulas try to set %s" name1
))
3100 (push name1 seen-fields
)
3103 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3106 (aref org-table-dlines
3107 (string-to-number (match-string 1 name
)))
3108 (error (user-error "Invalid row number in %s"
3110 (string-to-number (match-string 2 name
)))))
3111 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3112 (message "Re-applying formula to field: %s" name
)
3113 (org-goto-line (nth 1 a
))
3114 (org-table-goto-column (nth 2 a
))
3115 (push (append a
(list (cdr eq
))) eqlname1
)
3116 (org-table-put-field-property :org-untouchable t
)))
3117 (setq eqlname1
(nreverse eqlname1
))
3119 ;; Now evaluate the column formulas, but skip fields covered by
3122 (while (re-search-forward line-re end t
)
3123 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3124 ;; Unprotected line, recalculate
3125 (and all
(message "Re-applying formulas to full table...(line %d)"
3126 (setq cnt
(1+ cnt
))))
3127 (setq org-last-recalc-line
(org-current-line))
3129 (while (setq entry
(pop eql
))
3130 (org-goto-line org-last-recalc-line
)
3131 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3132 (unless (get-text-property (point) :org-untouchable
)
3133 (org-table-eval-formula nil
(cdr entry
)
3134 'noalign
'nocst
'nostore
'noanalysis
)))))
3136 ;; Now evaluate the field formulas
3137 (while (setq eq
(pop eqlname1
))
3138 (message "Re-applying formula to field: %s" (car eq
))
3139 (org-goto-line (nth 1 eq
))
3140 (let ((column-target (nth 2 eq
)))
3141 (when (> column-target
1000)
3142 (user-error "Formula column target too large"))
3143 (let* ((column-count (progn (end-of-line)
3144 (1- (org-table-current-column))))
3146 (and (> column-target column-count
)
3147 (or (eq org-table-formula-create-columns t
)
3149 (eq org-table-formula-create-columns
'warn
)
3151 (org-display-warning "Out-of-bounds formula added columns")
3154 (eq org-table-formula-create-columns
'prompt
)
3155 (yes-or-no-p "Out-of-bounds formula. Add columns?"))))))
3156 (org-table-goto-column column-target nil create-new-column
))
3158 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3159 'nostore
'noanalysis
)))
3161 (org-goto-line thisline
)
3162 (org-table-goto-column thiscol
)
3163 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3164 (or noalign
(and org-table-may-need-update
(org-table-align))
3165 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3167 ;; back to initial position
3168 (message "Re-applying formulas...done")
3169 (org-goto-line thisline
)
3170 (org-table-goto-column thiscol
)
3171 (or noalign
(and org-table-may-need-update
(org-table-align))
3172 (and all
(message "Re-applying formulas...done"))))))
3175 (defun org-table-iterate (&optional arg
)
3176 "Recalculate the table until it does not change anymore.
3177 The maximum number of iterations is 10, but you can choose a different value
3178 with the prefix ARG."
3180 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3182 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3187 (org-table-recalculate 'all
)
3188 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3189 (if (not (string= lasttbl thistbl
))
3190 (setq lasttbl thistbl
)
3192 (message "Convergence after %d iterations" i
)
3193 (message "Table was already stable"))
3195 (user-error "No convergence after %d iterations" i
))))
3198 (defun org-table-recalculate-buffer-tables ()
3199 "Recalculate all tables in the current buffer."
3204 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3207 (defun org-table-iterate-buffer-tables ()
3208 "Iterate all tables in the buffer, to converge inter-table dependencies."
3212 (checksum (md5 (buffer-string)))
3220 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3221 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3223 (message "Convergence after %d iterations" (- imax i
))
3225 (setq checksum c1
)))
3226 (user-error "No convergence after %d iterations" imax
))))))
3228 (defun org-table-calc-current-TBLFM (&optional arg
)
3229 "Apply the #+TBLFM in the line at point to the table."
3231 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3232 (let ((formula (buffer-substring
3237 ;; Insert a temporary formula at right after the table
3238 (goto-char (org-table-TBLFM-begin))
3239 (setq s
(set-marker (make-marker) (point)))
3240 (insert (concat formula
"\n"))
3241 (setq e
(set-marker (make-marker) (point)))
3242 ;; Recalculate the table
3243 (beginning-of-line 0) ; move to the inserted line
3244 (skip-chars-backward " \r\n\t")
3245 (if (org-at-table-p)
3247 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3248 ;; delete the formula inserted temporarily
3249 (delete-region s e
))))))
3251 (defun org-table-TBLFM-begin ()
3252 "Find the beginning of the TBLFM lines and return its position.
3253 Return nil when the beginning of TBLFM line was not found."
3255 (when (progn (forward-line 1)
3257 org-table-TBLFM-begin-regexp
3261 (defun org-table-expand-lhs-ranges (equations)
3262 "Expand list of formulas.
3263 If some of the RHS in the formulas are ranges or a row reference, expand
3264 them to individual field equations for each field."
3265 (let (e res lhs rhs range r1 r2 c1 c2
)
3266 (while (setq e
(pop equations
))
3267 (setq lhs
(car e
) rhs
(cdr e
))
3269 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3270 ;; This just refers to one fixed field
3272 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3273 ;; This just refers to one fixed named field
3275 ((string-match "^@[0-9]+$" lhs
)
3276 (loop for ic from
1 to org-table-current-ncol do
3277 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3278 (put-text-property 0 (length (caar res
))
3279 :orig-eqn e
(caar res
))))
3281 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3283 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3284 r2
(nth 2 range
) c2
(nth 3 range
))
3285 (setq r1
(org-table-line-to-dline r1
))
3286 (setq r2
(org-table-line-to-dline r2
'above
))
3287 (loop for ir from r1 to r2 do
3288 (loop for ic from c1 to c2 do
3289 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3290 (put-text-property 0 (length (caar res
))
3291 :orig-eqn e
(caar res
)))))))
3294 (defun org-table-formula-handle-first/last-rc
(s)
3295 "Replace @<, @>, $<, $> with first/last row/column of the table.
3296 So @< and $< will always be replaced with @1 and $1, respectively.
3297 The advantage of these special markers are that structure editing of
3298 the table will not change them, while @1 and $1 will be modified
3299 when a line/row is swapped out of that privileged position. So for
3300 formulas that use a range of rows or columns, it may often be better
3301 to anchor the formula with \"I\" row markers, or to offset from the
3302 borders of the table using the @< @> $< $> makers."
3303 (let (n nmax len char
(start 0))
3304 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3307 (setq start
(match-end 3))
3308 (setq nmax
(if (equal (match-string 1 s
) "@")
3309 (1- (length org-table-dlines
))
3310 org-table-current-ncol
)
3311 len
(- (match-end 2) (match-beginning 2))
3312 char
(string-to-char (match-string 2 s
))
3316 (if (or (< n
1) (> n nmax
))
3317 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3318 (match-string 0 s
) s
))
3319 (setq start
(match-beginning 0))
3320 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3323 (defun org-table-formula-substitute-names (f)
3324 "Replace $const with values in string F."
3325 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3326 ;; First, check for column names
3327 (while (setq start
(string-match org-table-column-name-regexp f start
))
3328 (setq start
(1+ start
))
3329 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3330 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3331 ;; Parameters and constants
3333 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3335 (setq start
(match-end 2))
3336 (setq start
(1+ start
))
3337 (if (setq a
(save-match-data
3338 (org-table-get-constant (match-string 1 f
))))
3339 (setq f
(replace-match
3340 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3341 (if org-table-formula-debug
3342 (put-text-property 0 (length f
) :orig-formula f1 f
))
3345 (defun org-table-get-constant (const)
3346 "Find the value for a parameter or constant in a formula.
3347 Parameters get priority."
3348 (or (cdr (assoc const org-table-local-parameters
))
3349 (cdr (assoc const org-table-formula-constants-local
))
3350 (cdr (assoc const org-table-formula-constants
))
3351 (and (fboundp 'constants-get
) (constants-get const
))
3352 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3353 (org-entry-get nil
(substring const
5) 'inherit
))
3356 (defvar org-table-fedit-map
3357 (let ((map (make-sparse-keymap)))
3358 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3359 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3360 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3361 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3362 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3363 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3364 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3365 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3366 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3367 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3368 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3369 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3370 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3371 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3372 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3373 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3374 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3375 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3376 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3377 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3380 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3382 ["Finish and Install" org-table-fedit-finish t
]
3383 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3384 ["Abort" org-table-fedit-abort t
]
3386 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3387 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3389 "Shift Reference at Point"
3390 ["Up" org-table-fedit-ref-up t
]
3391 ["Down" org-table-fedit-ref-down t
]
3392 ["Left" org-table-fedit-ref-left t
]
3393 ["Right" org-table-fedit-ref-right t
]
3395 "Change Test Row for Column Formulas"
3396 ["Up" org-table-fedit-line-up t
]
3397 ["Down" org-table-fedit-line-down t
]
3399 ["Scroll Table Window" org-table-fedit-scroll t
]
3400 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3401 ["Show Table Grid" org-table-fedit-toggle-coordinates
3402 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3403 org-table-overlay-coordinates
)]
3405 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3406 :style toggle
:selected org-table-buffer-is-an
]))
3411 (defun org-table-edit-formulas ()
3412 "Edit the formulas of the current table in a separate buffer."
3414 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3415 (beginning-of-line 0))
3416 (unless (org-at-table-p) (user-error "Not at a table"))
3417 (org-table-get-specials)
3418 (let ((key (org-table-current-field-formula 'key
'noerror
))
3419 (eql (sort (org-table-get-stored-formulas 'noerror
)
3420 'org-table-formula-less-p
))
3421 (pos (point-marker))
3423 (wc (current-window-configuration))
3424 (sel-win (selected-window))
3425 (titles '((column .
"# Column Formulas\n")
3426 (field .
"# Field and Range Formulas\n")
3427 (named .
"# Named Field Formulas\n")))
3429 (org-switch-to-buffer-other-window "*Edit Formulas*")
3431 ;; Keep global-font-lock-mode from turning on font-lock-mode
3432 (let ((font-lock-global-modes '(not fundamental-mode
)))
3434 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3435 (org-set-local 'org-pos pos
)
3436 (org-set-local 'org-window-configuration wc
)
3437 (org-set-local 'org-selected-window sel-win
)
3438 (use-local-map org-table-fedit-map
)
3439 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3440 (easy-menu-add org-table-fedit-menu
)
3441 (setq startline
(org-current-line))
3442 (while (setq entry
(pop eql
))
3444 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3445 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3446 ((string-match "^[0-9]" (car entry
)) 'column
)
3448 (when (setq title
(assq type titles
))
3449 (or (bobp) (insert "\n"))
3450 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3451 (setq titles
(remove title titles
)))
3452 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3453 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3454 (car entry
) " = " (cdr entry
) "\n"))
3455 (remove-text-properties 0 (length s
) '(face nil
) s
)
3457 (if (eq org-table-use-standard-references t
)
3458 (org-table-fedit-toggle-ref-type))
3459 (org-goto-line startline
)
3460 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3462 (defun org-table-fedit-post-command ()
3463 (when (not (memq this-command
'(lisp-complete-symbol)))
3464 (let ((win (selected-window)))
3467 (org-table-show-reference)
3469 (select-window win
)))))
3471 (defun org-table-formula-to-user (s)
3472 "Convert a formula from internal to user representation."
3473 (if (eq org-table-use-standard-references t
)
3474 (org-table-convert-refs-to-an s
)
3477 (defun org-table-formula-from-user (s)
3478 "Convert a formula from user to internal representation."
3479 (if org-table-use-standard-references
3480 (org-table-convert-refs-to-rc s
)
3483 (defun org-table-convert-refs-to-rc (s)
3484 "Convert spreadsheet references from A7 to @7$28.
3485 Works for single references, but also for entire formulas and even the
3488 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3491 ;; format match, just advance
3492 (setq start
(match-end 0)))
3493 ((and (> (match-beginning 0) 0)
3494 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3495 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3496 ;; 3.e5 or something like this.
3497 (setq start
(match-end 0)))
3498 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3499 ;; (member (match-string 1 s)
3500 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3502 ;; function name, just advance
3503 (setq start
(match-end 0)))
3505 (setq start
(match-beginning 0)
3507 (if (equal (match-string 2 s
) "&")
3508 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3510 (string-to-number (match-string 2 s
))
3511 (org-letters-to-number (match-string 1 s
))))
3515 (defun org-table-convert-refs-to-an (s)
3516 "Convert spreadsheet references from to @7$28 to AB7.
3517 Works for single references, but also for entire formulas and even the
3519 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3520 (setq s
(replace-match
3522 (org-number-to-letters
3523 (string-to-number (match-string 2 s
)))
3524 (string-to-number (match-string 1 s
)))
3526 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3527 (setq s
(replace-match (concat "\\1"
3528 (org-number-to-letters
3529 (string-to-number (match-string 2 s
))) "&")
3533 (defun org-letters-to-number (s)
3534 "Convert a base 26 number represented by letters into an integer.
3535 For example: AB -> 28."
3538 (while (> (length s
) 0)
3539 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3543 (defun org-number-to-letters (n)
3544 "Convert an integer into a base 26 number represented by letters.
3545 For example: 28 -> AB."
3548 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3552 (defun org-table-time-string-to-seconds (s)
3553 "Convert a time string into numerical duration in seconds.
3554 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3555 If S is a string representing a number, keep this number."
3558 (let (hour minus min sec res
)
3560 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3561 (setq minus
(< 0 (length (match-string 1 s
)))
3562 hour
(string-to-number (match-string 2 s
))
3563 min
(string-to-number (match-string 3 s
))
3564 sec
(string-to-number (match-string 4 s
)))
3566 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3567 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3568 ((and (not (string-match org-ts-regexp-both s
))
3569 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3570 (setq minus
(< 0 (length (match-string 1 s
)))
3571 hour
(string-to-number (match-string 2 s
))
3572 min
(string-to-number (match-string 3 s
)))
3574 (setq res
(- (+ (* hour
3600) (* min
60))))
3575 (setq res
(+ (* hour
3600) (* min
60)))))
3576 (t (setq res
(string-to-number s
))))
3577 (number-to-string res
))))
3579 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3580 "Convert a number of seconds to a time string.
3581 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3582 minutes or seconds."
3583 (let* ((secs0 (abs secs
))
3585 (cond ((eq output-format
'days
)
3586 (format "%.3f" (/ (float secs0
) 86400)))
3587 ((eq output-format
'hours
)
3588 (format "%.2f" (/ (float secs0
) 3600)))
3589 ((eq output-format
'minutes
)
3590 (format "%.1f" (/ (float secs0
) 60)))
3591 ((eq output-format
'seconds
)
3592 (format "%d" secs0
))
3593 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3594 (if (< secs
0) (concat "-" res
) res
)))
3596 (defun org-table-fedit-convert-buffer (function)
3597 "Convert all references in this buffer, using FUNCTION."
3598 (let ((line (org-current-line)))
3599 (goto-char (point-min))
3601 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3602 (delete-region (point) (point-at-eol))
3603 (or (eobp) (forward-char 1)))
3604 (org-goto-line line
)))
3606 (defun org-table-fedit-toggle-ref-type ()
3607 "Convert all references in the buffer from B3 to @3$2 and back."
3609 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3610 (org-table-fedit-convert-buffer
3611 (if org-table-buffer-is-an
3612 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3613 (message "Reference type switched to %s"
3614 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3616 (defun org-table-fedit-ref-up ()
3617 "Shift the reference at point one row/hline up."
3619 (org-table-fedit-shift-reference 'up
))
3620 (defun org-table-fedit-ref-down ()
3621 "Shift the reference at point one row/hline down."
3623 (org-table-fedit-shift-reference 'down
))
3624 (defun org-table-fedit-ref-left ()
3625 "Shift the reference at point one field to the left."
3627 (org-table-fedit-shift-reference 'left
))
3628 (defun org-table-fedit-ref-right ()
3629 "Shift the reference at point one field to the right."
3631 (org-table-fedit-shift-reference 'right
))
3633 (defun org-table-fedit-shift-reference (dir)
3635 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3636 (if (memq dir
'(left right
))
3637 (org-rematch-and-replace 1 (eq dir
'left
))
3638 (user-error "Cannot shift reference in this direction")))
3639 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3640 ;; A B3-like reference
3641 (if (memq dir
'(up down
))
3642 (org-rematch-and-replace 2 (eq dir
'up
))
3643 (org-rematch-and-replace 1 (eq dir
'left
))))
3645 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3646 ;; An internal reference
3647 (if (memq dir
'(up down
))
3648 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3649 (org-rematch-and-replace 5 (eq dir
'left
))))))
3651 (defun org-rematch-and-replace (n &optional decr hline
)
3652 "Re-match the group N, and replace it with the shifted reference."
3653 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3654 (goto-char (match-beginning n
))
3655 (and (looking-at (regexp-quote (match-string n
)))
3656 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3659 (defun org-table-shift-refpart (ref &optional decr hline
)
3660 "Shift a reference part REF.
3661 If DECR is set, decrease the references row/column, else increase.
3662 If HLINE is set, this may be a hline reference, it certainly is not
3663 a translation reference."
3665 (let* ((sign (string-match "^[-+]" ref
)) n
)
3667 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3669 ((and hline
(string-match "^I+" ref
))
3670 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3671 (setq n
(+ n
(if decr -
1 1)))
3672 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3674 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3676 (concat sign
(make-string n ?I
)))
3678 ((string-match "^[0-9]+" ref
)
3679 (setq n
(string-to-number (concat sign ref
)))
3680 (setq n
(+ n
(if decr -
1 1)))
3682 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3683 (number-to-string (max 1 n
))))
3685 ((string-match "^[a-zA-Z]+" ref
)
3686 (org-number-to-letters
3687 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3689 (t (user-error "Cannot shift reference"))))))
3691 (defun org-table-fedit-toggle-coordinates ()
3692 "Toggle the display of coordinates in the referenced table."
3694 (let ((pos (marker-position org-pos
)))
3695 (with-current-buffer (marker-buffer org-pos
)
3698 (org-table-toggle-coordinate-overlays)))))
3700 (defun org-table-fedit-finish (&optional arg
)
3701 "Parse the buffer for formula definitions and install them.
3702 With prefix ARG, apply the new formulas to the table."
3704 (org-table-remove-rectangle-highlight)
3705 (if org-table-use-standard-references
3707 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3708 (setq org-table-buffer-is-an nil
)))
3709 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3710 (goto-char (point-min))
3711 (while (re-search-forward
3712 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3714 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3715 form
(match-string 3))
3716 (setq form
(org-trim form
))
3717 (when (not (equal form
""))
3718 (while (string-match "[ \t]*\n[ \t]*" form
)
3719 (setq form
(replace-match " " t t form
)))
3720 (when (assoc var eql
)
3721 (user-error "Double formulas for %s" var
))
3722 (push (cons var form
) eql
)))
3724 (set-window-configuration org-window-configuration
)
3725 (select-window sel-win
)
3727 (unless (org-at-table-p)
3728 (user-error "Lost table position - cannot install formulas"))
3729 (org-table-store-formulas eql
)
3730 (move-marker pos nil
)
3731 (kill-buffer "*Edit Formulas*")
3733 (org-table-recalculate 'all
)
3734 (message "New formulas installed - press C-u C-c C-c to apply."))))
3736 (defun org-table-fedit-abort ()
3737 "Abort editing formulas, without installing the changes."
3739 (org-table-remove-rectangle-highlight)
3740 (let ((pos org-pos
) (sel-win org-selected-window
))
3741 (set-window-configuration org-window-configuration
)
3742 (select-window sel-win
)
3744 (move-marker pos nil
)
3745 (message "Formula editing aborted without installing changes")))
3747 (defun org-table-fedit-lisp-indent ()
3748 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3750 (let ((pos (point)) beg end ind
)
3751 (beginning-of-line 1)
3753 ((looking-at "[ \t]")
3755 (call-interactively 'lisp-indent-line
))
3756 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3757 ((not (fboundp 'pp-buffer
))
3758 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3759 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3760 (goto-char (- (match-end 0) 2))
3762 (setq ind
(make-string (current-column) ?\
))
3763 (condition-case nil
(forward-sexp 1)
3765 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3768 (narrow-to-region beg end
)
3769 (if (eq last-command this-command
)
3771 (goto-char (point-min))
3772 (setq this-command nil
)
3773 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3774 (replace-match " ")))
3776 (untabify (point-min) (point-max))
3777 (goto-char (1+ (point-min)))
3778 (while (re-search-forward "^." nil t
)
3779 (beginning-of-line 1)
3781 (goto-char (point-max))
3782 (org-delete-backward-char 1)))
3786 (defvar org-show-positions nil
)
3788 (defun org-table-show-reference (&optional local
)
3789 "Show the location/value of the $ expression at point."
3791 (org-table-remove-rectangle-highlight)
3793 (let ((pos (if local
(point) org-pos
))
3795 (org-inhibit-highlight-removal t
)
3796 (win (selected-window))
3797 (org-show-positions nil
)
3798 var name e what match dest
)
3799 (if local
(org-table-get-specials))
3801 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3802 (setq match
(concat (substring (match-string 0) 0 -
1)
3804 (substring (match-string 0) 0 -
1)
3807 ((or (org-at-regexp-p org-table-range-regexp2
)
3808 (org-at-regexp-p org-table-translate-regexp
)
3809 (org-at-regexp-p org-table-range-regexp
))
3812 (org-table-convert-refs-to-rc (match-string 0))))
3814 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3815 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3817 (t (user-error "No reference at point")))
3818 match
(and what
(or match
(match-string 0))))
3819 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3820 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3821 'secondary-selection
))
3822 (org-add-hook 'before-change-functions
3823 'org-table-remove-rectangle-highlight
)
3824 (if (eq what
'name
) (setq var
(substring match
1)))
3825 (when (eq what
'range
)
3826 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3827 (setq match
(org-table-formula-substitute-names match
)))
3831 (re-search-backward "^\\S-" nil t
)
3832 (beginning-of-line 1)
3833 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3836 (org-table-convert-refs-to-rc (match-string 1))))
3837 (org-table-add-rectangle-overlay
3838 (match-beginning 1) (match-end 1) face2
))))
3839 (if (and (markerp pos
) (marker-buffer pos
))
3840 (if (get-buffer-window (marker-buffer pos
))
3841 (select-window (get-buffer-window (marker-buffer pos
)))
3842 (org-switch-to-buffer-other-window (get-buffer-window
3843 (marker-buffer pos
)))))
3845 (org-table-force-dataline)
3847 (setq name
(substring dest
1))
3849 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3850 (setq e
(assoc name org-table-named-field-locations
))
3851 (org-goto-line (nth 1 e
))
3852 (org-table-goto-column (nth 2 e
)))
3853 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3854 (let ((l (string-to-number (match-string 1 dest
)))
3855 (c (string-to-number (match-string 2 dest
))))
3856 (org-goto-line (aref org-table-dlines l
))
3857 (org-table-goto-column c
)))
3858 (t (org-table-goto-column (string-to-number name
))))
3859 (move-marker pos
(point))
3860 (org-table-highlight-rectangle nil nil face2
))
3862 ((equal dest match
))
3867 (org-table-get-range match nil nil
'highlight
))
3869 ((setq e
(assoc var org-table-named-field-locations
))
3870 (org-goto-line (nth 1 e
))
3871 (org-table-goto-column (nth 2 e
))
3872 (org-table-highlight-rectangle (point) (point))
3873 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3874 ((setq e
(assoc var org-table-column-names
))
3875 (org-table-goto-column (string-to-number (cdr e
)))
3876 (org-table-highlight-rectangle (point) (point))
3877 (goto-char (org-table-begin))
3878 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3881 (goto-char (match-beginning 1))
3882 (org-table-highlight-rectangle)
3883 (message "Named column (column %s)" (cdr e
)))
3884 (user-error "Column name not found")))
3887 (org-table-goto-column (string-to-number (substring match
1)))
3888 (org-table-highlight-rectangle (point) (point))
3889 (message "Column %s" (substring match
1)))
3890 ((setq e
(assoc var org-table-local-parameters
))
3891 (goto-char (org-table-begin))
3892 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3894 (goto-char (match-beginning 1))
3895 (org-table-highlight-rectangle)
3896 (message "Local parameter."))
3897 (user-error "Parameter not found")))
3900 ((not var
) (user-error "No reference at point"))
3901 ((setq e
(assoc var org-table-formula-constants-local
))
3902 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3904 ((setq e
(assoc var org-table-formula-constants
))
3905 (message "Constant: $%s=%s in `org-table-formula-constants'."
3907 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3908 (message "Constant: $%s=%s, from `constants.el'%s."
3909 var e
(format " (%s units)" constants-unit-system
)))
3910 (t (user-error "Undefined name $%s" var
)))))
3912 (when (and org-show-positions
3913 (not (memq this-command
'(org-table-fedit-scroll
3914 org-table-fedit-scroll-down
))))
3915 (push pos org-show-positions
)
3916 (push org-table-current-begin-pos org-show-positions
)
3917 (let ((min (apply 'min org-show-positions
))
3918 (max (apply 'max org-show-positions
)))
3919 (set-window-start (selected-window) min
)
3921 (or (pos-visible-in-window-p max
)
3922 (set-window-start (selected-window) max
))))
3923 (select-window win
))))
3925 (defun org-table-force-dataline ()
3926 "Make sure the cursor is in a dataline in a table."
3927 (unless (save-excursion
3928 (beginning-of-line 1)
3929 (looking-at org-table-dataline-regexp
))
3930 (let* ((re org-table-dataline-regexp
)
3931 (p1 (save-excursion (re-search-forward re nil
'move
)))
3932 (p2 (save-excursion (re-search-backward re nil
'move
))))
3934 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3936 ((or p1 p2
) (goto-char (or p1 p2
)))
3937 (t (user-error "No table dataline around here"))))))
3939 (defun org-table-fedit-line-up ()
3940 "Move cursor one line up in the window showing the table."
3942 (org-table-fedit-move 'previous-line
))
3944 (defun org-table-fedit-line-down ()
3945 "Move cursor one line down in the window showing the table."
3947 (org-table-fedit-move 'next-line
))
3949 (defun org-table-fedit-move (command)
3950 "Move the cursor in the window showing the table.
3951 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3952 (let ((org-table-allow-automatic-line-recalculation nil
)
3953 (pos org-pos
) (win (selected-window)) p
)
3954 (select-window (get-buffer-window (marker-buffer org-pos
)))
3956 (call-interactively command
)
3957 (while (and (org-at-table-p)
3958 (org-at-table-hline-p))
3959 (call-interactively command
))
3960 (or (org-at-table-p) (goto-char p
))
3961 (move-marker pos
(point))
3962 (select-window win
)))
3964 (defun org-table-fedit-scroll (N)
3966 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3967 (scroll-other-window N
)))
3969 (defun org-table-fedit-scroll-down (N)
3971 (org-table-fedit-scroll (- N
)))
3973 (defvar org-table-rectangle-overlays nil
)
3975 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3976 "Add a new overlay."
3977 (let ((ov (make-overlay beg end
)))
3978 (overlay-put ov
'face
(or face
'secondary-selection
))
3979 (push ov org-table-rectangle-overlays
)))
3981 (defun org-table-highlight-rectangle (&optional beg end face
)
3982 "Highlight rectangular region in a table."
3983 (setq beg
(or beg
(point)) end
(or end
(point)))
3984 (let ((b (min beg end
))
3987 (and (boundp 'org-show-positions
)
3988 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3989 (goto-char (min beg end
))
3990 (setq l1
(org-current-line)
3991 c1
(org-table-current-column))
3992 (goto-char (max beg end
))
3993 (setq l2
(org-current-line)
3994 c2
(org-table-current-column))
3995 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3997 (beginning-of-line 1)
3998 (loop for line from l1 to l2 do
3999 (when (looking-at org-table-dataline-regexp
)
4000 (org-table-goto-column c1
)
4001 (skip-chars-backward "^|\n") (setq beg
(point))
4002 (org-table-goto-column c2
)
4003 (skip-chars-forward "^|\n") (setq end
(point))
4004 (org-table-add-rectangle-overlay beg end face
))
4005 (beginning-of-line 2))
4007 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
4009 (defun org-table-remove-rectangle-highlight (&rest ignore
)
4010 "Remove the rectangle overlays."
4011 (unless org-inhibit-highlight-removal
4012 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4013 (mapc 'delete-overlay org-table-rectangle-overlays
)
4014 (setq org-table-rectangle-overlays nil
)))
4016 (defvar org-table-coordinate-overlays nil
4017 "Collects the coordinate grid overlays, so that they can be removed.")
4018 (make-variable-buffer-local 'org-table-coordinate-overlays
)
4020 (defun org-table-overlay-coordinates ()
4021 "Add overlays to the table at point, to show row/column coordinates."
4023 (mapc 'delete-overlay org-table-coordinate-overlays
)
4024 (setq org-table-coordinate-overlays nil
)
4026 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4027 (goto-char (org-table-begin))
4028 (while (org-at-table-p)
4029 (setq eol
(point-at-eol))
4030 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4031 (push ov org-table-coordinate-overlays
)
4032 (setq hline
(looking-at org-table-hline-regexp
))
4033 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4034 (format "%4d" (setq id
(1+ id
)))))
4035 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4038 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4039 (setq beg
(1+ (match-beginning 0))
4041 s1
(concat "$" (int-to-string ic
))
4042 s2
(org-number-to-letters ic
)
4043 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4044 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4045 (push ov org-table-coordinate-overlays
)
4046 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4047 (beginning-of-line 2)))))
4050 (defun org-table-toggle-coordinate-overlays ()
4051 "Toggle the display of Row/Column numbers in tables."
4053 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4054 (message "Tables Row/Column numbers display turned %s"
4055 (if org-table-overlay-coordinates
"on" "off"))
4056 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4058 (unless org-table-overlay-coordinates
4059 (mapc 'delete-overlay org-table-coordinate-overlays
)
4060 (setq org-table-coordinate-overlays nil
)))
4063 (defun org-table-toggle-formula-debugger ()
4064 "Toggle the formula debugger in tables."
4066 (setq org-table-formula-debug
(not org-table-formula-debug
))
4067 (message "Formula debugging has been turned %s"
4068 (if org-table-formula-debug
"on" "off")))
4070 ;;; The orgtbl minor mode
4072 ;; Define a minor mode which can be used in other modes in order to
4073 ;; integrate the org-mode table editor.
4075 ;; This is really a hack, because the org-mode table editor uses several
4076 ;; keys which normally belong to the major mode, for example the TAB and
4077 ;; RET keys. Here is how it works: The minor mode defines all the keys
4078 ;; necessary to operate the table editor, but wraps the commands into a
4079 ;; function which tests if the cursor is currently inside a table. If that
4080 ;; is the case, the table editor command is executed. However, when any of
4081 ;; those keys is used outside a table, the function uses `key-binding' to
4082 ;; look up if the key has an associated command in another currently active
4083 ;; keymap (minor modes, major mode, global), and executes that command.
4084 ;; There might be problems if any of the keys used by the table editor is
4085 ;; otherwise used as a prefix key.
4087 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4088 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4089 ;; addresses this by checking explicitly for both bindings.
4091 ;; The optimized version (see variable `orgtbl-optimized') takes over
4092 ;; all keys which are bound to `self-insert-command' in the *global map*.
4093 ;; Some modes bind other commands to simple characters, for example
4094 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4095 ;; active, this binding is ignored inside tables and replaced with a
4096 ;; modified self-insert.
4099 (defvar orgtbl-mode-map
(make-keymap)
4100 "Keymap for `orgtbl-mode'.")
4102 (defvar org-old-auto-fill-inhibit-regexp nil
4103 "Local variable used by `orgtbl-mode'.")
4105 (defconst orgtbl-line-start-regexp
4106 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4107 "Matches a line belonging to an orgtbl.")
4109 (defconst orgtbl-extra-font-lock-keywords
4110 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4111 0 (quote 'org-table
) 'prepend
))
4112 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4114 ;; Install it as a minor mode.
4115 (put 'orgtbl-mode
:included t
)
4116 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4119 (define-minor-mode orgtbl-mode
4120 "The `org-mode' table editor as a minor mode for use in other modes."
4121 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4122 (org-load-modules-maybe)
4124 ((derived-mode-p 'org-mode
)
4125 ;; Exit without error, in case some hook functions calls this
4126 ;; by accident in org-mode.
4127 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4129 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4130 ;; Make sure we are first in minor-mode-map-alist
4131 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4132 ;; FIXME: maybe it should use emulation-mode-map-alists?
4133 (and c
(setq minor-mode-map-alist
4134 (cons c
(delq c minor-mode-map-alist
)))))
4135 (org-set-local (quote org-table-may-need-update
) t
)
4136 (org-add-hook 'before-change-functions
'org-before-change-function
4138 (org-set-local 'org-old-auto-fill-inhibit-regexp
4139 auto-fill-inhibit-regexp
)
4140 (org-set-local 'auto-fill-inhibit-regexp
4141 (if auto-fill-inhibit-regexp
4142 (concat orgtbl-line-start-regexp
"\\|"
4143 auto-fill-inhibit-regexp
)
4144 orgtbl-line-start-regexp
))
4145 (add-to-invisibility-spec '(org-cwidth))
4146 (when (fboundp 'font-lock-add-keywords
)
4147 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4148 (org-restart-font-lock))
4149 (easy-menu-add orgtbl-mode-menu
))
4151 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4152 (org-table-cleanup-narrow-column-properties)
4153 (org-remove-from-invisibility-spec '(org-cwidth))
4154 (remove-hook 'before-change-functions
'org-before-change-function t
)
4155 (when (fboundp 'font-lock-remove-keywords
)
4156 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4157 (org-restart-font-lock))
4158 (easy-menu-remove orgtbl-mode-menu
)
4159 (force-mode-line-update 'all
))))
4161 (defun org-table-cleanup-narrow-column-properties ()
4162 "Remove all properties related to narrow-column invisibility."
4163 (let ((s (point-min)))
4164 (while (setq s
(text-property-any s
(point-max)
4165 'display org-narrow-column-arrow
))
4166 (remove-text-properties s
(1+ s
) '(display t
)))
4167 (setq s
(point-min))
4168 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4169 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4170 (setq s
(point-min))
4171 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4172 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4174 (defun orgtbl-make-binding (fun n
&rest keys
)
4175 "Create a function for binding in the table minor mode.
4176 FUN is the command to call inside a table. N is used to create a unique
4177 command name. KEYS are keys that should be checked in for a command
4178 to execute outside of tables."
4181 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4183 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4184 "Outside of tables, run the binding of `"
4185 (mapconcat #'key-description keys
"' or `")
4190 (list 'call-interactively
(list 'quote fun
))
4191 (list 'let
'(orgtbl-mode)
4192 (list 'call-interactively
4195 (list 'key-binding k
))
4197 '('orgtbl-error
))))))))
4199 (defun orgtbl-error ()
4200 "Error when there is no default binding for a table key."
4202 (user-error "This key has no function outside tables"))
4204 (defun orgtbl-setup ()
4205 "Setup orgtbl keymaps."
4208 '(([(meta shift left
)] org-table-delete-column
)
4209 ([(meta left
)] org-table-move-column-left
)
4210 ([(meta right
)] org-table-move-column-right
)
4211 ([(meta shift right
)] org-table-insert-column
)
4212 ([(meta shift up
)] org-table-kill-row
)
4213 ([(meta shift down
)] org-table-insert-row
)
4214 ([(meta up
)] org-table-move-row-up
)
4215 ([(meta down
)] org-table-move-row-down
)
4216 ("\C-c\C-w" org-table-cut-region
)
4217 ("\C-c\M-w" org-table-copy-region
)
4218 ("\C-c\C-y" org-table-paste-rectangle
)
4219 ("\C-c\C-w" org-table-wrap-region
)
4220 ("\C-c-" org-table-insert-hline
)
4221 ("\C-c}" org-table-toggle-coordinate-overlays
)
4222 ("\C-c{" org-table-toggle-formula-debugger
)
4223 ("\C-m" org-table-next-row
)
4224 ([(shift return
)] org-table-copy-down
)
4225 ("\C-c?" org-table-field-info
)
4226 ("\C-c " org-table-blank-field
)
4227 ("\C-c+" org-table-sum
)
4228 ("\C-c=" org-table-eval-formula
)
4229 ("\C-c'" org-table-edit-formulas
)
4230 ("\C-c`" org-table-edit-field
)
4231 ("\C-c*" org-table-recalculate
)
4232 ("\C-c^" org-table-sort-lines
)
4233 ("\M-a" org-table-beginning-of-field
)
4234 ("\M-e" org-table-end-of-field
)
4235 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4237 (while (setq elt
(pop bindings
))
4238 (setq nfunc
(1+ nfunc
))
4239 (setq key
(org-key (car elt
))
4241 cmd
(orgtbl-make-binding fun nfunc key
))
4242 (org-defkey orgtbl-mode-map key cmd
))
4244 ;; Special treatment needed for TAB and RET
4245 (org-defkey orgtbl-mode-map
[(return)]
4246 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4247 (org-defkey orgtbl-mode-map
"\C-m"
4248 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4250 (org-defkey orgtbl-mode-map
[(tab)]
4251 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4252 (org-defkey orgtbl-mode-map
"\C-i"
4253 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4255 (org-defkey orgtbl-mode-map
[(shift tab
)]
4256 (orgtbl-make-binding 'org-table-previous-field
104
4257 [(shift tab
)] [(tab)] "\C-i"))
4260 (unless (featurep 'xemacs
)
4261 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4262 (orgtbl-make-binding 'org-table-previous-field
107
4263 [S-iso-lefttab
] [backtab] [(shift tab)]
4266 (org-defkey orgtbl-mode-map [backtab]
4267 (orgtbl-make-binding 'org-table-previous-field
108
4268 [backtab] [S-iso-lefttab] [(shift tab)]
4271 (org-defkey orgtbl-mode-map "\M-\C-m"
4272 (orgtbl-make-binding 'org-table-wrap-region 105
4273 "\M-\C-m" [(meta return)]))
4274 (org-defkey orgtbl-mode-map [(meta return)]
4275 (orgtbl-make-binding 'org-table-wrap-region 106
4276 [(meta return)] "\M-\C-m"))
4278 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4279 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4281 (when orgtbl-optimized
4282 ;; If the user wants maximum table support, we need to hijack
4283 ;; some standard editing functions
4284 (org-remap orgtbl-mode-map
4285 'self-insert-command 'orgtbl-self-insert-command
4286 'delete-char 'org-delete-char
4287 'delete-backward-char 'org-delete-backward-char)
4288 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4289 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4291 ["Create or convert" org-table-create-or-convert-from-region
4292 :active (not (org-at-table-p)) :keys "C-c |" ]
4294 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4295 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4296 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4297 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4299 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4300 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4301 ["Copy Field from Above"
4302 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4305 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4306 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4307 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4308 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4310 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4311 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4312 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4313 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4314 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4316 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4318 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4319 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4320 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4321 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4324 ["Insert table template" orgtbl-insert-radio-table
4325 (assq major-mode orgtbl-radio-table-templates)]
4326 ["Comment/uncomment table" orgtbl-toggle-comment t])
4328 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4329 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4330 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4331 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4332 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4333 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4334 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4335 ["Sum Column/Rectangle" org-table-sum
4336 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4337 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4339 org-table-toggle-formula-debugger :active (org-at-table-p)
4341 :style toggle :selected org-table-formula-debug]
4342 ["Show Col/Row Numbers"
4343 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4345 :style toggle :selected org-table-overlay-coordinates]
4348 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4349 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4352 (defun orgtbl-ctrl-c-ctrl-c (arg)
4353 "If the cursor is inside a table, realign the table.
4354 If it is a table to be sent away to a receiver, do it.
4355 With prefix arg, also recompute table."
4357 (let ((case-fold-search t) (pos (point)) action)
4359 (beginning-of-line 1)
4361 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4362 ((looking-at "[ \t]*|") pos)
4363 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4367 (org-table-maybe-eval-formula)
4369 (call-interactively 'org-table-recalculate)
4370 (org-table-maybe-recalculate-line))
4371 (call-interactively 'org-table-align)
4372 (when (orgtbl-send-table 'maybe)
4373 (run-hooks 'orgtbl-after-send-table-hook)))
4374 ((eq action 'recalc)
4376 (beginning-of-line 1)
4377 (skip-chars-backward " \r\n\t")
4378 (if (org-at-table-p)
4379 (org-call-with-arg 'org-table-recalculate t))))
4380 (t (let (orgtbl-mode)
4381 (call-interactively (key-binding "\C-c\C-c")))))))
4383 (defun orgtbl-create-or-convert-from-region (arg)
4384 "Create table or convert region to table, if no conflicting binding.
4385 This installs the table binding `C-c |', but only if there is no
4386 conflicting binding to this key outside orgtbl-mode."
4388 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4390 (call-interactively cmd)
4391 (call-interactively 'org-table-create-or-convert-from-region))))
4393 (defun orgtbl-tab (arg)
4394 "Justification and field motion for `orgtbl-mode'."
4396 (if arg (org-table-edit-field t)
4397 (org-table-justify-field-maybe)
4398 (org-table-next-field)))
4400 (defun orgtbl-ret ()
4401 "Justification and field motion for `orgtbl-mode'."
4405 (org-table-justify-field-maybe)
4406 (org-table-next-row)))
4408 (defun orgtbl-self-insert-command (N)
4409 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4410 If the cursor is in a table looking at whitespace, the whitespace is
4411 overwritten, and the table is not marked as requiring realignment."
4413 (if (and (org-at-table-p)
4415 (and org-table-auto-blank-field
4416 (member last-command
4417 '(orgtbl-hijacker-command-100
4418 orgtbl-hijacker-command-101
4419 orgtbl-hijacker-command-102
4420 orgtbl-hijacker-command-103
4421 orgtbl-hijacker-command-104
4422 orgtbl-hijacker-command-105
4424 (org-table-blank-field))
4427 (looking-at "[^|\n]* +|"))
4428 (let (org-table-may-need-update)
4429 (goto-char (1- (match-end 0)))
4430 (org-delete-backward-char 1)
4431 (goto-char (match-beginning 0))
4432 (self-insert-command N))
4433 (setq org-table-may-need-update t)
4436 (cmd (or (key-binding
4437 (or (and (listp function-key-map)
4438 (setq a (assoc last-input-event function-key-map))
4440 (vector last-input-event)))
4441 'self-insert-command)))
4442 (call-interactively cmd)
4443 (if (and org-self-insert-cluster-for-undo
4444 (eq cmd 'self-insert-command))
4445 (if (not (eq last-command 'orgtbl-self-insert-command))
4446 (setq org-self-insert-command-undo-counter 1)
4447 (if (>= org-self-insert-command-undo-counter 20)
4448 (setq org-self-insert-command-undo-counter 1)
4449 (and (> org-self-insert-command-undo-counter 0)
4451 (not (cadr buffer-undo-list)) ; remove nil entry
4452 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4453 (setq org-self-insert-command-undo-counter
4454 (1+ org-self-insert-command-undo-counter))))))))
4456 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4457 "Regular expression matching exponentials as produced by calc.")
4459 (defun orgtbl-gather-send-defs ()
4460 "Gather a plist of :name, :transform, :params for each destination before
4463 (goto-char (org-table-begin))
4465 (beginning-of-line 0)
4466 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4467 (let ((name (org-no-properties (match-string 1)))
4468 (transform (intern (match-string 2)))
4469 (params (if (match-end 3)
4470 (read (concat "(" (match-string 3) ")")))))
4471 (push (list :name name :transform transform :params params)
4473 (beginning-of-line 0)))
4476 (defun orgtbl-send-replace-tbl (name txt)
4477 "Find and replace table NAME with TXT."
4479 (goto-char (point-min))
4480 (unless (re-search-forward
4481 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4482 (user-error "Don't know where to insert translated table"))
4483 (let ((beg (line-beginning-position 2)))
4484 (unless (re-search-forward
4485 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4486 (user-error "Cannot find end of insertion region"))
4488 (delete-region beg (point)))
4492 (defun org-table-to-lisp (&optional txt)
4493 "Convert the table at point to a Lisp structure.
4494 The structure will be a list. Each item is either the symbol `hline'
4495 for a horizontal separator line, or a list of field values as strings.
4496 The table is taken from the parameter TXT, or from the buffer at point."
4497 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4499 (buffer-substring-no-properties (org-table-begin)
4502 (if (string-match org-table-hline-regexp x) 'hline
4503 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4504 (org-split-string txt "[ \t]*\n[ \t]*"))))
4506 (defun orgtbl-send-table (&optional maybe)
4507 "Send a transformed version of table at point to the receiver position.
4508 With argument MAYBE, fail quietly if no transformation is defined
4512 (unless (org-at-table-p) (user-error "Not at a table"))
4513 ;; when non-interactive, we assume align has just happened.
4514 (when (org-called-interactively-p 'any) (org-table-align))
4515 (let ((dests (orgtbl-gather-send-defs))
4516 (table (org-table-to-lisp
4517 (buffer-substring-no-properties (org-table-begin)
4521 (if maybe (throw 'exit nil)
4522 (user-error "Don't know how to transform this table")))
4523 (dolist (dest dests)
4524 (let ((name (plist-get dest :name))
4525 (transform (plist-get dest :transform))
4526 (params (plist-get dest :params)))
4527 (unless (fboundp transform)
4528 (user-error "No such transformation function %s" transform))
4529 (orgtbl-send-replace-tbl name (funcall transform table params)))
4531 (message "Table converted and installed at %d receiver location%s"
4532 ntbl (if (> ntbl 1) "s" ""))
4533 (and (> ntbl 0) ntbl))))
4535 (defun org-remove-by-index (list indices &optional i0)
4536 "Remove the elements in LIST with indices in INDICES.
4537 First element has index 0, or I0 if given."
4540 (if (integerp indices) (setq indices (list indices)))
4541 (setq i0 (1- (or i0 0)))
4542 (delq :rm (mapcar (lambda (x)
4544 (if (memq i0 indices) :rm x))
4547 (defun orgtbl-toggle-comment ()
4548 "Comment or uncomment the orgtbl at point."
4550 (let* ((case-fold-search t)
4551 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4552 (re2 (concat "^" orgtbl-line-start-regexp))
4553 (commented (save-excursion (beginning-of-line 1)
4554 (cond ((looking-at re1) t)
4555 ((looking-at re2) nil)
4556 (t (user-error "Not at an org table")))))
4557 (re (if commented re1 re2))
4560 (beginning-of-line 1)
4561 (while (looking-at re) (beginning-of-line 0))
4562 (beginning-of-line 2)
4564 (while (looking-at re) (beginning-of-line 2))
4566 (comment-region beg end (if commented '(4) nil))))
4568 (defun orgtbl-insert-radio-table ()
4569 "Insert a radio table template appropriate for this major mode."
4571 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4574 (unless e (user-error "No radio table setup defined for %s" major-mode))
4575 (setq name (read-string "Table name: "))
4576 (while (string-match "%n" txt)
4577 (setq txt (replace-match name t t txt)))
4578 (or (bolp) (insert "\n"))
4584 (defun orgtbl-to-generic (table params)
4585 "Convert the orgtbl-mode TABLE to some other format.
4587 This generic routine can be used for many standard cases.
4589 TABLE is a list, each entry either the symbol `hline' for
4590 a horizontal separator line, or a list of fields for that
4591 line. PARAMS is a property list of parameters that can
4592 influence the conversion.
4594 Valid parameters are:
4598 Export back-end used as a basis to transcode elements of the
4599 table, when no specific parameter applies to it. It is also
4600 used to translate cells contents. You can prevent this by
4601 setting :raw property to a non-nil value.
4605 When non-nil, only convert rows, not the table itself. This is
4606 equivalent to setting to the empty string both :tstart
4607 and :tend, which see.
4611 When set to an integer N, skip the first N lines of the table.
4612 Horizontal separation lines do count for this parameter!
4616 List of columns that should be skipped. If the table has
4617 a column with calculation marks, that column is automatically
4618 discarded beforehand.
4622 String to be inserted on horizontal separation lines. May be
4623 nil to ignore these lines altogether.
4627 Separator between two fields, as a string.
4629 Each in the following group may be either a string or a function
4630 of no arguments returning a string:
4634 Strings to start and end the table. Ignored when :splice is t.
4638 Strings to start and end a new table line.
4642 Strings to start and end the last table line. Default,
4643 respectively, to :lstart and :lend.
4645 Each in the following group may be a string or a function of one
4646 argument (either the cells in the current row, as a list of
4647 strings, or the current cell) returning a string:
4651 Format string for an entire row, with enough %s to capture all
4652 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4656 Format for the entire last line, defaults to :lfmt.
4660 A format to be used to wrap the field, should contain %s for
4661 the original field value. For example, to wrap everything in
4662 dollars, you could use :fmt \"$%s$\". This may also be
4663 a property list with column numbers and format strings, or
4666 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4668 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4670 Same as above, specific for the header lines in the table.
4671 All lines before the first hline are treated as header. If
4672 any of these is not present, the data line value is used.
4674 This may be either a string or a function of two arguments:
4678 Use this format to print numbers with exponential. The format
4679 should have %s twice for inserting mantissa and exponent, for
4680 example \"%s\\\\times10^{%s}\". This may also be a property
4681 list with column numbers and format strings or functions.
4682 :fmt will still be applied after :efmt."
4683 (let ((backend (plist-get params :backend)))
4684 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4685 (user-error "Unknown :backend value"))
4686 (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
4688 (org-export-string-as
4689 ;; Return TABLE as Org syntax. Tolerate non-string cells.
4690 (with-output-to-string
4692 (cond ((eq e 'hline) (princ "|--\n"))
4694 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4696 ;; Build a custom back-end according to PARAMS. Before defining
4697 ;; a translator, check if there is anything to do. When there
4698 ;; isn't, let BACKEND handle the element.
4699 (org-export-create-backend
4700 :parent (or backend 'org)
4702 '((:filter-parse-tree
4703 ;; Handle :skip parameter.
4704 (lambda (tree backend info)
4705 (let ((skip (plist-get info :skip)))
4707 (unless (wholenump skip) (user-error "Wrong :skip value"))
4709 (org-element-map tree 'table-row
4712 (org-element-extract-element row)
4717 ;; Handle :skipcols parameter.
4718 (lambda (tree backend info)
4719 (let ((skipcols (plist-get info :skipcols)))
4721 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4722 (org-element-map tree 'table
4725 (org-export-table-has-special-column-p table)))
4726 (dolist (row (org-element-contents table))
4727 (when (eq (org-element-property :type row) 'standard)
4729 (dolist (cell (nthcdr (if specialp 1 0)
4730 (org-element-contents row)))
4731 (when (memq c skipcols)
4732 (org-element-extract-element cell))
4737 `((table . ,(org-table--to-generic-table params))
4738 (table-row . ,(org-table--to-generic-row params))
4739 (table-cell . ,(org-table--to-generic-cell params))
4740 ;; Section. Return contents to avoid garbage around table.
4741 (section . (lambda (s c i) c))))
4742 'body-only (org-combine-plists params '(:with-tables t))))))
4744 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4745 (cond ((null value) nil)
4746 ((functionp value) `(funcall ',value ,@args))
4748 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4749 (args `(format ,value ,@args))
4751 ((and with-cons (consp value))
4752 `(let ((val (cadr (memq column ',value))))
4753 (cond ((null val) contents)
4754 ((stringp val) (format val ,@args))
4755 ((functionp val) (funcall val ,@args))
4756 (t (user-error "Wrong %s value" ,name)))))
4757 (t (user-error "Wrong %s value" name))))
4759 (defun org-table--to-generic-table (params)
4760 "Return custom table transcoder according to PARAMS.
4761 PARAMS is a plist. See `orgtbl-to-generic' for more
4763 (let ((backend (plist-get params :backend))
4764 (splice (plist-get params :splice))
4765 (tstart (plist-get params :tstart))
4766 (tend (plist-get params :tend)))
4767 `(lambda (table contents info)
4769 ,(and tstart (not splice)
4770 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4771 ,(if (or (not backend) tstart tend splice) 'contents
4772 `(org-export-with-backend ',backend table contents info))
4773 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4775 (defun org-table--to-generic-row (params)
4776 "Return custom table row transcoder according to PARAMS.
4777 PARAMS is a plist. See `orgtbl-to-generic' for more
4779 (let* ((backend (plist-get params :backend))
4780 (lstart (plist-get params :lstart))
4781 (llstart (plist-get params :llstart))
4782 (hlstart (plist-get params :hlstart))
4783 (hllstart (plist-get params :hllstart))
4784 (lend (plist-get params :lend))
4785 (llend (plist-get params :llend))
4786 (hlend (plist-get params :hlend))
4787 (hllend (plist-get params :hllend))
4788 (lfmt (plist-get params :lfmt))
4789 (llfmt (plist-get params :llfmt))
4790 (hlfmt (plist-get params :hlfmt))
4791 (hllfmt (plist-get params :hllfmt)))
4792 `(lambda (row contents info)
4793 (if (eq (org-element-property :type row) 'rule)
4795 ((plist-member params :hline)
4796 (org-table--generic-apply (plist-get params :hline) ":hline"))
4797 (backend `(org-export-with-backend ',backend row nil info)))
4798 (let ((headerp (org-export-table-row-in-header-p row info))
4799 (lastp (not (org-export-get-next-element row info)))
4800 (last-header-p (org-export-table-row-ends-header-p row info)))
4802 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4803 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4804 ;; `:lstart', `:lend' and their relatives.
4806 '(org-element-map row 'table-cell
4808 ;; Export all cells, without separators.
4810 ;; Use `org-export-data-with-backend'
4811 ;; instead of `org-export-data' to eschew
4812 ;; cached values, which
4813 ;; ignore :orgtbl-ignore-sep parameter.
4814 (org-export-data-with-backend
4816 (plist-get info :back-end)
4817 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4821 `(last-header-p ,(org-table--generic-apply
4822 hllfmt ":hllfmt" nil cells)))
4824 `(headerp ,(org-table--generic-apply
4825 hlfmt ":hlfmt" nil cells)))
4827 `(lastp ,(org-table--generic-apply
4828 llfmt ":llfmt" nil cells)))
4830 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4834 (or hllstart hllend)
4837 ,(org-table--generic-apply hllstart ":hllstart")
4839 ,(org-table--generic-apply hllend ":hllend"))))
4844 ,(org-table--generic-apply hlstart ":hlstart")
4846 ,(org-table--generic-apply hlend ":hlend"))))
4851 ,(org-table--generic-apply llstart ":llstart")
4853 ,(org-table--generic-apply llend ":llend"))))
4858 ,(org-table--generic-apply lstart ":lstart")
4860 ,(org-table--generic-apply lend ":lend")))
4862 `(org-export-with-backend
4863 ',backend row contents info))
4864 (t 'contents)))))))))))))))
4866 (defun org-table--to-generic-cell (params)
4867 "Return custom table cell transcoder according to PARAMS.
4868 PARAMS is a plist. See `orgtbl-to-generic' for more
4870 (let* ((backend (plist-get params :backend))
4871 (efmt (plist-get params :efmt))
4872 (fmt (plist-get params :fmt))
4873 (hfmt (plist-get params :hfmt))
4874 (sep (plist-get params :sep))
4875 (hsep (plist-get params :hsep)))
4876 `(lambda (cell contents info)
4877 (let ((headerp (org-export-table-row-in-header-p
4878 (org-export-get-parent-element cell) info))
4879 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4880 ;; Make sure that contents are exported as Org data when :raw
4881 ;; parameter is non-nil.
4882 ,(when (and backend (plist-get params :raw))
4884 ;; Since we don't know what are the pseudo object
4885 ;; types defined in backend, we cannot pass them to
4886 ;; `org-element-interpret-data'. As a consequence,
4887 ;; they will be treated as pseudo elements, and
4888 ;; will have newlines appended instead of spaces.
4889 ;; Therefore, we must make sure :post-blank value
4890 ;; is really turned into spaces.
4891 (replace-regexp-in-string
4894 (org-element-interpret-data
4895 (org-element-contents cell))))))
4897 ;; Check if we can apply `:efmt' on CONTENTS.
4899 `(when (string-match orgtbl-exp-regexp contents)
4900 (let ((mantissa (match-string 1 contents))
4901 (exponent (match-string 2 contents)))
4902 (setq contents ,(org-table--generic-apply
4903 efmt ":efmt" t 'mantissa 'exponent)))))
4904 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
4906 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
4907 hfmt ":hfmt" t 'contents))))
4908 ,(and fmt `(t (setq contents ,(org-table--generic-apply
4909 fmt ":hfmt" t 'contents))))))
4910 ;; If a separator is provided, use it instead of BACKEND's.
4911 ;; Separators are ignored when LFMT (or equivalent) is
4915 `(if (or ,(and (not sep) '(not headerp))
4916 (plist-get info :orgtbl-ignore-sep)
4917 (not (org-export-get-next-element cell info)))
4918 ,(if (not backend) 'contents
4919 `(org-export-with-backend ',backend cell contents info))
4921 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
4923 (backend `(org-export-with-backend ',backend cell contents info))
4927 (defun orgtbl-to-tsv (table params)
4928 "Convert the orgtbl-mode table to TAB separated material."
4929 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4932 (defun orgtbl-to-csv (table params)
4933 "Convert the orgtbl-mode table to CSV material.
4934 This does take care of the proper quoting of fields with comma or quotes."
4935 (orgtbl-to-generic table
4936 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
4940 (defun orgtbl-to-latex (table params)
4941 "Convert the orgtbl-mode TABLE to LaTeX.
4943 TABLE is a list, each entry either the symbol `hline' for
4944 a horizontal separator line, or a list of fields for that line.
4945 PARAMS is a property list of parameters that can influence the
4946 conversion. All parameters from `orgtbl-to-generic' are
4947 supported. It is also possible to use the following ones:
4951 When non-nil, use formal \"booktabs\" style.
4955 Specify environment to use, as a string. If you use
4956 \"longtable\", you may also want to specify :language property,
4957 as a string, to get proper continuation strings."
4962 ;; Provide sane default values.
4963 (list :backend 'latex
4964 :latex-default-table-mode 'table
4965 :latex-tables-centered nil
4966 :latex-tables-booktabs (plist-get params :booktabs)
4967 :latex-table-scientific-notation nil
4968 :latex-default-table-environment
4969 (or (plist-get params :environment) "tabular"))
4973 (defun orgtbl-to-html (table params)
4974 "Convert the orgtbl-mode TABLE to HTML.
4976 TABLE is a list, each entry either the symbol `hline' for
4977 a horizontal separator line, or a list of fields for that line.
4978 PARAMS is a property list of parameters that can influence the
4979 conversion. All parameters from `orgtbl-to-generic' are
4980 supported. It is also possible to use the following one:
4984 Attributes and values, as a plist, which will be used in
4990 ;; Provide sane default values.
4991 (list :backend 'html
4992 :html-table-data-tags '("<td%s>" . "</td>")
4993 :html-table-use-header-tags-for-first-column nil
4994 :html-table-align-individual-fields t
4995 :html-table-row-tags '("<tr>" . "</tr>")
4996 :html-table-attributes
4997 (if (plist-member params :attributes)
4998 (plist-get params :attributes)
4999 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5004 (defun orgtbl-to-texinfo (table params)
5005 "Convert the orgtbl-mode TABLE to Texinfo.
5007 TABLE is a list, each entry either the symbol `hline' for
5008 a horizontal separator line, or a list of fields for that line.
5009 PARAMS is a property list of parameters that can influence the
5010 conversion. All parameters from `orgtbl-to-generic' are
5011 supported. It is also possible to use the following one:
5015 Column widths, as a string. When providing column fractions,
5016 \"@columnfractions\" command can be omitted."
5017 (require 'ox-texinfo)
5022 (list :backend 'texinfo
5023 :texinfo-tables-verbatim nil
5024 :texinfo-table-scientific-notation nil)
5026 (columns (let ((w (plist-get params :columns)))
5028 ((org-string-match-p "{\\|@columnfractions " w) w)
5029 (t (concat "@columnfractions " w))))))
5030 (if (not columns) output
5031 (replace-regexp-in-string
5032 "@multitable \\(.*\\)" columns output t nil 1))))
5035 (defun orgtbl-to-orgtbl (table params)
5036 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5038 TABLE is a list, each entry either the symbol `hline' for
5039 a horizontal separator line, or a list of fields for that line.
5040 PARAMS is a property list of parameters that can influence the
5041 conversion. All parameters from `orgtbl-to-generic' are
5044 Useful when slicing one table into many. The :hline, :sep,
5045 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5046 be set to provide ORGTBL directives for the generated table."
5048 (orgtbl-to-generic table (org-combine-plists (list :backend 'org))))
5050 (defun orgtbl-to-table.el (table params)
5051 "Convert the orgtbl-mode TABLE into a table.el table.
5052 TABLE is a list, each entry either the symbol `hline' for
5053 a horizontal separator line, or a list of fields for that line.
5054 PARAMS is a property list of parameters that can influence the
5055 conversion. All parameters from `orgtbl-to-generic' are
5058 (insert (orgtbl-to-orgtbl table params))
5060 (replace-regexp-in-string
5062 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5064 (defun orgtbl-to-unicode (table params)
5065 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5067 TABLE is a list, each entry either the symbol `hline' for
5068 a horizontal separator line, or a list of fields for that line.
5069 PARAMS is a property list of parameters that can influence the
5070 conversion. All parameters from `orgtbl-to-generic' are
5071 supported. It is also possible to use the following ones:
5075 When non-nil, use \"ascii-art-to-unicode\" package to translate
5076 the table. You can download it here:
5077 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5081 When non-nil, narrow columns width than provided width cookie,
5082 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5087 (list :backend 'ascii
5088 :ascii-charset 'utf-8
5089 :ascii-table-keep-all-vertical-lines (plist-get params :)
5090 :ascii-table-widen-columns (not (plist-get params :narrow))
5091 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5094 ;; Put the cursor in a column containing numerical values
5095 ;; of an Org-Mode table,
5097 ;; A new column is added with a bar plot.
5098 ;; When the table is refreshed (C-u C-c *),
5099 ;; the plot is updated to reflect the new values.
5101 (defun orgtbl-ascii-draw (value min max &optional width characters)
5102 "Draw an ascii bar in a table.
5103 VALUE is a the value to plot, the width of the bar to draw. A
5104 value equal to MIN will be displayed as empty (zero width bar).
5105 A value equal to MAX will draw a bar filling all the WIDTH.
5106 WIDTH is the expected width in characters of the column.
5107 CHARACTERS is a string that will compose the bar, with shades of
5108 grey from pure white to pure black. It defaults to a 10
5109 characters string of regular ascii characters."
5110 (let* ((characters (or characters " .:;c!lhVHW"))
5111 (width (or width 12))
5112 (value (if (numberp value) value (string-to-number value)))
5113 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5115 ((< value 0) "too small")
5116 ((> value width) "too large")
5118 (let ((len (1- (length characters))))
5120 (make-string (floor value) (elt characters len))
5121 (string (elt characters
5122 (floor (* (- value (floor value)) len))))))))))
5125 (defun orgtbl-ascii-plot (&optional ask)
5126 "Draw an ascii bar plot in a column.
5127 With cursor in a column containing numerical values, this
5128 function will draw a plot in a new column.
5129 ASK, if given, is a numeric prefix to override the default 12
5130 characters width of the plot. ASK may also be the
5131 \\[universal-argument] prefix, which will prompt for the width."
5133 (let ((col (org-table-current-column))
5134 (min 1e999) ; 1e999 will be converted to infinity
5135 (max -1e999) ; which is the desired result
5136 (table (org-table-to-lisp))
5139 (read-number "Length of column " 12))
5142 ;; Skip any hline a the top of table.
5143 (while (eq (car table) 'hline) (setq table (cdr table)))
5144 ;; Skip table header if any.
5145 (dolist (x (or (cdr (memq 'hline table)) table))
5147 (setq x (nth (1- col) x))
5149 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5151 (setq x (string-to-number x))
5152 (when (> min x) (setq min x))
5153 (when (< max x) (setq max x)))))
5154 (org-table-insert-column)
5155 (org-table-move-column-right)
5156 (org-table-store-formulas
5159 (number-to-string (1+ col))
5160 (format "'(%s $%s %s %s %s)"
5161 "orgtbl-ascii-draw" col min max length))
5162 (org-table-get-stored-formulas)))
5163 (org-table-recalculate t)))
5165 ;; Example of extension: unicode characters
5166 ;; Here are two examples of different styles.
5168 ;; Unicode block characters are used to give a smooth effect.
5169 ;; See http://en.wikipedia.org/wiki/Block_Elements
5170 ;; Use one of those drawing functions
5171 ;; - orgtbl-ascii-draw (the default ascii)
5172 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5173 ;; - orgtbl-uc-draw-cont (smooth unicode)
5175 ;; This is best viewed with the "DejaVu Sans Mono" font
5176 ;; (use M-x set-default-font).
5178 (defun orgtbl-uc-draw-grid (value min max &optional width)
5179 "Draw a bar in a table using block unicode characters.
5180 It is a variant of orgtbl-ascii-draw with Unicode block
5181 characters, for a smooth display. Bars appear as grids (to the
5182 extent the font allows)."
5183 ;; http://en.wikipedia.org/wiki/Block_Elements
5184 ;; best viewed with the "DejaVu Sans Mono" font.
5185 (orgtbl-ascii-draw value min max width
5186 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5188 (defun orgtbl-uc-draw-cont (value min max &optional width)
5189 "Draw a bar in a table using block unicode characters.
5190 It is a variant of orgtbl-ascii-draw with Unicode block
5191 characters, for a smooth display. Bars are solid (to the extent
5193 (orgtbl-ascii-draw value min max width
5194 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5196 (defun org-table-get-remote-range (name-or-id form)
5197 "Get a field value or a list of values in a range from table at ID.
5199 NAME-OR-ID may be the name of a table in the current file as set
5200 by a \"#+NAME:\" directive. The first table following this line
5201 will then be used. Alternatively, it may be an ID referring to
5202 any entry, also in a different file. In this case, the first
5203 table in that entry will be referenced.
5204 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5205 \"@I$2..@II$2\". All the references must be absolute, not relative.
5207 The return value is either a single string for a single field, or a
5208 list of the fields in the rectangle."
5210 (let ((case-fold-search t) (id-loc nil)
5211 ;; Protect a bunch of variables from being overwritten
5212 ;; by the context of the remote table
5213 org-table-column-names org-table-column-name-regexp
5214 org-table-local-parameters org-table-named-field-locations
5215 org-table-current-line-types org-table-current-begin-line
5216 org-table-current-begin-pos org-table-dlines
5217 org-table-current-ncol
5218 org-table-hlines org-table-last-alignment
5219 org-table-last-column-widths org-table-last-alignment
5220 org-table-last-column-widths tbeg
5222 (setq form (org-table-convert-refs-to-rc form))
5227 (goto-char (point-min))
5228 (if (re-search-forward
5229 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5230 (regexp-quote name-or-id) "[ \t]*$")
5232 (setq buffer (current-buffer) loc (match-beginning 0))
5233 (setq id-loc (org-id-find name-or-id 'marker))
5234 (unless (and id-loc (markerp id-loc))
5235 (user-error "Can't find remote table \"%s\"" name-or-id))
5236 (setq buffer (marker-buffer id-loc)
5237 loc (marker-position id-loc))
5238 (move-marker id-loc nil)))
5239 (with-current-buffer buffer
5245 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5246 (not (match-beginning 1)))
5247 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5248 (setq tbeg (point-at-bol))
5249 (org-table-get-specials)
5250 (setq form (org-table-formula-substitute-names
5251 (org-table-formula-handle-first/last-rc form)))
5252 (if (and (string-match org-table-range-regexp form)
5253 (> (length (match-string 0 form)) 1))
5255 (org-table-get-range (match-string 0 form) tbeg 1))
5258 (defun org-table-remote-reference-indirection (form)
5259 "Return formula with table remote references substituted by indirection.
5260 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5261 This indirection works only with the format @ROW$COLUMN. The
5262 format \"B3\" is not supported because it can not be
5263 distinguished from a plain table name or ID."
5265 (while (string-match (concat
5266 ;; Same as in `org-table-eval-formula'.
5267 "\\<remote([ \t]*\\("
5268 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5270 ;; Same as in `org-table-eval-formula'.
5271 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5274 ;; The position of the character as far as possible to the right
5275 ;; that will not be replaced and particularly not be shifted by
5277 (setq start (match-beginning 1))
5278 ;; Substitute the remote reference with the value found in the
5283 (org-table-get-range (org-table-formula-handle-first/last-rc
5284 (match-string 1 form))))
5288 (defmacro org-define-lookup-function (mode)
5289 (let ((mode-str (symbol-name mode))
5290 (first-p (equal mode 'first))
5291 (all-p (equal mode 'all)))
5292 (let ((plural-str (if all-p "s" "")))
5293 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5294 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5295 If R-LIST is nil, return matching element%s of S-LIST.
5296 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5297 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5298 This function is generated by a call to the macro `org-define-lookup-function'."
5299 mode-str plural-str plural-str plural-str)
5300 (let ,(let ((lvars '((p (or predicate 'equal))
5302 (rl (or r-list s-list))
5304 (if first-p (add-to-list 'lvars '(match-p nil)))
5306 (while ,(if first-p '(and (not match-p) sl) 'sl)
5308 (if (funcall p val (car sl))
5310 ,(if first-p '(setq match-p t))
5311 (let ((rval (car rl)))
5312 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5313 (setq sl (cdr sl) rl (cdr rl))))
5316 (org-define-lookup-function first)
5317 (org-define-lookup-function last)
5318 (org-define-lookup-function all)
5320 (provide 'org-table)
5323 ;; generated-autoload-file: "org-loaddefs.el"
5326 ;;; org-table.el ends here