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 aa2u
"ext:ascii-art-to-unicode" ())
44 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
48 (defvar constants-unit-system
)
49 (defvar org-table-follow-field-mode
)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, otherwise, if table is not sent, the functions
57 (defvar org-table-TBLFM-begin-regexp
"|\n[ \t]*#\\+TBLFM: ")
59 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
60 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
61 In the optimized version, the table editor takes over all simple keys that
62 normally just insert a character. In tables, the characters are inserted
63 in a way to minimize disturbing the table structure (i.e. in overwrite mode
64 for empty fields). Outside tables, the correct binding of the keys is
67 The default for this option is t if the optimized version is also used in
68 Org-mode. See the variable `org-enable-table-editor' for details. Changing
69 this variable requires a restart of Emacs to become effective."
73 (defcustom orgtbl-radio-table-templates
74 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
75 % END RECEIVE ORGTBL %n
77 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
80 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
81 @c END RECEIVE ORGTBL %n
83 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
86 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
87 <!-- END RECEIVE ORGTBL %n -->
89 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
92 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
93 #+ END RECEIVE ORGTBL %n
95 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
98 "Templates for radio tables in different major modes.
99 Each template must define lines that will be treated as a comment and that
100 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
101 lines where \"%n\" will be replaced with the name of the table during
102 insertion of the template. The transformed table will later be inserted
105 The template should also contain a minimal table in a multiline comment.
106 If multiline comments are not possible in the buffer language,
107 you can pack it into a string that will not be used when the code
108 is compiled or executed. Above the table will you need a line with
109 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
110 convert the table into a data structure useful in the
111 language of the buffer. Check the manual for the section on
112 \"Translator functions\", and more generally check out
113 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
115 All occurrences of %n in a template will be replaced with the name of the
116 table, obtained by prompting the user."
119 (list (symbol :tag
"Major mode")
120 (string :tag
"Format"))))
122 (defgroup org-table-settings nil
123 "Settings for tables in Org-mode."
124 :tag
"Org Table Settings"
127 (defcustom org-table-default-size
"5x2"
128 "The default size for newly created tables, Columns x Rows."
129 :group
'org-table-settings
132 (defcustom org-table-number-regexp
133 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
134 "Regular expression for recognizing numbers in table columns.
135 If a table column contains mostly numbers, it will be aligned to the
136 right. If not, it will be aligned to the left.
138 The default value of this option is a regular expression which allows
139 anything which looks remotely like a number as used in scientific
140 context. For example, all of the following will be considered a
142 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
144 Other options offered by the customize interface are more restrictive."
145 :group
'org-table-settings
147 (const :tag
"Positive Integers"
149 (const :tag
"Integers"
151 (const :tag
"Floating Point Numbers"
152 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
153 (const :tag
"Floating Point Number or Integer"
154 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
155 (const :tag
"Exponential, Floating point, Integer"
156 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
157 (const :tag
"Very General Number-Like, including hex and Calc radix"
158 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
159 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
160 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
161 (string :tag
"Regexp:")))
163 (defcustom org-table-number-fraction
0.5
164 "Fraction of numbers in a column required to make the column align right.
165 In a column all non-white fields are considered. If at least
166 this fraction of fields is matched by `org-table-number-regexp',
167 alignment to the right border applies."
168 :group
'org-table-settings
171 (defgroup org-table-editing nil
172 "Behavior of tables during editing in Org-mode."
173 :tag
"Org Table Editing"
176 (defcustom org-table-automatic-realign t
177 "Non-nil means automatically re-align table when pressing TAB or RETURN.
178 When nil, aligning is only done with \\[org-table-align], or after column
180 :group
'org-table-editing
183 (defcustom org-table-auto-blank-field t
184 "Non-nil means automatically blank table field when starting to type into it.
185 This only happens when typing immediately after a field motion
186 command (TAB, S-TAB or RET).
187 Only relevant when `org-enable-table-editor' is equal to `optimized'."
188 :group
'org-table-editing
191 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
192 "Non-nil means automatically exit the follow mode.
193 When nil, the follow mode will stay on and be active in any table
194 the cursor enters. Since the table follow filed mode messes with the
195 window configuration, it is not recommended to set this variable to nil,
196 except maybe locally in a special file that has mostly tables with long
202 (defcustom org-table-fix-formulas-confirm nil
203 "Whether the user should confirm when Org fixes formulas."
204 :group
'org-table-editing
207 (const :tag
"with yes-or-no" yes-or-no-p
)
208 (const :tag
"with y-or-n" y-or-n-p
)
209 (const :tag
"no confirmation" nil
)))
210 (put 'org-table-fix-formulas-confirm
212 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
214 (defcustom org-table-tab-jumps-over-hlines t
215 "Non-nil means tab in the last column of a table with jump over a hline.
216 If a horizontal separator line is following the current line,
217 `org-table-next-field' can either create a new row before that line, or jump
218 over the line. When this option is nil, a new line will be created before
220 :group
'org-table-editing
223 (defgroup org-table-calculation nil
224 "Options concerning tables in Org-mode."
225 :tag
"Org Table Calculation"
228 (defcustom org-table-use-standard-references
'from
229 "Should org-mode work with table references like B3 instead of @3$2?
232 from accept as input, do not present for editing
233 t accept as input and present for editing"
234 :group
'org-table-calculation
236 (const :tag
"Never, don't even check user input for them" nil
)
237 (const :tag
"Always, both as user input, and when editing" t
)
238 (const :tag
"Convert user input, don't offer during editing" from
)))
240 (defcustom org-table-copy-increment t
241 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
242 :group
'org-table-calculation
244 :package-version
'(Org .
"8.3")
246 (const :tag
"Use the difference between the current and the above fields" t
)
247 (integer :tag
"Use a number" 1)
248 (const :tag
"Don't increment the value when copying a field" nil
)))
250 (defcustom org-calc-default-modes
251 '(calc-internal-prec 12
252 calc-float-format
(float 8)
255 calc-symbolic-mode nil
256 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
257 calc-display-working-message t
259 "List with Calc mode settings for use in `calc-eval' for table formulas.
260 The list must contain alternating symbols (Calc modes variables and values).
261 Don't remove any of the default settings, just change the values. Org-mode
262 relies on the variables to be present in the list."
263 :group
'org-table-calculation
266 (defcustom org-table-duration-custom-format
'hours
267 "Format for the output of calc computations like $1+$2;t.
268 The default value is 'hours, and will output the results as a
269 number of hours. Other allowed values are 'seconds, 'minutes and
270 'days, and the output will be a fraction of seconds, minutes or
272 :group
'org-table-calculation
274 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
275 (symbol :tag
"Minutes" 'minutes
)
276 (symbol :tag
"Hours " 'hours
)
277 (symbol :tag
"Days " 'days
)))
279 (defcustom org-table-formula-field-format
"%s"
280 "Format for fields which contain the result of a formula.
281 For example, using \"~%s~\" will display the result within tilde
282 characters. Beware that modifying the display can prevent the
283 field from being used in another formula."
284 :group
'org-table-settings
288 (defcustom org-table-formula-evaluate-inline t
289 "Non-nil means TAB and RET evaluate a formula in current table field.
290 If the current field starts with an equal sign, it is assumed to be a formula
291 which should be evaluated as described in the manual and in the documentation
292 string of the command `org-table-eval-formula'. This feature requires the
294 When this variable is nil, formula calculation is only available through
295 the command \\[org-table-eval-formula]."
296 :group
'org-table-calculation
299 (defcustom org-table-formula-use-constants t
300 "Non-nil means interpret constants in formulas in tables.
301 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
302 by the value given in `org-table-formula-constants', or by a value obtained
303 from the `constants.el' package."
304 :group
'org-table-calculation
307 (defcustom org-table-formula-constants nil
308 "Alist with constant names and values, for use in table formulas.
309 The car of each element is a name of a constant, without the `$' before it.
310 The cdr is the value as a string. For example, if you'd like to use the
311 speed of light in a formula, you would configure
313 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
315 and then use it in an equation like `$1*$c'.
317 Constants can also be defined on a per-file basis using a line like
319 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
320 :group
'org-table-calculation
322 (cons (string :tag
"name")
323 (string :tag
"value"))))
325 (defcustom org-table-allow-automatic-line-recalculation t
326 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
327 Automatically means when TAB or RET or C-c C-c are pressed in the line."
328 :group
'org-table-calculation
331 (defcustom org-table-error-on-row-ref-crossing-hline t
332 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
336 (defcustom org-table-relative-ref-may-cross-hline t
337 "Non-nil means relative formula references may cross hlines.
338 Here are the allowed values:
340 nil Relative references may not cross hlines. They will reference the
341 field next to the hline instead. Coming from below, the reference
342 will be to the field below the hline. Coming from above, it will be
344 t Relative references may cross hlines.
345 error An attempt to cross a hline will throw an error.
347 It is probably good to never set this variable to nil, for the sake of
348 portability of tables."
349 :group
'org-table-calculation
351 (const :tag
"Allow to cross" t
)
352 (const :tag
"Stick to hline" nil
)
353 (const :tag
"Error on attempt to cross" error
)))
355 (defgroup org-table-import-export nil
356 "Options concerning table import and export in Org-mode."
357 :tag
"Org Table Import Export"
360 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
361 "Default export parameters for `org-table-export'.
362 These can be overridden for a specific table by setting the
363 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
364 radio tables for the different export transformations and
365 available parameters."
366 :group
'org-table-import-export
369 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
370 "Detects a table line marked for automatic recalculation.")
371 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
372 "Detects a table line marked for automatic recalculation.")
373 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
374 "Detects a table line marked for automatic recalculation.")
375 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
376 "Searching from within a table (any type) this finds the first line outside the table.")
377 (defvar org-table-last-highlighted-reference nil
)
378 (defvar org-table-formula-history nil
)
380 (defvar org-table-column-names nil
381 "Alist with column names, derived from the `!' line.")
382 (defvar org-table-column-name-regexp nil
383 "Regular expression matching the current column names.")
384 (defvar org-table-local-parameters nil
385 "Alist with parameter names, derived from the `$' line.")
386 (defvar org-table-named-field-locations nil
387 "Alist with locations of named fields.")
389 (defvar org-table-current-line-types nil
390 "Table row types, non-nil only for the duration of a command.")
391 (defvar org-table-current-begin-line nil
392 "Table begin line, non-nil only for the duration of a command.")
393 (defvar org-table-current-begin-pos nil
394 "Table begin position, non-nil only for the duration of a command.")
395 (defvar org-table-current-ncol nil
396 "Number of columns in table, non-nil only for the duration of a command.")
397 (defvar org-table-dlines nil
398 "Vector of data line line numbers in the current table.")
399 (defvar org-table-hlines nil
400 "Vector of hline line numbers in the current table.")
402 (defconst org-table-range-regexp
403 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
405 "Regular expression for matching ranges in formulas.")
407 (defconst org-table-range-regexp2
409 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
411 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
412 "Match a range for reference display.")
414 (defun org-table-colgroup-line-p (line)
415 "Is this a table line colgroup information?"
417 (and (string-match "[<>]\\|&[lg]t;" line
)
418 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
424 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
425 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
427 (defun org-table-cookie-line-p (line)
428 "Is this a table line with only alignment/width cookies?"
430 (and (string-match "[<>]\\|&[lg]t;" line
)
432 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
433 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
434 (not (delq nil
(mapcar
436 (not (or (equal s
"")
438 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
440 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
442 (org-split-string (match-string 1 line
)
443 "[ \t]*|[ \t]*")))))))
445 (defvar org-table-clean-did-remove-column nil
) ; dynamically scoped
446 (defun org-table-clean-before-export (lines &optional maybe-quoted
)
447 "Check if the table has a marking column.
448 If yes remove the column and the special lines."
449 (let ((special (if maybe-quoted
450 "^[ \t]*| *\\\\?[\#!$*_^/ ] *|"
451 "^[ \t]*| *[\#!$*_^/ ] *|"))
452 (ignore (if maybe-quoted
453 "^[ \t]*| *\\\\?[!$_^/] *|"
454 "^[ \t]*| *[!$_^/] *|")))
455 (setq org-table-clean-did-remove-column
459 (or (string-match org-table-hline-regexp line
)
460 (string-match special line
)))
466 ((or (org-table-colgroup-line-p line
) ;; colgroup info
467 (org-table-cookie-line-p line
) ;; formatting cookies
468 (and org-table-clean-did-remove-column
469 (string-match ignore line
))) ;; non-exportable data
471 ((and org-table-clean-did-remove-column
472 (or (string-match "^\\([ \t]*\\)|-+\\+" line
)
473 (string-match "^\\([ \t]*\\)|[^|]*|" line
)))
474 ;; remove the first column
475 (replace-match "\\1|" t nil line
))
479 (defconst org-table-translate-regexp
480 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
481 "Match a reference that needs translation, for reference display.")
484 (defun org-table-create-with-table.el
()
485 "Use the table.el package to insert a new table.
486 If there is already a table at point, convert between Org-mode tables
487 and table.el tables."
492 (if (y-or-n-p "Convert table to Org-mode table? ")
493 (org-table-convert)))
495 (when (y-or-n-p "Convert table to table.el table? ")
497 (org-table-convert)))
498 (t (call-interactively 'table-insert
))))
501 (defun org-table-create-or-convert-from-region (arg)
502 "Convert region to table, or create an empty table.
503 If there is an active region, convert it to a table, using the function
504 `org-table-convert-region'. See the documentation of that function
505 to learn how the prefix argument is interpreted to determine the field
507 If there is no such region, create an empty table with `org-table-create'."
509 (if (org-region-active-p)
510 (org-table-convert-region (region-beginning) (region-end) arg
)
511 (org-table-create arg
)))
514 (defun org-table-create (&optional size
)
515 "Query for a size and insert a table skeleton.
516 SIZE is a string Columns x Rows like for example \"3x2\"."
519 (setq size
(read-string
520 (concat "Table size Columns x Rows [e.g. "
521 org-table-default-size
"]: ")
522 "" nil org-table-default-size
)))
525 (indent (make-string (current-column) ?\
))
526 (split (org-split-string size
" *x *"))
527 (rows (string-to-number (nth 1 split
)))
528 (columns (string-to-number (car split
)))
529 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
531 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
532 (point-at-bol) (point)))
533 (beginning-of-line 1)
535 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
536 (dotimes (i rows
) (insert line
))
539 ;; Insert a hline after the first row.
547 (defun org-table-convert-region (beg0 end0
&optional separator
)
548 "Convert region to a table.
549 The region goes from BEG0 to END0, but these borders will be moved
550 slightly, to make sure a beginning of line in the first line is included.
552 SEPARATOR specifies the field separator in the lines. It can have the
555 '(4) Use the comma as a field separator
556 '(16) Use a TAB as field separator
557 '(64) Prompt for a regular expression as field separator
558 integer When a number, use that many spaces as field separator
559 regexp When a regular expression, use it to match the separator
560 nil When nil, the command tries to be smart and figure out the
561 separator in the following way:
562 - when each line contains a TAB, assume TAB-separated material
563 - when each line contains a comma, assume CSV material
564 - else, assume one or more SPACE characters as separator."
566 (let* ((beg (min beg0 end0
))
567 (end (max beg0 end0
))
569 (if (equal separator
'(64))
570 (setq separator
(read-regexp "Regexp for field separator")))
572 (beginning-of-line 1)
573 (setq beg
(point-marker))
575 (if (bolp) (backward-char 1) (end-of-line 1))
576 (setq end
(point-marker))
577 ;; Get the right field separator
582 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
583 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
586 (if (equal separator
'(4))
587 (while (< (point) end
)
588 ;; parse the csv stuff
590 ((looking-at "^") (insert "| "))
591 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
592 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
593 (replace-match "\\1")
594 (if (looking-at "\"") (insert "\"")))
595 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
596 ((looking-at "[ \t]*,") (replace-match " | "))
597 (t (beginning-of-line 2))))
599 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
600 ((equal separator
'(16)) "^\\|\t")
601 ((integerp separator
)
603 (user-error "Number of spaces in separator must be >= 1")
604 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
606 (format "^ *\\|%s" separator
))
607 (t (error "This should not happen"))))
608 (while (re-search-forward re end t
)
609 (replace-match "| " t t
)))
614 (defun org-table-import (file arg
)
615 "Import FILE as a table.
616 The file is assumed to be tab-separated. Such files can be produced by most
617 spreadsheet and database applications. If no tabs (at least one per line)
618 are found, lines will be split on whitespace into fields."
620 (or (bolp) (newline))
623 (insert-file-contents file
)
624 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
627 (defvar org-table-last-alignment
)
628 (defvar org-table-last-column-widths
)
630 (defun org-table-export (&optional file format
)
631 "Export table to a file, with configurable format.
632 Such a file can be imported into usual spreadsheet programs.
634 FILE can be the output file name. If not given, it will be taken
635 from a TABLE_EXPORT_FILE property in the current entry or higher
636 up in the hierarchy, or the user will be prompted for a file
637 name. FORMAT can be an export format, of the same kind as it
638 used when `orgtbl-mode' sends a table in a different format.
640 The command suggests a format depending on TABLE_EXPORT_FORMAT,
641 whether it is set locally or up in the hierarchy, then on the
642 extension of the given file name, and finally on the variable
643 `org-table-export-default-format'."
645 (unless (org-at-table-p) (user-error "No table at point"))
646 (org-table-align) ;; make sure we have everything we need
647 (let* ((beg (org-table-begin))
648 (end (org-table-end))
649 (txt (buffer-substring-no-properties beg end
))
650 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
651 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
652 "orgtbl-to-latex" "orgtbl-to-html"
653 "orgtbl-to-generic" "orgtbl-to-texinfo"
656 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
657 buf deffmt-readable fileext
)
659 (setq file
(read-file-name "Export table to: "))
660 (unless (or (not (file-exists-p file
))
661 (y-or-n-p (format "Overwrite file %s? " file
)))
662 (user-error "File not written")))
663 (if (file-directory-p file
)
664 (user-error "This is a directory path, not a file"))
665 (if (and (buffer-file-name)
666 (equal (file-truename file
)
667 (file-truename (buffer-file-name))))
668 (user-error "Please specify a file name that is different from current"))
669 (setq fileext
(concat (file-name-extension file
) "$"))
671 (setq deffmt-readable
672 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
673 org-table-export-default-format
))
674 (while (string-match "\t" deffmt-readable
)
675 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
676 (while (string-match "\n" deffmt-readable
)
677 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
678 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
679 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
680 (let* ((transform (intern (match-string 1 format
)))
681 (params (if (match-end 2)
682 (read (concat "(" (match-string 2 format
) ")"))))
683 (skip (plist-get params
:skip
))
684 (skipcols (plist-get params
:skipcols
))
685 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
686 (lines (org-table-clean-before-export lines
))
687 (i0 (if org-table-clean-did-remove-column
2 1))
690 (if (string-match org-table-hline-regexp x
)
693 (org-split-string (org-trim x
) "\\s-*|\\s-*")
696 (fun (if (= i0
2) 'cdr
'identity
))
697 (org-table-last-alignment
698 (org-remove-by-index (funcall fun org-table-last-alignment
)
700 (org-table-last-column-widths
701 (org-remove-by-index (funcall fun org-table-last-column-widths
)
704 (unless (fboundp transform
)
705 (user-error "No such transformation function %s" transform
))
706 (setq txt
(funcall transform table params
))
708 (with-current-buffer (find-file-noselect file
)
709 (setq buf
(current-buffer))
715 (message "Export done."))
716 (user-error "TABLE_EXPORT_FORMAT invalid"))))
718 (defvar org-table-aligned-begin-marker
(make-marker)
719 "Marker at the beginning of the table last aligned.
720 Used to check if cursor still is in that table, to minimize realignment.")
721 (defvar org-table-aligned-end-marker
(make-marker)
722 "Marker at the end of the table last aligned.
723 Used to check if cursor still is in that table, to minimize realignment.")
724 (defvar org-table-last-alignment nil
725 "List of flags for flushright alignment, from the last re-alignment.
726 This is being used to correctly align a single field after TAB or RET.")
727 (defvar org-table-last-column-widths nil
728 "List of max width of fields in each column.
729 This is being used to correctly align a single field after TAB or RET.")
730 (defvar org-table-formula-debug nil
731 "Non-nil means debug table formulas.
732 When nil, simply write \"#ERROR\" in corrupted fields.")
733 (make-variable-buffer-local 'org-table-formula-debug
)
734 (defvar org-table-overlay-coordinates nil
735 "Overlay coordinates after each align of a table.")
736 (make-variable-buffer-local 'org-table-overlay-coordinates
)
738 (defvar org-last-recalc-line nil
)
739 (defvar org-table-do-narrow t
) ; for dynamic scoping
740 (defconst org-narrow-column-arrow
"=>"
741 "Used as display property in narrowed table columns.")
744 (defun org-table-align ()
745 "Align the table at point by aligning all vertical bars."
749 (beg (org-table-begin))
750 (end (org-table-end))
751 ;; Current cursor position
752 (linepos (org-current-line))
753 (colpos (org-table-current-column))
754 (winstart (window-start))
755 (winstartline (org-current-line (min winstart
(1- (point-max)))))
756 lines
(new "") lengths l typenums ty fields maxfields i
764 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
766 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
767 emptystrings links dates emph raise narrow
768 falign falign1 fmax f1 len c e space
)
770 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
771 ;; Check if we have links or dates
773 (setq links
(re-search-forward org-bracket-link-regexp end t
))
775 (setq emph
(and org-hide-emphasis-markers
776 (re-search-forward org-emph-re end t
)))
778 (setq raise
(and org-use-sub-superscripts
779 (re-search-forward org-match-substring-regexp end t
)))
781 (setq dates
(and org-display-custom-times
782 (re-search-forward org-ts-regexp-both end t
)))
783 ;; Make sure the link properties are right
784 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
785 ;; Make sure the date properties are right
786 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
787 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
788 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
790 ;; Check if we are narrowing any columns
792 (setq narrow
(and org-table-do-narrow
793 org-format-transports-properties-p
794 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
796 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
799 (setq lines
(org-split-string
800 (buffer-substring beg end
) "\n"))
801 ;; Store the indentation of the first line
802 (if (string-match "^ *" (car lines
))
803 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
804 ;; Mark the hlines by setting the corresponding element to nil
805 ;; At the same time, we remove trailing space.
806 (setq lines
(mapcar (lambda (l)
807 (if (string-match "^ *|-" l
)
809 (if (string-match "[ \t]+$" l
)
810 (substring l
0 (match-beginning 0))
813 ;; Get the data fields by splitting the lines.
816 (org-split-string l
" *| *"))
817 (delq nil
(copy-sequence lines
))))
818 ;; How many fields in the longest line?
820 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
822 (kill-region beg end
)
823 (org-table-create org-table-default-size
)
824 (user-error "Empty table - created default table")))
825 ;; A list of empty strings to fill any short rows on output
826 (setq emptystrings
(make-list maxfields
""))
827 ;; Check for special formatting.
829 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
830 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
831 ;; Check if there is an explicit width specified
833 (when (or narrow falign
)
834 (setq c column fmax nil falign1 nil
)
837 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
838 (if (match-end 1) (setq falign1
(match-string 1 e
)))
839 (if (and org-table-do-narrow
(match-end 2))
840 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
841 ;; Find fields that are wider than fmax, and shorten them
843 (loop for xx in column do
844 (when (and (stringp xx
)
845 (> (org-string-width xx
) fmax
))
846 (org-add-props xx nil
848 (concat "Clipped table field, use C-c ` to edit. Full value is:\n"
849 (org-no-properties (copy-sequence xx
))))
850 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
852 (user-error "Cannot narrow field starting with wide link \"%s\""
853 (match-string 0 xx
)))
854 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
855 (add-text-properties (- f1
2) f1
856 (list 'display org-narrow-column-arrow
)
858 ;; Get the maximum width for each column
859 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
861 ;; Get the fraction of numbers, to decide about alignment of the column
863 (push (equal (downcase falign1
) "r") typenums
)
864 (setq cnt
0 frac
0.0)
865 (loop for x in column do
868 (setq frac
( / (+ (* frac cnt
)
869 (if (string-match org-table-number-regexp x
) 1 0))
870 (setq cnt
(1+ cnt
))))))
871 (push (>= frac org-table-number-fraction
) typenums
)))
872 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
874 ;; Store the alignment of this table, for later editing of single fields
875 (setq org-table-last-alignment typenums
876 org-table-last-column-widths lengths
)
878 ;; With invisible characters, `format' does not get the field width right
879 ;; So we need to make these fields wide by hand.
880 (when (or links emph raise
)
881 (loop for i from
0 upto
(1- maxfields
) do
882 (setq len
(nth i lengths
))
883 (loop for j from
0 upto
(1- (length fields
)) do
884 (setq c
(nthcdr i
(car (nthcdr j fields
))))
885 (if (and (stringp (car c
))
886 (or (text-property-any 0 (length (car c
))
887 'invisible
'org-link
(car c
))
888 (text-property-any 0 (length (car c
))
889 'org-dwidth t
(car c
)))
890 (< (org-string-width (car c
)) len
))
892 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
893 (setcar c
(if (nth i typenums
)
894 (concat space
(car c
))
895 (concat (car c
) space
))))))))
897 ;; Compute the formats needed for output of the table
898 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
899 (while (setq l
(pop lengths
))
900 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
901 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
902 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
903 (setq rfmt
(concat rfmt
"\n")
904 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
908 (if l
(apply 'format rfmt
909 (append (pop fields
) emptystrings
))
912 (move-marker org-table-aligned-begin-marker
(point))
914 ;; Replace the old one
915 (delete-region (point) end
)
916 (move-marker end nil
)
917 (move-marker org-table-aligned-end-marker
(point))
918 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
919 (goto-char org-table-aligned-begin-marker
)
920 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
921 ;; Try to move to the old location
922 (org-goto-line winstartline
)
923 (setq winstart
(point-at-bol))
924 (org-goto-line linepos
)
925 (when (eq (window-buffer (selected-window)) (current-buffer))
926 (set-window-start (selected-window) winstart
'noforce
))
927 (org-table-goto-column colpos
)
928 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
929 (setq org-table-may-need-update nil
)
933 (defun org-table-begin (&optional table-type
)
934 "Find the beginning of the table and return its position.
935 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
937 (if (not (re-search-backward
938 (if table-type org-table-any-border-regexp
939 org-table-border-regexp
)
941 (progn (goto-char (point-min)) (point))
942 (goto-char (match-beginning 0))
943 (beginning-of-line 2)
947 (defun org-table-end (&optional table-type
)
948 "Find the end of the table and return its position.
949 With argument TABLE-TYPE, go to the end of a table.el-type table."
951 (if (not (re-search-forward
952 (if table-type org-table-any-border-regexp
953 org-table-border-regexp
)
955 (goto-char (point-max))
956 (goto-char (match-beginning 0)))
960 (defun org-table-justify-field-maybe (&optional new
)
961 "Justify the current field, text to left, number to right.
962 Optional argument NEW may specify text to replace the current field content."
964 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
965 ((org-at-table-hline-p))
967 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
969 (< (point) org-table-aligned-begin-marker
)
970 (>= (point) org-table-aligned-end-marker
)))
971 ;; This is not the same table, force a full re-align
972 (setq org-table-may-need-update t
))
973 (t ;; realign the current field, based on previous full realign
974 (let* ((pos (point)) s
975 (col (org-table-current-column))
976 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
979 (skip-chars-backward "^|\n")
980 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
982 (setq s
(match-string 1)
984 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
985 e
(not (= (match-beginning 2) (match-end 2))))
986 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
987 l
(if e
"|" (setq org-table-may-need-update t
) ""))
990 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
991 (setq n
(format f new
))
992 (setq n
(concat new
"|") org-table-may-need-update t
)))
993 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
995 (let (org-table-may-need-update)
996 (replace-match n t t
))))
997 (setq org-table-may-need-update t
))
1001 (defun org-table-next-field ()
1002 "Go to the next field in the current table, creating new lines as needed.
1003 Before doing so, re-align the table if necessary."
1005 (org-table-maybe-eval-formula)
1006 (org-table-maybe-recalculate-line)
1007 (if (and org-table-automatic-realign
1008 org-table-may-need-update
)
1010 (let ((end (org-table-end)))
1011 (if (org-at-table-hline-p)
1015 (re-search-forward "|" end
)
1016 (if (looking-at "[ \t]*$")
1017 (re-search-forward "|" end
))
1018 (if (and (looking-at "-")
1019 org-table-tab-jumps-over-hlines
1020 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1021 (goto-char (match-beginning 1)))
1022 (if (looking-at "-")
1024 (beginning-of-line 0)
1025 (org-table-insert-row 'below
))
1026 (if (looking-at " ") (forward-char 1))))
1028 (org-table-insert-row 'below
)))))
1031 (defun org-table-previous-field ()
1032 "Go to the previous field in the table.
1033 Before doing so, re-align the table if necessary."
1035 (org-table-justify-field-maybe)
1036 (org-table-maybe-recalculate-line)
1037 (if (and org-table-automatic-realign
1038 org-table-may-need-update
)
1040 (if (org-at-table-hline-p)
1044 (re-search-backward "|" (org-table-begin))
1045 (re-search-backward "|" (org-table-begin)))
1046 (error (user-error "Cannot move to previous table field")))
1047 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1048 (re-search-backward "|" (org-table-begin)))
1049 (if (looking-at "| ?")
1050 (goto-char (match-end 0))))
1052 (defun org-table-beginning-of-field (&optional n
)
1053 "Move to the end of the current table field.
1054 If already at or after the end, move to the end of the next table field.
1055 With numeric argument N, move N-1 fields forward first."
1057 (let ((pos (point)))
1060 (org-table-previous-field))
1061 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1062 (user-error "No more table fields before the current")
1063 (goto-char (match-end 0))
1064 (and (looking-at " ") (forward-char 1)))
1065 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1067 (defun org-table-end-of-field (&optional n
)
1068 "Move to the beginning of the current table field.
1069 If already at or before the beginning, move to the beginning of the
1071 With numeric argument N, move N-1 fields backward first."
1073 (let ((pos (point)))
1076 (org-table-next-field))
1077 (when (re-search-forward "|" (point-at-eol 1) t
)
1079 (skip-chars-backward " ")
1080 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1082 (if (<= (point) pos
) (org-table-end-of-field 2))))
1085 (defun org-table-next-row ()
1086 "Go to the next row (same column) in the current table.
1087 Before doing so, re-align the table if necessary."
1089 (org-table-maybe-eval-formula)
1090 (org-table-maybe-recalculate-line)
1091 (if (or (looking-at "[ \t]*$")
1092 (save-excursion (skip-chars-backward " \t") (bolp)))
1094 (if (and org-table-automatic-realign
1095 org-table-may-need-update
)
1097 (let ((col (org-table-current-column)))
1098 (beginning-of-line 2)
1099 (if (or (not (org-at-table-p))
1100 (org-at-table-hline-p))
1102 (beginning-of-line 0)
1103 (org-table-insert-row 'below
)))
1104 (org-table-goto-column col
)
1105 (skip-chars-backward "^|\n\r")
1106 (if (looking-at " ") (forward-char 1)))))
1109 (defun org-table-copy-down (n)
1110 "Copy the value of the current field one row below.
1112 If the field at the cursor is empty, copy the content of the
1113 nearest non-empty field above. With argument N, use the Nth
1116 If the current field is not empty, it is copied down to the next
1117 row, and the cursor is moved with it. Therefore, repeating this
1118 command causes the column to be filled row-by-row.
1120 If the variable `org-table-copy-increment' is non-nil and the
1121 field is an integer or a timestamp, it will be incremented while
1122 copying. By default, increment by the difference between the
1123 value in the current field and the one in the field above. To
1124 increment using a fixed integer, set `org-table-copy-increment'
1125 to a number. In the case of a timestamp, increment by days."
1127 (let* ((colpos (org-table-current-column))
1128 (col (current-column))
1129 (field (save-excursion (org-table-get-field)))
1130 (field-up (or (save-excursion
1131 (org-table-get (1- (org-table-current-line))
1132 (org-table-current-column))) ""))
1133 (non-empty (string-match "[^ \t]" field
))
1134 (non-empty-up (string-match "[^ \t]" field-up
))
1135 (beg (org-table-begin))
1138 (org-table-check-inside-data-field)
1143 (while (progn (beginning-of-line 1)
1144 (re-search-backward org-table-dataline-regexp
1146 (org-table-goto-column colpos t
)
1147 (if (and (looking-at
1148 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1149 (<= (setq n
(1- n
)) 0))
1150 (throw 'exit
(match-string 1))))))
1153 (while (progn (beginning-of-line 1)
1154 (re-search-backward org-table-dataline-regexp
1156 (org-table-goto-column colpos t
)
1157 (if (and (looking-at
1158 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1159 (<= (setq n
(1- n
)) 0))
1160 (throw 'exit
(match-string 1))))))
1161 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1162 ;; Above field was not empty, go down to the next row
1163 (setq txt
(org-trim field
))
1164 (org-table-next-row)
1165 (org-table-blank-field))
1166 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1168 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1169 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1170 (string-match org-ts-regexp3 txt
))
1171 (- (org-time-string-to-absolute txt
)
1172 (org-time-string-to-absolute txt-up
)))
1173 ((string-match org-ts-regexp3 txt
) 1)
1174 (t (- (string-to-number txt
)
1175 (string-to-number txt-up
)))))
1178 (user-error "No non-empty field found")
1179 (if (and org-table-copy-increment
1180 (not (equal orig-n
0))
1181 (string-match "^[-+^/*0-9eE.]+$" txt
)
1182 (< (string-to-number txt
) 100000000))
1183 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1185 (org-move-to-column col
)
1186 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1187 (org-timestamp-up-day inc
)
1188 (org-table-maybe-recalculate-line))
1190 (org-move-to-column col
))))
1192 (defun org-table-check-inside-data-field (&optional noerror
)
1193 "Is point inside a table data field?
1194 I.e. not on a hline or before the first or after the last column?
1195 This actually throws an error, so it aborts the current command."
1196 (if (or (not (org-at-table-p))
1197 (= (org-table-current-column) 0)
1198 (org-at-table-hline-p)
1199 (looking-at "[ \t]*$"))
1202 (user-error "Not in table data field"))
1205 (defvar org-table-clip nil
1206 "Clipboard for table regions.")
1208 (defun org-table-get (line column
)
1209 "Get the field in table line LINE, column COLUMN.
1210 If LINE is larger than the number of data lines in the table, the function
1211 returns nil. However, if COLUMN is too large, we will simply return an
1213 If LINE is nil, use the current line.
1214 If column is nil, use the current column."
1215 (setq column
(or column
(org-table-current-column)))
1217 (and (or (not line
) (org-table-goto-line line
))
1218 (org-trim (org-table-get-field column
)))))
1220 (defun org-table-put (line column value
&optional align
)
1221 "Put VALUE into line LINE, column COLUMN.
1222 When ALIGN is set, also realign the table."
1223 (setq column
(or column
(org-table-current-column)))
1224 (prog1 (save-excursion
1225 (and (or (not line
) (org-table-goto-line line
))
1226 (progn (org-table-goto-column column nil
'force
) t
)
1227 (org-table-get-field column value
)))
1228 (and align
(org-table-align))))
1230 (defun org-table-current-line ()
1231 "Return the index of the current data line."
1232 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1234 (goto-char (org-table-begin))
1235 (while (and (re-search-forward org-table-dataline-regexp end t
)
1237 (< (point-at-eol) pos
))))
1240 (defun org-table-goto-line (N)
1241 "Go to the Nth data line in the current table.
1242 Return t when the line exists, nil if it does not exist."
1243 (goto-char (org-table-begin))
1244 (let ((end (org-table-end)) (cnt 0))
1245 (while (and (re-search-forward org-table-dataline-regexp end t
)
1246 (< (setq cnt
(1+ cnt
)) N
)))
1250 (defun org-table-blank-field ()
1251 "Blank the current table field or active region."
1253 (org-table-check-inside-data-field)
1254 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1255 (let (org-table-clip)
1256 (org-table-cut-region (region-beginning) (region-end)))
1257 (skip-chars-backward "^|")
1259 (if (looking-at "|[^|\n]+")
1260 (let* ((pos (match-beginning 0))
1261 (match (match-string 0))
1262 (len (org-string-width match
)))
1263 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1264 (goto-char (+ 2 pos
))
1265 (substring match
1)))))
1267 (defun org-table-get-field (&optional n replace
)
1268 "Return the value of the field in column N of current row.
1269 N defaults to current field.
1270 If REPLACE is a string, replace field with this value. The return value
1271 is always the old value."
1272 (and n
(org-table-goto-column n
))
1273 (skip-chars-backward "^|\n")
1275 (if (looking-at "|[^|\r\n]*")
1276 (let* ((pos (match-beginning 0))
1277 (val (buffer-substring (1+ pos
) (match-end 0))))
1279 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1281 (goto-char (min (point-at-eol) (+ 2 pos
)))
1283 (forward-char 1) ""))
1286 (defun org-table-field-info (arg)
1287 "Show info about the current field, and highlight any reference at point."
1289 (unless (org-at-table-p) (user-error "Not at a table"))
1290 (org-table-get-specials)
1292 (let* ((pos (point))
1293 (col (org-table-current-column))
1294 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1295 (name (car (rassoc (list (org-current-line) col
)
1296 org-table-named-field-locations
)))
1297 (eql (org-table-expand-lhs-ranges
1300 (cons (org-table-formula-handle-first/last-rc
1302 (org-table-get-stored-formulas))))
1303 (dline (org-table-current-dline))
1304 (ref (format "@%d$%d" dline col
))
1305 (ref1 (org-table-convert-refs-to-an ref
))
1306 (fequation (or (assoc name eql
) (assoc ref eql
)))
1307 (cequation (assoc (int-to-string col
) eql
))
1308 (eqn (or fequation cequation
)))
1309 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1310 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1313 (org-table-show-reference 'local
)
1315 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1317 (if cname
(concat " or $" cname
) "")
1319 (if name
(concat " or $" name
) "")
1320 ;; FIXME: formula info not correct if special table line
1322 (concat ", formula: "
1323 (org-table-formula-to-user
1325 (if (string-match "^[$@]"(car eqn
)) "" "$")
1326 (car eqn
) "=" (cdr eqn
))))
1329 (defun org-table-current-column ()
1330 "Find out which column we are in."
1332 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1334 (let ((cnt 0) (pos (point)))
1335 (beginning-of-line 1)
1336 (while (search-forward "|" pos t
)
1337 (setq cnt
(1+ cnt
)))
1338 (when (org-called-interactively-p 'interactive
)
1339 (message "In table column %d" cnt
))
1343 (defun org-table-current-dline ()
1344 "Find out what table data line we are in.
1345 Only data lines count for this."
1347 (when (org-called-interactively-p 'any
)
1348 (org-table-check-inside-data-field))
1350 (let ((cnt 0) (pos (point)))
1351 (goto-char (org-table-begin))
1352 (while (<= (point) pos
)
1353 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1354 (beginning-of-line 2))
1355 (when (org-called-interactively-p 'any
)
1356 (message "This is table line %d" cnt
))
1360 (defun org-table-goto-column (n &optional on-delim force
)
1361 "Move the cursor to the Nth column in the current table line.
1362 With optional argument ON-DELIM, stop with point before the left delimiter
1364 If there are less than N fields, just go to after the last delimiter.
1365 However, when FORCE is non-nil, create new columns if necessary."
1367 (beginning-of-line 1)
1369 (while (and (> (setq n
(1- n
)) -
1)
1370 (or (search-forward "|" (point-at-eol) t
)
1372 (progn (end-of-line 1)
1373 (skip-chars-backward "^|")
1376 (when (and force
(not (looking-at ".*|")))
1377 (save-excursion (end-of-line 1) (insert " | ")))
1380 (if (looking-at " ") (forward-char 1)))))
1383 (defun org-table-insert-column ()
1384 "Insert a new column into the table."
1386 (if (not (org-at-table-p))
1387 (user-error "Not at a table"))
1388 (org-table-find-dataline)
1389 (let* ((col (max 1 (org-table-current-column)))
1390 (beg (org-table-begin))
1391 (end (org-table-end))
1392 ;; Current cursor position
1393 (linepos (org-current-line))
1396 (while (< (point) end
)
1397 (if (org-at-table-hline-p)
1399 (org-table-goto-column col t
)
1401 (beginning-of-line 2))
1402 (move-marker end nil
)
1403 (org-goto-line linepos
)
1404 (org-table-goto-column colpos
)
1406 (when (or (not org-table-fix-formulas-confirm
)
1407 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1408 (org-table-fix-formulas "$" nil
(1- col
) 1)
1409 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1411 (defun org-table-find-dataline ()
1412 "Find a data line in the current table, which is needed for column commands."
1413 (if (and (org-at-table-p)
1414 (not (org-at-table-hline-p)))
1416 (let ((col (current-column))
1417 (end (org-table-end)))
1418 (org-move-to-column col
)
1419 (while (and (< (point) end
)
1420 (or (not (= (current-column) col
))
1421 (org-at-table-hline-p)))
1422 (beginning-of-line 2)
1423 (org-move-to-column col
))
1424 (if (and (org-at-table-p)
1425 (not (org-at-table-hline-p)))
1428 "Please position cursor in a data line for column operations")))))
1430 (defun org-table-line-to-dline (line &optional above
)
1431 "Turn a buffer line number into a data line number.
1432 If there is no data line in this line, return nil.
1433 If there is no matching dline (most likely te reference was a hline), the
1434 first dline below it is used. When ABOVE is non-nil, the one above is used."
1436 (let ((ll (length org-table-dlines
))
1442 (if (<= (aref org-table-dlines i
) line
)
1447 (if (>= (aref org-table-dlines i
) line
)
1453 (defun org-table-delete-column ()
1454 "Delete a column from the table."
1456 (if (not (org-at-table-p))
1457 (user-error "Not at a table"))
1458 (org-table-find-dataline)
1459 (org-table-check-inside-data-field)
1460 (let* ((col (org-table-current-column))
1461 (beg (org-table-begin))
1462 (end (org-table-end))
1463 ;; Current cursor position
1464 (linepos (org-current-line))
1467 (while (< (point) end
)
1468 (if (org-at-table-hline-p)
1470 (org-table-goto-column col t
)
1471 (and (looking-at "|[^|\n]+|")
1472 (replace-match "|")))
1473 (beginning-of-line 2))
1474 (move-marker end nil
)
1475 (org-goto-line linepos
)
1476 (org-table-goto-column colpos
)
1478 (when (or (not org-table-fix-formulas-confirm
)
1479 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1480 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1482 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1486 (defun org-table-move-column-right ()
1487 "Move column to the right."
1489 (org-table-move-column nil
))
1491 (defun org-table-move-column-left ()
1492 "Move column to the left."
1494 (org-table-move-column 'left
))
1497 (defun org-table-move-column (&optional left
)
1498 "Move the current column to the right. With arg LEFT, move to the left."
1500 (if (not (org-at-table-p))
1501 (user-error "Not at a table"))
1502 (org-table-find-dataline)
1503 (org-table-check-inside-data-field)
1504 (let* ((col (org-table-current-column))
1505 (col1 (if left
(1- col
) col
))
1506 (beg (org-table-begin))
1507 (end (org-table-end))
1508 ;; Current cursor position
1509 (linepos (org-current-line))
1510 (colpos (if left
(1- col
) (1+ col
))))
1511 (if (and left
(= col
1))
1512 (user-error "Cannot move column further left"))
1513 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1514 (user-error "Cannot move column further right"))
1516 (while (< (point) end
)
1517 (if (org-at-table-hline-p)
1519 (org-table-goto-column col1 t
)
1520 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1521 (replace-match "|\\2|\\1|")))
1522 (beginning-of-line 2))
1523 (move-marker end nil
)
1524 (org-goto-line linepos
)
1525 (org-table-goto-column colpos
)
1527 (when (or (not org-table-fix-formulas-confirm
)
1528 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1529 (org-table-fix-formulas
1530 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1531 (cons (number-to-string colpos
) (number-to-string col
))))
1532 (org-table-fix-formulas
1533 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1534 (cons (number-to-string colpos
) (number-to-string col
)))))))
1537 (defun org-table-move-row-down ()
1538 "Move table row down."
1540 (org-table-move-row nil
))
1542 (defun org-table-move-row-up ()
1543 "Move table row up."
1545 (org-table-move-row 'up
))
1548 (defun org-table-move-row (&optional up
)
1549 "Move the current table line down. With arg UP, move it up."
1551 (let* ((col (current-column))
1553 (hline1p (save-excursion (beginning-of-line 1)
1554 (looking-at org-table-hline-regexp
)))
1555 (dline1 (org-table-current-dline))
1556 (dline2 (+ dline1
(if up -
1 1)))
1559 (beginning-of-line tonew
)
1560 (unless (org-at-table-p)
1562 (user-error "Cannot move row further"))
1563 (setq hline2p
(looking-at org-table-hline-regexp
))
1565 (beginning-of-line 1)
1567 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1568 (delete-region (point) (1+ (point-at-eol)))
1569 (beginning-of-line tonew
)
1571 (beginning-of-line 0)
1572 (org-move-to-column col
)
1573 (unless (or hline1p hline2p
1574 (not (or (not org-table-fix-formulas-confirm
)
1575 (funcall org-table-fix-formulas-confirm
1576 "Fix formulas? "))))
1577 (org-table-fix-formulas
1578 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1579 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1582 (defun org-table-insert-row (&optional arg
)
1583 "Insert a new row above the current line into the table.
1584 With prefix ARG, insert below the current line."
1586 (if (not (org-at-table-p))
1587 (user-error "Not at a table"))
1588 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1589 (new (org-table-clean-line line
)))
1590 ;; Fix the first field if necessary
1591 (if (string-match "^[ \t]*| *[#$] *|" line
)
1592 (setq new
(replace-match (match-string 0 line
) t t new
)))
1593 (beginning-of-line (if arg
2 1))
1594 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1595 (beginning-of-line 0)
1596 (re-search-forward "| ?" (point-at-eol) t
)
1597 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1599 (when (or (not org-table-fix-formulas-confirm
)
1600 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1601 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1604 (defun org-table-insert-hline (&optional above
)
1605 "Insert a horizontal-line below the current line into the table.
1606 With prefix ABOVE, insert above the current line."
1608 (if (not (org-at-table-p))
1609 (user-error "Not at a table"))
1610 (when (eobp) (insert "\n") (backward-char 1))
1611 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1613 (let ((line (org-table-clean-line
1614 (buffer-substring (point-at-bol) (point-at-eol))))
1615 (col (current-column)))
1616 (while (string-match "|\\( +\\)|" line
)
1617 (setq line
(replace-match
1618 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1619 ?-
) "|") t t line
)))
1620 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1621 (beginning-of-line (if above
1 2))
1623 (beginning-of-line (if above
1 -
1))
1624 (org-move-to-column col
)
1625 (and org-table-overlay-coordinates
(org-table-align))))
1628 (defun org-table-hline-and-move (&optional same-column
)
1629 "Insert a hline and move to the row below that line."
1631 (let ((col (org-table-current-column)))
1632 (org-table-maybe-eval-formula)
1633 (org-table-maybe-recalculate-line)
1634 (org-table-insert-hline)
1636 (if (looking-at "\n[ \t]*|-")
1637 (progn (insert "\n|") (org-table-align))
1638 (org-table-next-field))
1639 (if same-column
(org-table-goto-column col
))))
1641 (defun org-table-clean-line (s)
1642 "Convert a table line S into a string with only \"|\" and space.
1643 In particular, this does handle wide and invisible characters."
1644 (if (string-match "^[ \t]*|-" s
)
1645 ;; It's a hline, just map the characters
1646 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1647 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1648 (setq s
(replace-match
1649 (concat "|" (make-string (org-string-width (match-string 1 s
))
1655 (defun org-table-kill-row ()
1656 "Delete the current row or horizontal line from the table."
1658 (if (not (org-at-table-p))
1659 (user-error "Not at a table"))
1660 (let ((col (current-column))
1661 (dline (org-table-current-dline)))
1662 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1663 (if (not (org-at-table-p)) (beginning-of-line 0))
1664 (org-move-to-column col
)
1665 (when (or (not org-table-fix-formulas-confirm
)
1666 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1667 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1671 (defun org-table-sort-lines (with-case &optional sorting-type
)
1672 "Sort table lines according to the column at point.
1674 The position of point indicates the column to be used for
1675 sorting, and the range of lines is the range between the nearest
1676 horizontal separator lines, or the entire table of no such lines
1677 exist. If point is before the first column, you will be prompted
1678 for the sorting column. If there is an active region, the mark
1679 specifies the first line and the sorting column, while point
1680 should be in the last line to be included into the sorting.
1682 The command then prompts for the sorting type which can be
1683 alphabetically, numerically, or by time (as given in a time stamp
1684 in the field, or as a HH:MM value). Sorting in reverse order is
1687 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1689 If SORTING-TYPE is specified when this function is called from a Lisp
1690 program, no prompting will take place. SORTING-TYPE must be a character,
1691 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1692 should be done in reverse order."
1694 (let* ((thisline (org-current-line))
1695 (thiscol (org-table-current-column))
1696 (otc org-table-overlay-coordinates
)
1697 beg end bcol ecol tend tbeg column lns pos
)
1698 (when (equal thiscol
0)
1699 (if (org-called-interactively-p 'any
)
1702 (read-string "Use column N for sorting: ")))
1704 (org-table-goto-column thiscol
))
1705 (org-table-check-inside-data-field)
1706 (if (org-region-active-p)
1708 (setq beg
(region-beginning) end
(region-end))
1710 (setq column
(org-table-current-column)
1713 (setq end
(point-at-bol 2)))
1714 (setq column
(org-table-current-column)
1716 tbeg
(org-table-begin)
1717 tend
(org-table-end))
1718 (if (re-search-backward org-table-hline-regexp tbeg t
)
1719 (setq beg
(point-at-bol 2))
1721 (setq beg
(point-at-bol 1)))
1723 (if (re-search-forward org-table-hline-regexp tend t
)
1724 (setq end
(point-at-bol 1))
1726 (setq end
(point-at-bol))))
1727 (setq beg
(move-marker (make-marker) beg
)
1728 end
(move-marker (make-marker) end
))
1731 (org-table-goto-column column
)
1732 (skip-chars-backward "^|")
1733 (setq bcol
(current-column))
1734 (org-table-goto-column (1+ column
))
1735 (skip-chars-backward "^|")
1736 (setq ecol
(1- (current-column)))
1737 (org-table-goto-column column
)
1738 (setq lns
(mapcar (lambda(x) (cons
1739 (org-sort-remove-invisible
1741 (org-split-string x
"[ \t]*|[ \t]*")))
1743 (org-split-string (buffer-substring beg end
) "\n")))
1744 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1745 (when org-table-overlay-coordinates
1746 (org-table-toggle-coordinate-overlays))
1747 (delete-region beg end
)
1748 (move-marker beg nil
)
1749 (move-marker end nil
)
1750 (insert (mapconcat 'cdr lns
"\n") "\n")
1751 (org-goto-line thisline
)
1752 (org-table-goto-column thiscol
)
1753 (when otc
(org-table-toggle-coordinate-overlays))
1754 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1757 (defun org-table-cut-region (beg end
)
1758 "Copy region in table to the clipboard and blank all relevant fields.
1759 If there is no active region, use just the field at point."
1761 (if (org-region-active-p) (region-beginning) (point))
1762 (if (org-region-active-p) (region-end) (point))))
1763 (org-table-copy-region beg end
'cut
))
1766 (defun org-table-copy-region (beg end
&optional cut
)
1767 "Copy rectangular region in table to clipboard.
1768 A special clipboard is used which can only be accessed
1769 with `org-table-paste-rectangle'."
1771 (if (org-region-active-p) (region-beginning) (point))
1772 (if (org-region-active-p) (region-end) (point))
1773 current-prefix-arg
))
1774 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1776 (rpl (if cut
" " nil
)))
1778 (org-table-check-inside-data-field)
1779 (setq l01
(org-current-line)
1780 c01
(org-table-current-column))
1782 (org-table-check-inside-data-field)
1783 (setq l02
(org-current-line)
1784 c02
(org-table-current-column))
1785 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1786 c1
(min c01 c02
) c2
(max c01 c02
))
1790 (if (> l1 l2
) (throw 'exit t
))
1792 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1793 (setq cols nil ic1 c1 ic2 c2
)
1794 (while (< ic1
(1+ ic2
))
1795 (push (org-table-get-field ic1 rpl
) cols
)
1796 (setq ic1
(1+ ic1
)))
1797 (push (nreverse cols
) region
)
1798 (setq l1
(1+ l1
)))))
1799 (setq org-table-clip
(nreverse region
))
1800 (if cut
(org-table-align))
1804 (defun org-table-paste-rectangle ()
1805 "Paste a rectangular region into a table.
1806 The upper right corner ends up in the current field. All involved fields
1807 will be overwritten. If the rectangle does not fit into the present table,
1808 the table is enlarged as needed. The process ignores horizontal separator
1811 (unless (and org-table-clip
(listp org-table-clip
))
1812 (user-error "First cut/copy a region to paste!"))
1813 (org-table-check-inside-data-field)
1814 (let* ((clip org-table-clip
)
1815 (line (org-current-line))
1816 (col (org-table-current-column))
1817 (org-enable-table-editor t
)
1818 (org-table-automatic-realign nil
)
1820 (while (setq cols
(pop clip
))
1821 (while (org-at-table-hline-p) (beginning-of-line 2))
1822 (if (not (org-at-table-p))
1823 (progn (end-of-line 0) (org-table-next-field)))
1825 (while (setq field
(pop cols
))
1826 (org-table-goto-column c nil
'force
)
1827 (org-table-get-field nil field
)
1829 (beginning-of-line 2))
1830 (org-goto-line line
)
1831 (org-table-goto-column col
)
1835 (defun org-table-convert ()
1836 "Convert from `org-mode' table to table.el and back.
1837 Obviously, this only works within limits. When an Org-mode table is
1838 converted to table.el, all horizontal separator lines get lost, because
1839 table.el uses these as cell boundaries and has no notion of horizontal lines.
1840 A table.el table can be converted to an Org-mode table only if it does not
1841 do row or column spanning. Multiline cells will become multiple cells.
1842 Beware, Org-mode does not test if the table can be successfully converted - it
1843 blindly applies a recipe that works for simple tables."
1846 (if (org-at-table.el-p
)
1847 ;; convert to Org-mode table
1848 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1849 (end (move-marker (make-marker) (org-table-end t
))))
1850 (table-unrecognize-region beg end
)
1852 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1855 (if (org-at-table-p)
1856 ;; convert to table.el table
1857 (let ((beg (move-marker (make-marker) (org-table-begin)))
1858 (end (move-marker (make-marker) (org-table-end))))
1859 ;; first, get rid of all horizontal lines
1861 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1863 ;; insert a hline before first
1865 (org-table-insert-hline 'above
)
1866 (beginning-of-line -
1)
1867 ;; insert a hline after each line
1868 (while (progn (beginning-of-line 3) (< (point) end
))
1869 (org-table-insert-hline))
1871 (setq end
(move-marker end
(org-table-end)))
1872 ;; replace "+" at beginning and ending of hlines
1873 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1874 (replace-match "\\1+-"))
1876 (while (re-search-forward "-|[ \t]*$" end t
)
1877 (replace-match "-+"))
1880 (defun org-table-transpose-table-at-point ()
1881 "Transpose Org table at point and eliminate hlines.
1889 will be transposed as
1896 Note that horizontal lines disappear."
1898 (let* ((table (delete 'hline
(org-table-to-lisp)))
1899 (dline_old (org-table-current-line))
1900 (col_old (org-table-current-column))
1901 (contents (mapcar (lambda (p)
1907 (setq tp
(cdr tp
))))
1910 (goto-char (org-table-begin))
1911 (re-search-forward "|")
1913 (delete-region (point) (org-table-end))
1916 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1918 (org-table-goto-line col_old
)
1919 (org-table-goto-column dline_old
))
1923 (defun org-table-wrap-region (arg)
1924 "Wrap several fields in a column like a paragraph.
1925 This is useful if you'd like to spread the contents of a field over several
1926 lines, in order to keep the table compact.
1928 If there is an active region, and both point and mark are in the same column,
1929 the text in the column is wrapped to minimum width for the given number of
1930 lines. Generally, this makes the table more compact. A prefix ARG may be
1931 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1932 formats the selected text to two lines. If the region was longer than two
1933 lines, the remaining lines remain empty. A negative prefix argument reduces
1934 the current number of lines by that amount. The wrapped text is pasted back
1935 into the table. If you formatted it to more lines than it was before, fields
1936 further down in the table get overwritten - so you might need to make space in
1939 If there is no region, the current field is split at the cursor position and
1940 the text fragment to the right of the cursor is prepended to the field one
1943 If there is no region, but you specify a prefix ARG, the current field gets
1944 blank, and the content is appended to the field above."
1946 (org-table-check-inside-data-field)
1947 (if (org-region-active-p)
1948 ;; There is a region: fill as a paragraph
1949 (let* ((beg (region-beginning))
1950 (cline (save-excursion (goto-char beg
) (org-current-line)))
1951 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1953 (org-table-cut-region (region-beginning) (region-end))
1954 (if (> (length (car org-table-clip
)) 1)
1955 (user-error "Region must be limited to single column"))
1956 (setq nlines
(if arg
1958 (+ (length org-table-clip
) arg
)
1960 (length org-table-clip
)))
1961 (setq org-table-clip
1962 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1964 (org-goto-line cline
)
1965 (org-table-goto-column ccol
)
1966 (org-table-paste-rectangle))
1967 ;; No region, split the current field at point
1968 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1969 (skip-chars-forward "^\r\n|"))
1971 ;; combine with field above
1972 (let ((s (org-table-blank-field))
1973 (col (org-table-current-column)))
1974 (beginning-of-line 0)
1975 (while (org-at-table-hline-p) (beginning-of-line 0))
1976 (org-table-goto-column col
)
1977 (skip-chars-forward "^|")
1978 (skip-chars-backward " ")
1979 (insert " " (org-trim s
))
1982 (if (looking-at "\\([^|]+\\)+|")
1983 (let ((s (match-string 1)))
1984 (replace-match " |")
1985 (goto-char (match-beginning 0))
1986 (org-table-next-row)
1987 (insert (org-trim s
) " ")
1989 (org-table-next-row)))))
1991 (defvar org-field-marker nil
)
1994 (defun org-table-edit-field (arg)
1995 "Edit table field in a different window.
1996 This is mainly useful for fields that contain hidden parts.
1997 When called with a \\[universal-argument] prefix, just make the full field visible so that
1998 it can be edited in place."
2002 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2004 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2005 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2006 (remove-text-properties b e
'(org-cwidth t invisible t
2007 display t intangible t
))
2008 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2009 (font-lock-fontify-block))))
2011 (let ((pos (point-marker))
2013 (if (eq org-table-use-standard-references t
)
2014 (concat (org-number-to-letters (org-table-current-column))
2015 (int-to-string (org-table-current-dline)))
2016 (concat "@" (int-to-string (org-table-current-dline))
2017 "$" (int-to-string (org-table-current-column)))))
2018 (field (org-table-get-field))
2019 (cw (current-window-configuration))
2022 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2023 (when (and (local-variable-p 'org-field-marker
)
2024 (markerp org-field-marker
))
2025 (move-marker org-field-marker nil
))
2027 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2028 (let ((org-inhibit-startup t
)) (org-mode))
2030 (setq truncate-lines nil
)
2032 (goto-char (setq p
(point-max)))
2033 (insert (org-trim field
))
2034 (remove-text-properties p
(point-max)
2035 '(invisible t org-cwidth t display t
2038 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
2039 (org-set-local 'org-window-configuration cw
)
2040 (org-set-local 'org-field-marker pos
)
2041 (message "Edit and finish with C-c C-c")))))
2043 (defun org-table-finish-edit-field ()
2044 "Finish editing a table data field.
2045 Remove all newline characters, insert the result into the table, realign
2046 the table and kill the editing buffer."
2047 (let ((pos org-field-marker
)
2048 (cw org-window-configuration
)
2049 (cb (current-buffer))
2051 (goto-char (point-min))
2052 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2053 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2054 (replace-match " "))
2055 (setq text
(org-trim (buffer-string)))
2056 (set-window-configuration cw
)
2058 (select-window (get-buffer-window (marker-buffer pos
)))
2060 (move-marker pos nil
)
2061 (org-table-check-inside-data-field)
2062 (org-table-get-field nil text
)
2064 (message "New field value inserted")))
2066 (define-minor-mode org-table-follow-field-mode
2067 "Minor mode to make the table field editor window follow the cursor.
2068 When this mode is active, the field editor window will always show the
2069 current field. The mode exits automatically when the cursor leaves the
2070 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2071 nil
" TblFollow" nil
2072 (if org-table-follow-field-mode
2073 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2075 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2076 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2077 (win (and buf
(get-buffer-window buf
))))
2078 (when win
(delete-window win
))
2080 (with-current-buffer buf
2081 (move-marker org-field-marker nil
))
2082 (kill-buffer buf
)))))
2084 (defun org-table-follow-fields-with-editor ()
2085 (if (and org-table-exit-follow-field-mode-when-leaving-table
2086 (not (org-at-table-p)))
2087 ;; We have left the table, exit the follow mode
2088 (org-table-follow-field-mode -
1)
2089 (when (org-table-check-inside-data-field 'noerror
)
2090 (let ((win (selected-window)))
2091 (org-table-edit-field nil
)
2092 (org-fit-window-to-buffer)
2093 (select-window win
)))))
2095 (defvar org-timecnt
) ; dynamically scoped parameter
2098 (defun org-table-sum (&optional beg end nlast
)
2099 "Sum numbers in region of current table column.
2100 The result will be displayed in the echo area, and will be available
2101 as kill to be inserted with \\[yank].
2103 If there is an active region, it is interpreted as a rectangle and all
2104 numbers in that rectangle will be summed. If there is no active
2105 region and point is located in a table column, sum all numbers in that
2108 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2109 numbers are assumed to be times as well (in decimal hours) and the
2110 numbers are added as such.
2112 If NLAST is a number, only the NLAST fields will actually be summed."
2115 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2117 ((and beg end
)) ; beg and end given explicitly
2118 ((org-region-active-p)
2119 (setq beg
(region-beginning) end
(region-end)))
2121 (setq col
(org-table-current-column))
2122 (goto-char (org-table-begin))
2123 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2124 (user-error "No table data"))
2125 (org-table-goto-column col
)
2127 (goto-char (org-table-end))
2128 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2129 (user-error "No table data"))
2130 (org-table-goto-column col
)
2131 (setq end
(point))))
2132 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2133 (items1 (cond ((not nlast
) items
)
2134 ((>= nlast
(length items
)) items
)
2135 (t (setq items
(reverse items
))
2136 (setcdr (nthcdr (1- nlast
) items
) nil
)
2138 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2140 (res (apply '+ numbers
))
2141 (sres (if (= org-timecnt
0)
2142 (number-to-string res
)
2143 (setq diff
(* 3600 res
)
2144 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2145 m
(floor (/ diff
60)) diff
(mod diff
60)
2147 (format "%.0f:%02.0f:%02.0f" h m s
))))
2149 (if (org-called-interactively-p 'interactive
)
2151 (substitute-command-keys
2152 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2153 (length numbers
) sres
))))
2156 (defun org-table-get-number-for-summing (s)
2158 (if (string-match "^ *|? *" s
)
2159 (setq s
(replace-match "" nil nil s
)))
2160 (if (string-match " *|? *$" s
)
2161 (setq s
(replace-match "" nil nil s
)))
2162 (setq n
(string-to-number s
))
2164 ((and (string-match "0" s
)
2165 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2166 ((string-match "\\`[ \t]+\\'" s
) nil
)
2167 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2168 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2169 (m (string-to-number (or (match-string 2 s
) "0")))
2170 (s (string-to-number (or (match-string 4 s
) "0"))))
2171 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2172 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2176 (defun org-table-current-field-formula (&optional key noerror
)
2177 "Return the formula active for the current field.
2178 Assumes that specials are in place.
2179 If KEY is given, return the key to this formula.
2180 Otherwise return the formula preceded with \"=\" or \":=\"."
2181 (let* ((name (car (rassoc (list (org-current-line)
2182 (org-table-current-column))
2183 org-table-named-field-locations
)))
2184 (col (org-table-current-column))
2185 (scol (int-to-string col
))
2186 (ref (format "@%d$%d" (org-table-current-dline) col
))
2187 (stored-list (org-table-get-stored-formulas noerror
))
2188 (ass (or (assoc name stored-list
)
2189 (assoc ref stored-list
)
2190 (assoc scol stored-list
))))
2193 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2196 (defun org-table-get-formula (&optional equation named
)
2197 "Read a formula from the minibuffer, offer stored formula as default.
2198 When NAMED is non-nil, look for a named equation."
2199 (let* ((stored-list (org-table-get-stored-formulas))
2200 (name (car (rassoc (list (org-current-line)
2201 (org-table-current-column))
2202 org-table-named-field-locations
)))
2203 (ref (format "@%d$%d" (org-table-current-dline)
2204 (org-table-current-column)))
2205 (refass (assoc ref stored-list
))
2206 (nameass (assoc name stored-list
))
2208 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2211 (int-to-string (org-table-current-column))))
2212 (dummy (and (or nameass refass
) (not named
)
2213 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2214 (message "Formula not replaced")))
2215 (name (or name ref
))
2216 (org-table-may-need-update nil
)
2217 (stored (cdr (assoc scol stored-list
)))
2219 ((and stored equation
(string-match "^ *=? *$" equation
))
2223 (t (org-table-formula-from-user
2225 (org-table-formula-to-user
2226 (format "%s formula %s%s="
2227 (if named
"Field" "Column")
2228 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2230 (if stored
(org-table-formula-to-user stored
) "")
2231 'org-table-formula-history
2234 (when (not (string-match "\\S-" eq
))
2236 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2237 (org-table-store-formulas stored-list
)
2238 (user-error "Formula removed"))
2239 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2240 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2241 (if (and name
(not named
))
2242 ;; We set the column equation, delete the named one.
2243 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2246 (setcdr (assoc scol stored-list
) eq
)
2247 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2248 (if (or mustsave
(not (equal stored eq
)))
2249 (org-table-store-formulas stored-list
))
2252 (defun org-table-store-formulas (alist)
2253 "Store the list of formulas below the current table."
2254 (setq alist
(sort alist
'org-table-formula-less-p
))
2255 (let ((case-fold-search t
))
2257 (goto-char (org-table-end))
2258 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2260 ;; don't overwrite TBLFM, we might use text properties to store stuff
2261 (goto-char (match-beginning 3))
2262 (delete-region (match-beginning 3) (match-end 0)))
2264 (insert (or (match-string 2) "#+TBLFM:")))
2266 (mapconcat (lambda (x)
2268 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2269 (car x
) "=" (cdr x
)))
2273 (defsubst org-table-formula-make-cmp-string
(a)
2274 (when (string-match "\\`$[<>]" a
)
2275 (let ((arrow (string-to-char (substring a
1))))
2276 ;; Fake a high number to make sure this is sorted at the end.
2277 (setq a
(org-table-formula-handle-first/last-rc a
))
2278 (setq a
(format "$%d" (+ 10000
2279 (if (= arrow ?
<) -
1000 0)
2280 (string-to-number (substring a
1)))))))
2282 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2286 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2288 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2290 (concat "@@" (match-string 5 a
))))))
2292 (defun org-table-formula-less-p (a b
)
2293 "Compare two formulas for sorting."
2294 (let ((as (org-table-formula-make-cmp-string (car a
)))
2295 (bs (org-table-formula-make-cmp-string (car b
))))
2296 (and as bs
(string< as bs
))))
2299 (defun org-table-get-stored-formulas (&optional noerror
)
2300 "Return an alist with the stored formulas directly after current table."
2301 (interactive) ;; FIXME interactive?
2302 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2304 (goto-char (org-table-end))
2305 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2306 (setq strings
(org-split-string (org-match-string-no-properties 2)
2308 (while (setq string
(pop strings
))
2309 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2310 (setq scol
(if (match-end 2)
2311 (match-string 2 string
)
2312 (match-string 1 string
))
2313 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2314 (concat "$" scol
) scol
)
2315 eq
(match-string 3 string
)
2316 eq-alist
(cons (cons scol eq
) eq-alist
))
2317 (if (member scol seen
)
2320 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2323 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2324 (push scol seen
))))))
2325 (nreverse eq-alist
)))
2327 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2328 "Modify the equations after the table structure has been edited.
2329 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2330 For all numbers larger than LIMIT, shift them by DELTA."
2332 (goto-char (org-table-end))
2333 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2334 (let ((msg "The formulas in #+TBLFM have been updated")
2335 (re (concat key
"\\([0-9]+\\)"))
2338 (if (or (equal key
"$") (equal key
"$LR"))
2339 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2340 (regexp-quote key
) remove
)
2341 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2344 (while (re-search-forward re2
(point-at-eol) t
)
2345 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2346 (if (equal (char-before (match-beginning 0)) ?.
)
2348 "Change makes TBLFM term %s invalid, use undo to recover"
2350 (replace-match "")))))
2351 (while (re-search-forward re
(point-at-eol) t
)
2352 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2353 (setq s
(match-string 1) n
(string-to-number s
))
2355 ((setq a
(assoc s replace
))
2356 (replace-match (concat key
(cdr a
)) t t
)
2358 ((and limit
(> n limit
))
2359 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2363 (defun org-table-get-specials ()
2364 "Get the column names and local parameters for this table."
2366 (let ((beg (org-table-begin)) (end (org-table-end))
2367 names name fields fields1 field cnt
2368 c v l line col types dlines hlines last-dline
)
2369 (setq org-table-column-names nil
2370 org-table-local-parameters nil
2371 org-table-named-field-locations nil
2372 org-table-current-begin-line nil
2373 org-table-current-begin-pos nil
2374 org-table-current-line-types nil
2375 org-table-current-ncol
0)
2377 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2378 (setq names
(org-split-string (match-string 1) " *| *")
2380 (while (setq name
(pop names
))
2382 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2383 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2384 (setq org-table-column-names
(nreverse org-table-column-names
))
2385 (setq org-table-column-name-regexp
2386 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2388 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2389 (setq fields
(org-split-string (match-string 1) " *| *"))
2390 (while (setq field
(pop fields
))
2391 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2392 (push (cons (match-string 1 field
) (match-string 2 field
))
2393 org-table-local-parameters
))))
2395 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2396 (setq c
(match-string 1)
2397 fields
(org-split-string (match-string 2) " *| *"))
2399 (beginning-of-line (if (equal c
"_") 2 0))
2400 (setq line
(org-current-line) col
1)
2401 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2402 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2403 (while (and fields1
(setq field
(pop fields
)))
2404 (setq v
(pop fields1
) col
(1+ col
))
2405 (when (and (stringp field
) (stringp v
)
2406 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2407 (push (cons field v
) org-table-local-parameters
)
2408 (push (list field line col
) org-table-named-field-locations
))))
2409 ;; Analyse the line types
2411 (setq org-table-current-begin-line
(org-current-line)
2412 org-table-current-begin-pos
(point)
2413 l org-table-current-begin-line
)
2414 (while (looking-at "[ \t]*|\\(-\\)?")
2415 (push (if (match-end 1) 'hline
'dline
) types
)
2416 (if (match-end 1) (push l hlines
) (push l dlines
))
2417 (beginning-of-line 2)
2419 (push 'hline types
) ;; add an imaginary extra hline to the end
2420 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2421 last-dline
(car dlines
)
2422 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2423 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2424 (org-goto-line last-dline
)
2425 (let* ((l last-dline
)
2426 (fields (org-split-string
2427 (buffer-substring (point-at-bol) (point-at-eol))
2429 (nfields (length fields
))
2431 (setq org-table-current-ncol nfields
)
2432 (loop for i from
1 to nfields do
2433 (push (list (format "LR%d" i
) l i
) al
)
2434 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2435 (setq org-table-named-field-locations
2436 (append org-table-named-field-locations al
))
2437 (setq org-table-local-parameters
2438 (append org-table-local-parameters al2
))))))
2441 (defun org-table-maybe-eval-formula ()
2442 "Check if the current field starts with \"=\" or \":=\".
2443 If yes, store the formula and apply it."
2444 ;; We already know we are in a table. Get field will only return a formula
2445 ;; when appropriate. It might return a separator line, but no problem.
2446 (when org-table-formula-evaluate-inline
2447 (let* ((field (org-trim (or (org-table-get-field) "")))
2449 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2450 (setq named
(equal (string-to-char field
) ?
:)
2451 eq
(match-string 1 field
))
2452 (if (or (fboundp 'calc-eval
)
2453 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2454 (org-table-eval-formula (if named
'(4) nil
)
2455 (org-table-formula-from-user eq
))
2456 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2458 (defvar org-recalc-commands nil
2459 "List of commands triggering the recalculation of a line.
2460 Will be filled automatically during use.")
2462 (defvar org-recalc-marks
2463 '((" " .
"Unmarked: no special line, no automatic recalculation")
2464 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2465 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2466 ("!" .
"Column name definition line. Reference in formula as $name.")
2467 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2468 ("_" .
"Names for values in row below this one.")
2469 ("^" .
"Names for values in row above this one.")))
2472 (defun org-table-rotate-recalc-marks (&optional newchar
)
2473 "Rotate the recalculation mark in the first column.
2474 If in any row, the first field is not consistent with a mark,
2475 insert a new column for the markers.
2476 When there is an active region, change all the lines in the region,
2477 after prompting for the marking character.
2478 After each change, a message will be displayed indicating the meaning
2481 (unless (org-at-table-p) (user-error "Not at a table"))
2482 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2483 (beg (org-table-begin))
2484 (end (org-table-end))
2485 (l (org-current-line))
2486 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2487 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2491 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2492 (col (org-table-current-column))
2493 (forcenew (car (assoc newchar org-recalc-marks
)))
2496 (message "Change region to what mark? Type # * ! $ or SPC: ")
2497 (setq newchar
(char-to-string (read-char-exclusive))
2498 forcenew
(car (assoc newchar org-recalc-marks
))))
2499 (if (and newchar
(not forcenew
))
2500 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2502 (if l1
(org-goto-line l1
))
2504 (beginning-of-line 1)
2505 (unless (looking-at org-table-dataline-regexp
)
2506 (user-error "Not at a table data line")))
2508 (org-table-goto-column 1)
2509 (org-table-insert-column)
2510 (org-table-goto-column (1+ col
)))
2511 (setq epos
(point-at-eol))
2513 (beginning-of-line 1)
2514 (org-table-get-field
2515 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2517 (setq new
(or forcenew
2518 (cadr (member (match-string 1) marks
))))
2524 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2525 (and (looking-at org-table-dataline-regexp
)
2526 (org-table-get-field 1 (concat " " new
" "))))
2527 (org-goto-line l1
)))
2528 (if (not (= epos
(point-at-eol))) (org-table-align))
2530 (and (org-called-interactively-p 'interactive
)
2531 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2534 (defun org-table-maybe-recalculate-line ()
2535 "Recompute the current line if marked for it, and if we haven't just done it."
2537 (and org-table-allow-automatic-line-recalculation
2538 (not (and (memq last-command org-recalc-commands
)
2539 (equal org-last-recalc-line
(org-current-line))))
2540 (save-excursion (beginning-of-line 1)
2541 (looking-at org-table-auto-recalculate-regexp
))
2542 (org-table-recalculate) t
))
2544 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2545 (defsubst org-set-calc-mode
(var &optional value
)
2547 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2548 ("R" calc-angle-mode rad
)
2549 ("F" calc-prefer-frac t
)
2550 ("S" calc-symbolic-mode t
)))
2551 value
(nth 2 var
) var
(nth 1 var
)))
2552 (if (memq var org-tbl-calc-modes
)
2553 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2554 (cons var
(cons value org-tbl-calc-modes
)))
2558 (defun org-table-eval-formula (&optional arg equation
2559 suppress-align suppress-const
2560 suppress-store suppress-analysis
)
2561 "Replace the table field value at the cursor by the result of a calculation.
2563 This function makes use of Dave Gillespie's Calc package, in my view the
2564 most exciting program ever written for GNU Emacs. So you need to have Calc
2565 installed in order to use this function.
2567 In a table, this command replaces the value in the current field with the
2568 result of a formula. It also installs the formula as the \"current\" column
2569 formula, by storing it in a special line below the table. When called
2570 with a `C-u' prefix, the current field must be a named field, and the
2571 formula is installed as valid in only this specific field.
2573 When called with two `C-u' prefixes, insert the active equation
2574 for the field back into the current field, so that it can be
2575 edited there. This is useful in order to use \\[org-table-show-reference]
2576 to check the referenced fields.
2578 When called, the command first prompts for a formula, which is read in
2579 the minibuffer. Previously entered formulas are available through the
2580 history list, and the last used formula is offered as a default.
2581 These stored formulas are adapted correctly when moving, inserting, or
2582 deleting columns with the corresponding commands.
2584 The formula can be any algebraic expression understood by the Calc package.
2585 For details, see the Org-mode manual.
2587 This function can also be called from Lisp programs and offers
2588 additional arguments: EQUATION can be the formula to apply. If this
2589 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2590 used to speed-up recursive calls by by-passing unnecessary aligns.
2591 SUPPRESS-CONST suppresses the interpretation of constants in the
2592 formula, assuming that this has been done already outside the function.
2593 SUPPRESS-STORE means the formula should not be stored, either because
2594 it is already stored, or because it is a modified equation that should
2595 not overwrite the stored one."
2597 (org-table-check-inside-data-field)
2598 (or suppress-analysis
(org-table-get-specials))
2599 (if (equal arg
'(16))
2600 (let ((eq (org-table-current-field-formula)))
2601 (or eq
(user-error "No equation active for current field"))
2602 (org-table-get-field nil eq
)
2604 (setq org-table-may-need-update t
))
2606 (ndown (if (integerp arg
) arg
1))
2607 (org-table-automatic-realign nil
)
2608 (case-fold-search nil
)
2610 (formula (if (and equation suppress-store
)
2612 (org-table-get-formula equation
(equal arg
'(4)))))
2613 (n0 (org-table-current-column))
2614 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2615 (numbers nil
) ; was a variable, now fixed default
2617 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2618 duration duration-output-format
)
2619 ;; Parse the format string. Since we have a lot of modes, this is
2620 ;; a lot of work. However, I think calc still uses most of the time.
2621 (if (string-match ";" formula
)
2622 (let ((tmp (org-split-string formula
";")))
2623 (setq formula
(car tmp
)
2624 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2626 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2627 (setq c
(string-to-char (match-string 1 fmt
))
2628 n
(string-to-number (match-string 2 fmt
)))
2630 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2631 (setq org-tbl-calc-modes
2634 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2635 (?s . sci
) (?e . eng
))))
2637 (setq fmt
(replace-match "" t t fmt
)))
2638 (if (string-match "T" fmt
)
2639 (setq duration t numbers t
2640 duration-output-format nil
2641 fmt
(replace-match "" t t fmt
)))
2642 (if (string-match "t" fmt
)
2644 duration-output-format org-table-duration-custom-format
2646 fmt
(replace-match "" t t fmt
)))
2647 (if (string-match "N" fmt
)
2649 fmt
(replace-match "" t t fmt
)))
2650 (if (string-match "L" fmt
)
2652 fmt
(replace-match "" t t fmt
)))
2653 (if (string-match "E" fmt
)
2655 fmt
(replace-match "" t t fmt
)))
2656 (while (string-match "[DRFS]" fmt
)
2657 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2658 (setq fmt
(replace-match "" t t fmt
)))
2659 (unless (string-match "\\S-" fmt
)
2661 (if (and (not suppress-const
) org-table-formula-use-constants
)
2662 (setq formula
(org-table-formula-substitute-names formula
)))
2663 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2665 (setq fields
(org-split-string
2666 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2668 ;; replace fields with duration values if relevant
2671 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2674 (setq fields
(mapcar
2676 (if (string-match "\\S-" x
)
2677 (number-to-string (string-to-number x
))
2680 (setq ndown
(1- ndown
))
2681 (setq form
(copy-sequence formula
)
2682 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2683 (if (and lispp literal
) (setq lispp
'literal
))
2685 ;; Insert row and column number of formula result field
2686 (while (string-match "[@$]#" form
)
2691 (if (equal (substring form
(match-beginning 0)
2692 (1+ (match-beginning 0)))
2694 (org-table-current-dline)
2695 (org-table-current-column))))
2698 ;; Check for old vertical references
2699 (setq form
(org-table-rewrite-old-row-references form
))
2700 ;; Insert remote references
2701 (setq form
(org-table-remote-reference-indirection form
))
2702 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2706 (org-table-make-reference
2707 (let ((rmtrng (org-table-get-remote-range
2708 (match-string 1 form
) (match-string 2 form
))))
2711 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2712 (org-table-time-string-to-seconds rmtrng
))
2714 keep-empty numbers lispp
))
2716 ;; Insert complex ranges
2717 (while (and (string-match org-table-range-regexp form
)
2718 (> (length (match-string 0 form
)) 1))
2719 (setq formrg
(save-match-data
2720 (org-table-get-range (match-string 0 form
) nil n0
)))
2723 (org-table-make-reference
2724 ;; possibly handle durations
2727 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2728 (org-table-time-string-to-seconds formrg
))
2730 keep-empty numbers lispp
)))
2731 (if (not (save-match-data
2732 (string-match (regexp-quote form
) formrpl
)))
2733 (setq form
(replace-match formrpl t t form
))
2734 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2735 ;; Insert simple ranges
2736 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2740 (org-table-make-reference
2742 fields
(string-to-number (match-string 1 form
))
2743 (string-to-number (match-string 2 form
)))
2744 keep-empty numbers lispp
))
2747 ;; Insert the references to fields in same row
2748 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2749 (setq n
(+ (string-to-number (match-string 1 form
))
2750 (if (match-end 2) n0
0))
2751 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2752 (unless x
(user-error "Invalid field specifier \"%s\""
2753 (match-string 0 form
)))
2754 (setq form
(replace-match
2756 (org-table-make-reference
2757 x keep-empty numbers lispp
))
2761 (setq ev
(condition-case nil
2762 (eval (eval (read form
)))
2764 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2765 ev
(if duration
(org-table-time-seconds-to-string
2766 (string-to-number ev
)
2767 duration-output-format
) ev
))
2768 (or (fboundp 'calc-eval
)
2769 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2770 ;; Use <...> time-stamps so that Calc can handle them
2771 (while (string-match (concat "\\[" org-ts-regexp1
"\\]") form
)
2772 (setq form
(replace-match "<\\1>" nil nil form
)))
2773 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2774 (when (string-match org-ts-regexp2 form
)
2775 (let* ((ts (match-string 0 form
))
2776 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2777 (system-time-locale "C")
2778 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2779 (cdr org-time-stamp-formats
))
2780 (car org-time-stamp-formats
))))
2781 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2783 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2785 (calc-eval (cons form org-tbl-calc-modes
)
2786 (when (and (not keep-empty
) numbers
) 'num
)))
2787 ev
(if duration
(org-table-time-seconds-to-string
2788 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2789 (string-to-number (org-table-time-string-to-seconds ev
))
2790 (string-to-number ev
))
2791 duration-output-format
)
2794 (when org-table-formula-debug
2795 (with-output-to-temp-buffer "*Substitution History*"
2796 (princ (format "Substitution history of formula
2800 $1-> %s\n" orig formula form0 form
))
2802 (princ (format " %s^\nError: %s"
2803 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2804 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2806 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2807 (setq bw
(get-buffer-window "*Substitution History*"))
2808 (org-fit-window-to-buffer bw
)
2809 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2810 (unless (let (inhibit-redisplay)
2811 (y-or-n-p "Debugging Formula. Continue to next? "))
2813 (user-error "Abort"))
2816 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2817 (org-table-justify-field-maybe
2818 (format org-table-formula-field-format
2819 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2820 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2821 (call-interactively 'org-return
)
2823 (and down
(org-table-maybe-recalculate-line))
2824 (or suppress-align
(and org-table-may-need-update
2825 (org-table-align))))))
2827 (defun org-table-put-field-property (prop value
)
2829 (put-text-property (progn (skip-chars-backward "^|") (point))
2830 (progn (skip-chars-forward "^|") (point))
2833 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2834 "Get a calc vector from a column, according to descriptor DESC.
2835 Optional arguments TBEG and COL can give the beginning of the table and
2836 the current column, to avoid unnecessary parsing.
2838 HIGHLIGHT means just highlight the range.
2840 When CORNERS-ONLY is set, only return the corners of the range as
2841 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2842 in the buffer and column1 and column2 are table column numbers."
2843 (if (not (equal (string-to-char desc
) ?
@))
2844 (setq desc
(concat "@" desc
)))
2846 (or tbeg
(setq tbeg
(org-table-begin)))
2847 (or col
(setq col
(org-table-current-column)))
2848 (let ((thisline (org-current-line))
2849 beg end c1 c2 r1 r2 rangep tmp
)
2850 (unless (string-match org-table-range-regexp desc
)
2851 (user-error "Invalid table range specifier `%s'" desc
))
2852 (setq rangep
(match-end 3)
2853 r1
(and (match-end 1) (match-string 1 desc
))
2854 r2
(and (match-end 4) (match-string 4 desc
))
2855 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2856 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2858 (and c1
(setq c1
(+ (string-to-number c1
)
2859 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2860 (and c2
(setq c2
(+ (string-to-number c2
)
2861 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2862 (if (equal r1
"") (setq r1 nil
))
2863 (if (equal r2
"") (setq r2 nil
))
2864 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2865 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2866 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2867 (if (not r1
) (setq r1 thisline
))
2868 (if (not r2
) (setq r2 thisline
))
2869 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2870 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2871 (if (and (not corners-only
)
2872 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2876 (while (not (looking-at org-table-dataline-regexp
))
2877 (beginning-of-line 2))
2878 (prog1 (org-trim (org-table-get-field c1
))
2879 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2880 ;; A range, return a vector
2881 ;; First sort the numbers to get a regular rectangle
2882 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2883 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2885 ;; Only return the corners of the range
2887 ;; Copy the range values into a list
2889 (while (not (looking-at org-table-dataline-regexp
))
2890 (beginning-of-line 2))
2891 (org-table-goto-column c1
)
2894 (while (not (looking-at org-table-dataline-regexp
))
2895 (beginning-of-line 0))
2896 (org-table-goto-column c2
)
2899 (org-table-highlight-rectangle
2900 beg
(progn (skip-chars-forward "^|\n") (point))))
2901 ;; return string representation of calc vector
2903 (apply 'append
(org-table-copy-region beg end
))))))))
2905 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2906 "Analyze descriptor DESC and retrieve the corresponding line number.
2907 The cursor is currently in line CLINE, the table begins in line BLINE,
2908 and TABLE is a vector with line types."
2909 (if (string-match "^[0-9]+$" desc
)
2910 (aref org-table-dlines
(string-to-number desc
))
2911 (setq cline
(or cline
(org-current-line))
2912 bline
(or bline org-table-current-begin-line
)
2913 table
(or table org-table-current-line-types
))
2915 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2917 (and (not (match-end 3)) (not (match-end 6)))
2918 (and (match-end 3) (match-end 6) (not (match-end 5))))
2919 (user-error "Invalid row descriptor `%s'" desc
))
2920 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2921 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2922 (odir (and (match-end 5) (match-string 5 desc
)))
2923 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2925 (rel (and (match-end 6)
2926 (or (and (match-end 1) (not (match-end 3)))
2928 (if (and hn
(not hdir
))
2931 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2932 (if (and (not hn
) on
(not odir
))
2933 (user-error "Should never happen");;(aref org-table-dlines on)
2934 (if (and hn
(> hn
0))
2935 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2936 nil hn cline desc
)))
2938 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2939 rel on cline desc
)))
2942 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2943 "FIXME: Needs more documentation."
2944 (let ((l (length table
)))
2946 (while (and (setq i
(+ i
(if backwards -
1 1)))
2948 (not (eq (aref table i
) type
))
2949 (if (and relative
(eq (aref table i
) 'hline
))
2951 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2952 ((eq org-table-relative-ref-may-cross-hline
'error
)
2953 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2954 (t (setq i
(- i
(if backwards -
1 1))
2959 (if (or (< i
0) (>= i l
))
2960 (user-error "Row descriptor %s used in line %d leads outside table"
2964 (defun org-table-rewrite-old-row-references (s)
2965 (if (string-match "&[-+0-9I]" s
)
2966 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2969 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2970 "Convert list ELEMENTS to something appropriate to insert into formula.
2971 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2972 NUMBERS indicates that everything should be converted to numbers.
2973 LISPP non-nil means to return something appropriate for a Lisp
2974 list, 'literal is for the format specifier L."
2975 ;; Calc nan (not a number) is used for the conversion of the empty
2976 ;; field to a reference for several reasons: (i) It is accepted in a
2977 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2978 ;; (ii) In a single field (not in range) it can be distinguished
2979 ;; from "(nan)" which is the reference made from a single field
2980 ;; containing "nan".
2981 (if (stringp elements
)
2984 (if (eq lispp
'literal
)
2986 (if (and (eq elements
"") (not keep-empty
))
2989 (if numbers
(string-to-number elements
) elements
))))
2990 (if (string-match "\\S-" elements
)
2992 (when numbers
(setq elements
(number-to-string
2993 (string-to-number elements
))))
2994 (concat "(" elements
")"))
2995 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3000 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3002 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3006 (if (eq lispp
'literal
)
3008 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3010 (concat "[" (mapconcat
3012 (if (string-match "\\S-" x
)
3014 (number-to-string (string-to-number x
))
3016 (if (or (not keep-empty
) numbers
) "0" "nan")))
3021 (defun org-table-set-constants ()
3022 "Set `org-table-formula-constants-local' in the current buffer."
3023 (let (cst consts const-str
)
3025 (goto-char (point-min))
3026 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
3027 (setq const-str
(substring-no-properties (match-string 1)))
3028 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
3031 (while (setq e
(pop consts
))
3032 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
3033 (if (assoc-string (match-string 1 e
) cst
)
3034 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
3035 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
3036 (setq org-table-formula-constants-local cst
)))))))
3039 (defun org-table-recalculate (&optional all noalign
)
3040 "Recalculate the current table line by applying all stored formulas.
3041 With prefix arg ALL, do this for all lines in the table.
3042 With the prefix argument ALL is `(16)' \
3043 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3044 it is the symbol `iterate', recompute the table until it no longer changes.
3045 If NOALIGN is not nil, do not re-align the table after the computations
3046 are done. This is typically used internally to save time, if it is
3047 known that the table will be realigned a little later anyway."
3049 (or (memq this-command org-recalc-commands
)
3050 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
3051 (unless (org-at-table-p) (user-error "Not at a table"))
3052 (if (or (eq all
'iterate
) (equal all
'(16)))
3054 (org-table-get-specials)
3055 (let* ((eqlist (sort (org-table-get-stored-formulas)
3056 (lambda (a b
) (string< (car a
) (car b
)))))
3057 (eqlist1 (copy-sequence eqlist
))
3058 (inhibit-redisplay (not debug-on-error
))
3059 (line-re org-table-dataline-regexp
)
3060 (thisline (org-current-line))
3061 (thiscol (org-table-current-column))
3063 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3064 ;; Insert constants in all formulas
3067 (if (string-match "^@-?I+" (car x
))
3068 (user-error "Can't assign to hline relative reference"))
3069 (when (string-match "\\`$[<>]" (car x
))
3071 (setq x
(cons (substring
3072 (org-table-formula-handle-first/last-rc
3075 (if (assoc (car x
) eqlist1
)
3076 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3079 (org-table-formula-handle-first/last-rc
(car x
))
3080 (org-table-formula-substitute-names
3081 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3083 ;; Split the equation list
3084 (while (setq eq
(pop eqlist
))
3085 (if (<= (string-to-char (car eq
)) ?
9)
3088 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3089 ;; Expand ranges in lhs of formulas
3090 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3092 ;; Get the correct line range to process
3095 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3096 (goto-char (setq beg
(org-table-begin)))
3097 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3098 ;; This is a table with marked lines, compute selected lines
3099 (setq line-re org-table-recalculate-regexp
)
3100 ;; Move forward to the first non-header line
3101 (if (and (re-search-forward org-table-dataline-regexp end t
)
3102 (re-search-forward org-table-hline-regexp end t
)
3103 (re-search-forward org-table-dataline-regexp end t
))
3104 (setq beg
(match-beginning 0))
3105 nil
))) ;; just leave beg where it is
3106 (setq beg
(point-at-bol)
3107 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3109 (and all
(message "Re-applying formulas to full table..."))
3111 ;; First find the named fields, and mark them untouchable.
3112 ;; Also check if several field/range formulas try to set the same field.
3113 (remove-text-properties beg end
'(org-untouchable t
))
3114 (while (setq eq
(pop eqlname
))
3116 a
(assoc name org-table-named-field-locations
))
3118 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3120 (when (member name1 seen-fields
)
3121 (user-error "Several field/range formulas try to set %s" name1
))
3122 (push name1 seen-fields
)
3125 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3128 (aref org-table-dlines
3129 (string-to-number (match-string 1 name
)))
3130 (error (user-error "Invalid row number in %s"
3132 (string-to-number (match-string 2 name
)))))
3133 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3134 (message "Re-applying formula to field: %s" name
)
3135 (org-goto-line (nth 1 a
))
3136 (org-table-goto-column (nth 2 a
))
3137 (push (append a
(list (cdr eq
))) eqlname1
)
3138 (org-table-put-field-property :org-untouchable t
)))
3139 (setq eqlname1
(nreverse eqlname1
))
3141 ;; Now evaluate the column formulas, but skip fields covered by
3144 (while (re-search-forward line-re end t
)
3145 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3146 ;; Unprotected line, recalculate
3147 (and all
(message "Re-applying formulas to full table...(line %d)"
3148 (setq cnt
(1+ cnt
))))
3149 (setq org-last-recalc-line
(org-current-line))
3151 (while (setq entry
(pop eql
))
3152 (org-goto-line org-last-recalc-line
)
3153 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3154 (unless (get-text-property (point) :org-untouchable
)
3155 (org-table-eval-formula nil
(cdr entry
)
3156 'noalign
'nocst
'nostore
'noanalysis
)))))
3158 ;; Now evaluate the field formulas
3159 (while (setq eq
(pop eqlname1
))
3160 (message "Re-applying formula to field: %s" (car eq
))
3161 (org-goto-line (nth 1 eq
))
3162 (org-table-goto-column (nth 2 eq
))
3163 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3164 'nostore
'noanalysis
))
3166 (org-goto-line thisline
)
3167 (org-table-goto-column thiscol
)
3168 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3169 (or noalign
(and org-table-may-need-update
(org-table-align))
3170 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3172 ;; back to initial position
3173 (message "Re-applying formulas...done")
3174 (org-goto-line thisline
)
3175 (org-table-goto-column thiscol
)
3176 (or noalign
(and org-table-may-need-update
(org-table-align))
3177 (and all
(message "Re-applying formulas...done"))))))
3180 (defun org-table-iterate (&optional arg
)
3181 "Recalculate the table until it does not change anymore.
3182 The maximum number of iterations is 10, but you can choose a different value
3183 with the prefix ARG."
3185 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3187 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3192 (org-table-recalculate 'all
)
3193 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3194 (if (not (string= lasttbl thistbl
))
3195 (setq lasttbl thistbl
)
3197 (message "Convergence after %d iterations" i
)
3198 (message "Table was already stable"))
3200 (user-error "No convergence after %d iterations" i
))))
3203 (defun org-table-recalculate-buffer-tables ()
3204 "Recalculate all tables in the current buffer."
3209 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3212 (defun org-table-iterate-buffer-tables ()
3213 "Iterate all tables in the buffer, to converge inter-table dependencies."
3217 (checksum (md5 (buffer-string)))
3225 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3226 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3228 (message "Convergence after %d iterations" (- imax i
))
3230 (setq checksum c1
)))
3231 (user-error "No convergence after %d iterations" imax
))))))
3233 (defun org-table-calc-current-TBLFM (&optional arg
)
3234 "Apply the #+TBLFM in the line at point to the table."
3236 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3237 (let ((formula (buffer-substring
3242 ;; Insert a temporary formula at right after the table
3243 (goto-char (org-table-TBLFM-begin))
3244 (setq s
(set-marker (make-marker) (point)))
3245 (insert (concat formula
"\n"))
3246 (setq e
(set-marker (make-marker) (point)))
3247 ;; Recalculate the table
3248 (beginning-of-line 0) ; move to the inserted line
3249 (skip-chars-backward " \r\n\t")
3250 (if (org-at-table-p)
3252 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3253 ;; delete the formula inserted temporarily
3254 (delete-region s e
))))))
3256 (defun org-table-TBLFM-begin ()
3257 "Find the beginning of the TBLFM lines and return its position.
3258 Return nil when the beginning of TBLFM line was not found."
3260 (when (progn (forward-line 1)
3262 org-table-TBLFM-begin-regexp
3266 (defun org-table-expand-lhs-ranges (equations)
3267 "Expand list of formulas.
3268 If some of the RHS in the formulas are ranges or a row reference, expand
3269 them to individual field equations for each field."
3270 (let (e res lhs rhs range r1 r2 c1 c2
)
3271 (while (setq e
(pop equations
))
3272 (setq lhs
(car e
) rhs
(cdr e
))
3274 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3275 ;; This just refers to one fixed field
3277 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3278 ;; This just refers to one fixed named field
3280 ((string-match "^@[0-9]+$" lhs
)
3281 (loop for ic from
1 to org-table-current-ncol do
3282 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3283 (put-text-property 0 (length (caar res
))
3284 :orig-eqn e
(caar res
))))
3286 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3288 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3289 r2
(nth 2 range
) c2
(nth 3 range
))
3290 (setq r1
(org-table-line-to-dline r1
))
3291 (setq r2
(org-table-line-to-dline r2
'above
))
3292 (loop for ir from r1 to r2 do
3293 (loop for ic from c1 to c2 do
3294 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3295 (put-text-property 0 (length (caar res
))
3296 :orig-eqn e
(caar res
)))))))
3299 (defun org-table-formula-handle-first/last-rc
(s)
3300 "Replace @<, @>, $<, $> with first/last row/column of the table.
3301 So @< and $< will always be replaced with @1 and $1, respectively.
3302 The advantage of these special markers are that structure editing of
3303 the table will not change them, while @1 and $1 will be modified
3304 when a line/row is swapped out of that privileged position. So for
3305 formulas that use a range of rows or columns, it may often be better
3306 to anchor the formula with \"I\" row markers, or to offset from the
3307 borders of the table using the @< @> $< $> makers."
3308 (let (n nmax len char
(start 0))
3309 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3312 (setq start
(match-end 3))
3313 (setq nmax
(if (equal (match-string 1 s
) "@")
3314 (1- (length org-table-dlines
))
3315 org-table-current-ncol
)
3316 len
(- (match-end 2) (match-beginning 2))
3317 char
(string-to-char (match-string 2 s
))
3321 (if (or (< n
1) (> n nmax
))
3322 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3323 (match-string 0 s
) s
))
3324 (setq start
(match-beginning 0))
3325 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3328 (defun org-table-formula-substitute-names (f)
3329 "Replace $const with values in string F."
3330 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3331 ;; First, check for column names
3332 (while (setq start
(string-match org-table-column-name-regexp f start
))
3333 (setq start
(1+ start
))
3334 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3335 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3336 ;; Parameters and constants
3338 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3340 (setq start
(match-end 2))
3341 (setq start
(1+ start
))
3342 (if (setq a
(save-match-data
3343 (org-table-get-constant (match-string 1 f
))))
3344 (setq f
(replace-match
3345 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3346 (if org-table-formula-debug
3347 (put-text-property 0 (length f
) :orig-formula f1 f
))
3350 (defun org-table-get-constant (const)
3351 "Find the value for a parameter or constant in a formula.
3352 Parameters get priority."
3353 (or (cdr (assoc const org-table-local-parameters
))
3354 (cdr (assoc const org-table-formula-constants-local
))
3355 (cdr (assoc const org-table-formula-constants
))
3356 (and (fboundp 'constants-get
) (constants-get const
))
3357 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3358 (org-entry-get nil
(substring const
5) 'inherit
))
3361 (defvar org-table-fedit-map
3362 (let ((map (make-sparse-keymap)))
3363 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3364 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3365 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3366 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3367 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3368 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3369 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3370 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3371 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3372 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3373 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3374 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3375 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3376 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3377 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3378 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3379 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3380 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3381 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3382 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3385 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3387 ["Finish and Install" org-table-fedit-finish t
]
3388 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3389 ["Abort" org-table-fedit-abort t
]
3391 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3392 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3394 "Shift Reference at Point"
3395 ["Up" org-table-fedit-ref-up t
]
3396 ["Down" org-table-fedit-ref-down t
]
3397 ["Left" org-table-fedit-ref-left t
]
3398 ["Right" org-table-fedit-ref-right t
]
3400 "Change Test Row for Column Formulas"
3401 ["Up" org-table-fedit-line-up t
]
3402 ["Down" org-table-fedit-line-down t
]
3404 ["Scroll Table Window" org-table-fedit-scroll t
]
3405 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3406 ["Show Table Grid" org-table-fedit-toggle-coordinates
3407 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3408 org-table-overlay-coordinates
)]
3410 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3411 :style toggle
:selected org-table-buffer-is-an
]))
3416 (defun org-table-edit-formulas ()
3417 "Edit the formulas of the current table in a separate buffer."
3419 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3420 (beginning-of-line 0))
3421 (unless (org-at-table-p) (user-error "Not at a table"))
3422 (org-table-get-specials)
3423 (let ((key (org-table-current-field-formula 'key
'noerror
))
3424 (eql (sort (org-table-get-stored-formulas 'noerror
)
3425 'org-table-formula-less-p
))
3426 (pos (point-marker))
3428 (wc (current-window-configuration))
3429 (sel-win (selected-window))
3430 (titles '((column .
"# Column Formulas\n")
3431 (field .
"# Field and Range Formulas\n")
3432 (named .
"# Named Field Formulas\n")))
3434 (org-switch-to-buffer-other-window "*Edit Formulas*")
3436 ;; Keep global-font-lock-mode from turning on font-lock-mode
3437 (let ((font-lock-global-modes '(not fundamental-mode
)))
3439 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3440 (org-set-local 'org-pos pos
)
3441 (org-set-local 'org-window-configuration wc
)
3442 (org-set-local 'org-selected-window sel-win
)
3443 (use-local-map org-table-fedit-map
)
3444 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3445 (easy-menu-add org-table-fedit-menu
)
3446 (setq startline
(org-current-line))
3447 (while (setq entry
(pop eql
))
3449 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3450 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3451 ((string-match "^[0-9]" (car entry
)) 'column
)
3453 (when (setq title
(assq type titles
))
3454 (or (bobp) (insert "\n"))
3455 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3456 (setq titles
(remove title titles
)))
3457 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3458 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3459 (car entry
) " = " (cdr entry
) "\n"))
3460 (remove-text-properties 0 (length s
) '(face nil
) s
)
3462 (if (eq org-table-use-standard-references t
)
3463 (org-table-fedit-toggle-ref-type))
3464 (org-goto-line startline
)
3465 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3467 (defun org-table-fedit-post-command ()
3468 (when (not (memq this-command
'(lisp-complete-symbol)))
3469 (let ((win (selected-window)))
3472 (org-table-show-reference)
3474 (select-window win
)))))
3476 (defun org-table-formula-to-user (s)
3477 "Convert a formula from internal to user representation."
3478 (if (eq org-table-use-standard-references t
)
3479 (org-table-convert-refs-to-an s
)
3482 (defun org-table-formula-from-user (s)
3483 "Convert a formula from user to internal representation."
3484 (if org-table-use-standard-references
3485 (org-table-convert-refs-to-rc s
)
3488 (defun org-table-convert-refs-to-rc (s)
3489 "Convert spreadsheet references from A7 to @7$28.
3490 Works for single references, but also for entire formulas and even the
3493 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3496 ;; format match, just advance
3497 (setq start
(match-end 0)))
3498 ((and (> (match-beginning 0) 0)
3499 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3500 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3501 ;; 3.e5 or something like this.
3502 (setq start
(match-end 0)))
3503 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3504 ;; (member (match-string 1 s)
3505 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3507 ;; function name, just advance
3508 (setq start
(match-end 0)))
3510 (setq start
(match-beginning 0)
3512 (if (equal (match-string 2 s
) "&")
3513 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3515 (string-to-number (match-string 2 s
))
3516 (org-letters-to-number (match-string 1 s
))))
3520 (defun org-table-convert-refs-to-an (s)
3521 "Convert spreadsheet references from to @7$28 to AB7.
3522 Works for single references, but also for entire formulas and even the
3524 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3525 (setq s
(replace-match
3527 (org-number-to-letters
3528 (string-to-number (match-string 2 s
)))
3529 (string-to-number (match-string 1 s
)))
3531 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3532 (setq s
(replace-match (concat "\\1"
3533 (org-number-to-letters
3534 (string-to-number (match-string 2 s
))) "&")
3538 (defun org-letters-to-number (s)
3539 "Convert a base 26 number represented by letters into an integer.
3540 For example: AB -> 28."
3543 (while (> (length s
) 0)
3544 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3548 (defun org-number-to-letters (n)
3549 "Convert an integer into a base 26 number represented by letters.
3550 For example: 28 -> AB."
3553 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3557 (defun org-table-time-string-to-seconds (s)
3558 "Convert a time string into numerical duration in seconds.
3559 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3560 If S is a string representing a number, keep this number."
3563 (let (hour minus min sec res
)
3565 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3566 (setq minus
(< 0 (length (match-string 1 s
)))
3567 hour
(string-to-number (match-string 2 s
))
3568 min
(string-to-number (match-string 3 s
))
3569 sec
(string-to-number (match-string 4 s
)))
3571 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3572 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3573 ((and (not (string-match org-ts-regexp-both s
))
3574 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3575 (setq minus
(< 0 (length (match-string 1 s
)))
3576 hour
(string-to-number (match-string 2 s
))
3577 min
(string-to-number (match-string 3 s
)))
3579 (setq res
(- (+ (* hour
3600) (* min
60))))
3580 (setq res
(+ (* hour
3600) (* min
60)))))
3581 (t (setq res
(string-to-number s
))))
3582 (number-to-string res
))))
3584 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3585 "Convert a number of seconds to a time string.
3586 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3587 minutes or seconds."
3588 (let* ((secs0 (abs secs
))
3590 (cond ((eq output-format
'days
)
3591 (format "%.3f" (/ (float secs0
) 86400)))
3592 ((eq output-format
'hours
)
3593 (format "%.2f" (/ (float secs0
) 3600)))
3594 ((eq output-format
'minutes
)
3595 (format "%.1f" (/ (float secs0
) 60)))
3596 ((eq output-format
'seconds
)
3597 (format "%d" secs0
))
3598 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3599 (if (< secs
0) (concat "-" res
) res
)))
3601 (defun org-table-fedit-convert-buffer (function)
3602 "Convert all references in this buffer, using FUNCTION."
3603 (let ((line (org-current-line)))
3604 (goto-char (point-min))
3606 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3607 (delete-region (point) (point-at-eol))
3608 (or (eobp) (forward-char 1)))
3609 (org-goto-line line
)))
3611 (defun org-table-fedit-toggle-ref-type ()
3612 "Convert all references in the buffer from B3 to @3$2 and back."
3614 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3615 (org-table-fedit-convert-buffer
3616 (if org-table-buffer-is-an
3617 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3618 (message "Reference type switched to %s"
3619 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3621 (defun org-table-fedit-ref-up ()
3622 "Shift the reference at point one row/hline up."
3624 (org-table-fedit-shift-reference 'up
))
3625 (defun org-table-fedit-ref-down ()
3626 "Shift the reference at point one row/hline down."
3628 (org-table-fedit-shift-reference 'down
))
3629 (defun org-table-fedit-ref-left ()
3630 "Shift the reference at point one field to the left."
3632 (org-table-fedit-shift-reference 'left
))
3633 (defun org-table-fedit-ref-right ()
3634 "Shift the reference at point one field to the right."
3636 (org-table-fedit-shift-reference 'right
))
3638 (defun org-table-fedit-shift-reference (dir)
3640 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3641 (if (memq dir
'(left right
))
3642 (org-rematch-and-replace 1 (eq dir
'left
))
3643 (user-error "Cannot shift reference in this direction")))
3644 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3645 ;; A B3-like reference
3646 (if (memq dir
'(up down
))
3647 (org-rematch-and-replace 2 (eq dir
'up
))
3648 (org-rematch-and-replace 1 (eq dir
'left
))))
3650 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3651 ;; An internal reference
3652 (if (memq dir
'(up down
))
3653 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3654 (org-rematch-and-replace 5 (eq dir
'left
))))))
3656 (defun org-rematch-and-replace (n &optional decr hline
)
3657 "Re-match the group N, and replace it with the shifted reference."
3658 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3659 (goto-char (match-beginning n
))
3660 (and (looking-at (regexp-quote (match-string n
)))
3661 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3664 (defun org-table-shift-refpart (ref &optional decr hline
)
3665 "Shift a reference part REF.
3666 If DECR is set, decrease the references row/column, else increase.
3667 If HLINE is set, this may be a hline reference, it certainly is not
3668 a translation reference."
3670 (let* ((sign (string-match "^[-+]" ref
)) n
)
3672 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3674 ((and hline
(string-match "^I+" ref
))
3675 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3676 (setq n
(+ n
(if decr -
1 1)))
3677 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3679 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3681 (concat sign
(make-string n ?I
)))
3683 ((string-match "^[0-9]+" ref
)
3684 (setq n
(string-to-number (concat sign ref
)))
3685 (setq n
(+ n
(if decr -
1 1)))
3687 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3688 (number-to-string (max 1 n
))))
3690 ((string-match "^[a-zA-Z]+" ref
)
3691 (org-number-to-letters
3692 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3694 (t (user-error "Cannot shift reference"))))))
3696 (defun org-table-fedit-toggle-coordinates ()
3697 "Toggle the display of coordinates in the referenced table."
3699 (let ((pos (marker-position org-pos
)))
3700 (with-current-buffer (marker-buffer org-pos
)
3703 (org-table-toggle-coordinate-overlays)))))
3705 (defun org-table-fedit-finish (&optional arg
)
3706 "Parse the buffer for formula definitions and install them.
3707 With prefix ARG, apply the new formulas to the table."
3709 (org-table-remove-rectangle-highlight)
3710 (if org-table-use-standard-references
3712 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3713 (setq org-table-buffer-is-an nil
)))
3714 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3715 (goto-char (point-min))
3716 (while (re-search-forward
3717 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3719 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3720 form
(match-string 3))
3721 (setq form
(org-trim form
))
3722 (when (not (equal form
""))
3723 (while (string-match "[ \t]*\n[ \t]*" form
)
3724 (setq form
(replace-match " " t t form
)))
3725 (when (assoc var eql
)
3726 (user-error "Double formulas for %s" var
))
3727 (push (cons var form
) eql
)))
3729 (set-window-configuration org-window-configuration
)
3730 (select-window sel-win
)
3732 (unless (org-at-table-p)
3733 (user-error "Lost table position - cannot install formulas"))
3734 (org-table-store-formulas eql
)
3735 (move-marker pos nil
)
3736 (kill-buffer "*Edit Formulas*")
3738 (org-table-recalculate 'all
)
3739 (message "New formulas installed - press C-u C-c C-c to apply."))))
3741 (defun org-table-fedit-abort ()
3742 "Abort editing formulas, without installing the changes."
3744 (org-table-remove-rectangle-highlight)
3745 (let ((pos org-pos
) (sel-win org-selected-window
))
3746 (set-window-configuration org-window-configuration
)
3747 (select-window sel-win
)
3749 (move-marker pos nil
)
3750 (message "Formula editing aborted without installing changes")))
3752 (defun org-table-fedit-lisp-indent ()
3753 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3755 (let ((pos (point)) beg end ind
)
3756 (beginning-of-line 1)
3758 ((looking-at "[ \t]")
3760 (call-interactively 'lisp-indent-line
))
3761 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3762 ((not (fboundp 'pp-buffer
))
3763 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3764 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3765 (goto-char (- (match-end 0) 2))
3767 (setq ind
(make-string (current-column) ?\
))
3768 (condition-case nil
(forward-sexp 1)
3770 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3773 (narrow-to-region beg end
)
3774 (if (eq last-command this-command
)
3776 (goto-char (point-min))
3777 (setq this-command nil
)
3778 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3779 (replace-match " ")))
3781 (untabify (point-min) (point-max))
3782 (goto-char (1+ (point-min)))
3783 (while (re-search-forward "^." nil t
)
3784 (beginning-of-line 1)
3786 (goto-char (point-max))
3787 (org-delete-backward-char 1)))
3791 (defvar org-show-positions nil
)
3793 (defun org-table-show-reference (&optional local
)
3794 "Show the location/value of the $ expression at point."
3796 (org-table-remove-rectangle-highlight)
3798 (let ((pos (if local
(point) org-pos
))
3800 (org-inhibit-highlight-removal t
)
3801 (win (selected-window))
3802 (org-show-positions nil
)
3803 var name e what match dest
)
3804 (if local
(org-table-get-specials))
3806 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3807 (setq match
(concat (substring (match-string 0) 0 -
1)
3809 (substring (match-string 0) 0 -
1)
3812 ((or (org-at-regexp-p org-table-range-regexp2
)
3813 (org-at-regexp-p org-table-translate-regexp
)
3814 (org-at-regexp-p org-table-range-regexp
))
3817 (org-table-convert-refs-to-rc (match-string 0))))
3819 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3820 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3822 (t (user-error "No reference at point")))
3823 match
(and what
(or match
(match-string 0))))
3824 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3825 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3826 'secondary-selection
))
3827 (org-add-hook 'before-change-functions
3828 'org-table-remove-rectangle-highlight
)
3829 (if (eq what
'name
) (setq var
(substring match
1)))
3830 (when (eq what
'range
)
3831 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3832 (setq match
(org-table-formula-substitute-names match
)))
3836 (re-search-backward "^\\S-" nil t
)
3837 (beginning-of-line 1)
3838 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3841 (org-table-convert-refs-to-rc (match-string 1))))
3842 (org-table-add-rectangle-overlay
3843 (match-beginning 1) (match-end 1) face2
))))
3844 (if (and (markerp pos
) (marker-buffer pos
))
3845 (if (get-buffer-window (marker-buffer pos
))
3846 (select-window (get-buffer-window (marker-buffer pos
)))
3847 (org-switch-to-buffer-other-window (get-buffer-window
3848 (marker-buffer pos
)))))
3850 (org-table-force-dataline)
3852 (setq name
(substring dest
1))
3854 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3855 (setq e
(assoc name org-table-named-field-locations
))
3856 (org-goto-line (nth 1 e
))
3857 (org-table-goto-column (nth 2 e
)))
3858 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3859 (let ((l (string-to-number (match-string 1 dest
)))
3860 (c (string-to-number (match-string 2 dest
))))
3861 (org-goto-line (aref org-table-dlines l
))
3862 (org-table-goto-column c
)))
3863 (t (org-table-goto-column (string-to-number name
))))
3864 (move-marker pos
(point))
3865 (org-table-highlight-rectangle nil nil face2
))
3867 ((equal dest match
))
3872 (org-table-get-range match nil nil
'highlight
))
3874 ((setq e
(assoc var org-table-named-field-locations
))
3875 (org-goto-line (nth 1 e
))
3876 (org-table-goto-column (nth 2 e
))
3877 (org-table-highlight-rectangle (point) (point))
3878 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3879 ((setq e
(assoc var org-table-column-names
))
3880 (org-table-goto-column (string-to-number (cdr e
)))
3881 (org-table-highlight-rectangle (point) (point))
3882 (goto-char (org-table-begin))
3883 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3886 (goto-char (match-beginning 1))
3887 (org-table-highlight-rectangle)
3888 (message "Named column (column %s)" (cdr e
)))
3889 (user-error "Column name not found")))
3892 (org-table-goto-column (string-to-number (substring match
1)))
3893 (org-table-highlight-rectangle (point) (point))
3894 (message "Column %s" (substring match
1)))
3895 ((setq e
(assoc var org-table-local-parameters
))
3896 (goto-char (org-table-begin))
3897 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3899 (goto-char (match-beginning 1))
3900 (org-table-highlight-rectangle)
3901 (message "Local parameter."))
3902 (user-error "Parameter not found")))
3905 ((not var
) (user-error "No reference at point"))
3906 ((setq e
(assoc var org-table-formula-constants-local
))
3907 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3909 ((setq e
(assoc var org-table-formula-constants
))
3910 (message "Constant: $%s=%s in `org-table-formula-constants'."
3912 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3913 (message "Constant: $%s=%s, from `constants.el'%s."
3914 var e
(format " (%s units)" constants-unit-system
)))
3915 (t (user-error "Undefined name $%s" var
)))))
3917 (when (and org-show-positions
3918 (not (memq this-command
'(org-table-fedit-scroll
3919 org-table-fedit-scroll-down
))))
3920 (push pos org-show-positions
)
3921 (push org-table-current-begin-pos org-show-positions
)
3922 (let ((min (apply 'min org-show-positions
))
3923 (max (apply 'max org-show-positions
)))
3924 (goto-char min
) (recenter 0)
3926 (or (pos-visible-in-window-p max
) (recenter -
1))))
3927 (select-window win
))))
3929 (defun org-table-force-dataline ()
3930 "Make sure the cursor is in a dataline in a table."
3931 (unless (save-excursion
3932 (beginning-of-line 1)
3933 (looking-at org-table-dataline-regexp
))
3934 (let* ((re org-table-dataline-regexp
)
3935 (p1 (save-excursion (re-search-forward re nil
'move
)))
3936 (p2 (save-excursion (re-search-backward re nil
'move
))))
3938 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3940 ((or p1 p2
) (goto-char (or p1 p2
)))
3941 (t (user-error "No table dataline around here"))))))
3943 (defun org-table-fedit-line-up ()
3944 "Move cursor one line up in the window showing the table."
3946 (org-table-fedit-move 'previous-line
))
3948 (defun org-table-fedit-line-down ()
3949 "Move cursor one line down in the window showing the table."
3951 (org-table-fedit-move 'next-line
))
3953 (defun org-table-fedit-move (command)
3954 "Move the cursor in the window showing the table.
3955 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3956 (let ((org-table-allow-automatic-line-recalculation nil
)
3957 (pos org-pos
) (win (selected-window)) p
)
3958 (select-window (get-buffer-window (marker-buffer org-pos
)))
3960 (call-interactively command
)
3961 (while (and (org-at-table-p)
3962 (org-at-table-hline-p))
3963 (call-interactively command
))
3964 (or (org-at-table-p) (goto-char p
))
3965 (move-marker pos
(point))
3966 (select-window win
)))
3968 (defun org-table-fedit-scroll (N)
3970 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3971 (scroll-other-window N
)))
3973 (defun org-table-fedit-scroll-down (N)
3975 (org-table-fedit-scroll (- N
)))
3977 (defvar org-table-rectangle-overlays nil
)
3979 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3980 "Add a new overlay."
3981 (let ((ov (make-overlay beg end
)))
3982 (overlay-put ov
'face
(or face
'secondary-selection
))
3983 (push ov org-table-rectangle-overlays
)))
3985 (defun org-table-highlight-rectangle (&optional beg end face
)
3986 "Highlight rectangular region in a table."
3987 (setq beg
(or beg
(point)) end
(or end
(point)))
3988 (let ((b (min beg end
))
3991 (and (boundp 'org-show-positions
)
3992 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3993 (goto-char (min beg end
))
3994 (setq l1
(org-current-line)
3995 c1
(org-table-current-column))
3996 (goto-char (max beg end
))
3997 (setq l2
(org-current-line)
3998 c2
(org-table-current-column))
3999 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
4001 (beginning-of-line 1)
4002 (loop for line from l1 to l2 do
4003 (when (looking-at org-table-dataline-regexp
)
4004 (org-table-goto-column c1
)
4005 (skip-chars-backward "^|\n") (setq beg
(point))
4006 (org-table-goto-column c2
)
4007 (skip-chars-forward "^|\n") (setq end
(point))
4008 (org-table-add-rectangle-overlay beg end face
))
4009 (beginning-of-line 2))
4011 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
4013 (defun org-table-remove-rectangle-highlight (&rest ignore
)
4014 "Remove the rectangle overlays."
4015 (unless org-inhibit-highlight-removal
4016 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4017 (mapc 'delete-overlay org-table-rectangle-overlays
)
4018 (setq org-table-rectangle-overlays nil
)))
4020 (defvar org-table-coordinate-overlays nil
4021 "Collects the coordinate grid overlays, so that they can be removed.")
4022 (make-variable-buffer-local 'org-table-coordinate-overlays
)
4024 (defun org-table-overlay-coordinates ()
4025 "Add overlays to the table at point, to show row/column coordinates."
4027 (mapc 'delete-overlay org-table-coordinate-overlays
)
4028 (setq org-table-coordinate-overlays nil
)
4030 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4031 (goto-char (org-table-begin))
4032 (while (org-at-table-p)
4033 (setq eol
(point-at-eol))
4034 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4035 (push ov org-table-coordinate-overlays
)
4036 (setq hline
(looking-at org-table-hline-regexp
))
4037 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4038 (format "%4d" (setq id
(1+ id
)))))
4039 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4042 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4043 (setq beg
(1+ (match-beginning 0))
4045 s1
(concat "$" (int-to-string ic
))
4046 s2
(org-number-to-letters ic
)
4047 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4048 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4049 (push ov org-table-coordinate-overlays
)
4050 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4051 (beginning-of-line 2)))))
4054 (defun org-table-toggle-coordinate-overlays ()
4055 "Toggle the display of Row/Column numbers in tables."
4057 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4058 (message "Tables Row/Column numbers display turned %s"
4059 (if org-table-overlay-coordinates
"on" "off"))
4060 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4062 (unless org-table-overlay-coordinates
4063 (mapc 'delete-overlay org-table-coordinate-overlays
)
4064 (setq org-table-coordinate-overlays nil
)))
4067 (defun org-table-toggle-formula-debugger ()
4068 "Toggle the formula debugger in tables."
4070 (setq org-table-formula-debug
(not org-table-formula-debug
))
4071 (message "Formula debugging has been turned %s"
4072 (if org-table-formula-debug
"on" "off")))
4074 ;;; The orgtbl minor mode
4076 ;; Define a minor mode which can be used in other modes in order to
4077 ;; integrate the org-mode table editor.
4079 ;; This is really a hack, because the org-mode table editor uses several
4080 ;; keys which normally belong to the major mode, for example the TAB and
4081 ;; RET keys. Here is how it works: The minor mode defines all the keys
4082 ;; necessary to operate the table editor, but wraps the commands into a
4083 ;; function which tests if the cursor is currently inside a table. If that
4084 ;; is the case, the table editor command is executed. However, when any of
4085 ;; those keys is used outside a table, the function uses `key-binding' to
4086 ;; look up if the key has an associated command in another currently active
4087 ;; keymap (minor modes, major mode, global), and executes that command.
4088 ;; There might be problems if any of the keys used by the table editor is
4089 ;; otherwise used as a prefix key.
4091 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4092 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4093 ;; addresses this by checking explicitly for both bindings.
4095 ;; The optimized version (see variable `orgtbl-optimized') takes over
4096 ;; all keys which are bound to `self-insert-command' in the *global map*.
4097 ;; Some modes bind other commands to simple characters, for example
4098 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4099 ;; active, this binding is ignored inside tables and replaced with a
4100 ;; modified self-insert.
4103 (defvar orgtbl-mode-map
(make-keymap)
4104 "Keymap for `orgtbl-mode'.")
4106 (defvar org-old-auto-fill-inhibit-regexp nil
4107 "Local variable used by `orgtbl-mode'.")
4109 (defconst orgtbl-line-start-regexp
4110 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4111 "Matches a line belonging to an orgtbl.")
4113 (defconst orgtbl-extra-font-lock-keywords
4114 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4115 0 (quote 'org-table
) 'prepend
))
4116 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4118 ;; Install it as a minor mode.
4119 (put 'orgtbl-mode
:included t
)
4120 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4123 (define-minor-mode orgtbl-mode
4124 "The `org-mode' table editor as a minor mode for use in other modes."
4125 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4126 (org-load-modules-maybe)
4128 ((derived-mode-p 'org-mode
)
4129 ;; Exit without error, in case some hook functions calls this
4130 ;; by accident in org-mode.
4131 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4133 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4134 ;; Make sure we are first in minor-mode-map-alist
4135 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4136 ;; FIXME: maybe it should use emulation-mode-map-alists?
4137 (and c
(setq minor-mode-map-alist
4138 (cons c
(delq c minor-mode-map-alist
)))))
4139 (org-set-local (quote org-table-may-need-update
) t
)
4140 (org-add-hook 'before-change-functions
'org-before-change-function
4142 (org-set-local 'org-old-auto-fill-inhibit-regexp
4143 auto-fill-inhibit-regexp
)
4144 (org-set-local 'auto-fill-inhibit-regexp
4145 (if auto-fill-inhibit-regexp
4146 (concat orgtbl-line-start-regexp
"\\|"
4147 auto-fill-inhibit-regexp
)
4148 orgtbl-line-start-regexp
))
4149 (add-to-invisibility-spec '(org-cwidth))
4150 (when (fboundp 'font-lock-add-keywords
)
4151 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4152 (org-restart-font-lock))
4153 (easy-menu-add orgtbl-mode-menu
))
4155 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4156 (org-table-cleanup-narrow-column-properties)
4157 (org-remove-from-invisibility-spec '(org-cwidth))
4158 (remove-hook 'before-change-functions
'org-before-change-function t
)
4159 (when (fboundp 'font-lock-remove-keywords
)
4160 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4161 (org-restart-font-lock))
4162 (easy-menu-remove orgtbl-mode-menu
)
4163 (force-mode-line-update 'all
))))
4165 (defun org-table-cleanup-narrow-column-properties ()
4166 "Remove all properties related to narrow-column invisibility."
4167 (let ((s (point-min)))
4168 (while (setq s
(text-property-any s
(point-max)
4169 'display org-narrow-column-arrow
))
4170 (remove-text-properties s
(1+ s
) '(display t
)))
4171 (setq s
(point-min))
4172 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4173 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4174 (setq s
(point-min))
4175 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4176 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4178 (defun orgtbl-make-binding (fun n
&rest keys
)
4179 "Create a function for binding in the table minor mode.
4180 FUN is the command to call inside a table. N is used to create a unique
4181 command name. KEYS are keys that should be checked in for a command
4182 to execute outside of tables."
4185 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4187 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4188 "Outside of tables, run the binding of `"
4189 (mapconcat #'key-description keys
"' or `")
4194 (list 'call-interactively
(list 'quote fun
))
4195 (list 'let
'(orgtbl-mode)
4196 (list 'call-interactively
4199 (list 'key-binding k
))
4201 '('orgtbl-error
))))))))
4203 (defun orgtbl-error ()
4204 "Error when there is no default binding for a table key."
4206 (user-error "This key has no function outside tables"))
4208 (defun orgtbl-setup ()
4209 "Setup orgtbl keymaps."
4212 '(([(meta shift left
)] org-table-delete-column
)
4213 ([(meta left
)] org-table-move-column-left
)
4214 ([(meta right
)] org-table-move-column-right
)
4215 ([(meta shift right
)] org-table-insert-column
)
4216 ([(meta shift up
)] org-table-kill-row
)
4217 ([(meta shift down
)] org-table-insert-row
)
4218 ([(meta up
)] org-table-move-row-up
)
4219 ([(meta down
)] org-table-move-row-down
)
4220 ("\C-c\C-w" org-table-cut-region
)
4221 ("\C-c\M-w" org-table-copy-region
)
4222 ("\C-c\C-y" org-table-paste-rectangle
)
4223 ("\C-c\C-w" org-table-wrap-region
)
4224 ("\C-c-" org-table-insert-hline
)
4225 ("\C-c}" org-table-toggle-coordinate-overlays
)
4226 ("\C-c{" org-table-toggle-formula-debugger
)
4227 ("\C-m" org-table-next-row
)
4228 ([(shift return
)] org-table-copy-down
)
4229 ("\C-c?" org-table-field-info
)
4230 ("\C-c " org-table-blank-field
)
4231 ("\C-c+" org-table-sum
)
4232 ("\C-c=" org-table-eval-formula
)
4233 ("\C-c'" org-table-edit-formulas
)
4234 ("\C-c`" org-table-edit-field
)
4235 ("\C-c*" org-table-recalculate
)
4236 ("\C-c^" org-table-sort-lines
)
4237 ("\M-a" org-table-beginning-of-field
)
4238 ("\M-e" org-table-end-of-field
)
4239 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4241 (while (setq elt
(pop bindings
))
4242 (setq nfunc
(1+ nfunc
))
4243 (setq key
(org-key (car elt
))
4245 cmd
(orgtbl-make-binding fun nfunc key
))
4246 (org-defkey orgtbl-mode-map key cmd
))
4248 ;; Special treatment needed for TAB and RET
4249 (org-defkey orgtbl-mode-map
[(return)]
4250 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4251 (org-defkey orgtbl-mode-map
"\C-m"
4252 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4254 (org-defkey orgtbl-mode-map
[(tab)]
4255 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4256 (org-defkey orgtbl-mode-map
"\C-i"
4257 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4259 (org-defkey orgtbl-mode-map
[(shift tab
)]
4260 (orgtbl-make-binding 'org-table-previous-field
104
4261 [(shift tab
)] [(tab)] "\C-i"))
4264 (unless (featurep 'xemacs
)
4265 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4266 (orgtbl-make-binding 'org-table-previous-field
107
4267 [S-iso-lefttab
] [backtab] [(shift tab)]
4270 (org-defkey orgtbl-mode-map [backtab]
4271 (orgtbl-make-binding 'org-table-previous-field
108
4272 [backtab] [S-iso-lefttab] [(shift tab)]
4275 (org-defkey orgtbl-mode-map "\M-\C-m"
4276 (orgtbl-make-binding 'org-table-wrap-region 105
4277 "\M-\C-m" [(meta return)]))
4278 (org-defkey orgtbl-mode-map [(meta return)]
4279 (orgtbl-make-binding 'org-table-wrap-region 106
4280 [(meta return)] "\M-\C-m"))
4282 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4283 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4285 (when orgtbl-optimized
4286 ;; If the user wants maximum table support, we need to hijack
4287 ;; some standard editing functions
4288 (org-remap orgtbl-mode-map
4289 'self-insert-command 'orgtbl-self-insert-command
4290 'delete-char 'org-delete-char
4291 'delete-backward-char 'org-delete-backward-char)
4292 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4293 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4295 ["Create or convert" org-table-create-or-convert-from-region
4296 :active (not (org-at-table-p)) :keys "C-c |" ]
4298 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4299 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4300 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4301 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4303 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4304 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4305 ["Copy Field from Above"
4306 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4309 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4310 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4311 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4312 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4314 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4315 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4316 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4317 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4318 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4320 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4322 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4323 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4324 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4325 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4328 ["Insert table template" orgtbl-insert-radio-table
4329 (assq major-mode orgtbl-radio-table-templates)]
4330 ["Comment/uncomment table" orgtbl-toggle-comment t])
4332 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4333 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4334 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4335 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4336 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4337 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4338 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4339 ["Sum Column/Rectangle" org-table-sum
4340 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4341 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4343 org-table-toggle-formula-debugger :active (org-at-table-p)
4345 :style toggle :selected org-table-formula-debug]
4346 ["Show Col/Row Numbers"
4347 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4349 :style toggle :selected org-table-overlay-coordinates]
4353 (defun orgtbl-ctrl-c-ctrl-c (arg)
4354 "If the cursor is inside a table, realign the table.
4355 If it is a table to be sent away to a receiver, do it.
4356 With prefix arg, also recompute table."
4358 (let ((case-fold-search t) (pos (point)) action)
4360 (beginning-of-line 1)
4362 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4363 ((looking-at "[ \t]*|") pos)
4364 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4368 (org-table-maybe-eval-formula)
4370 (call-interactively 'org-table-recalculate)
4371 (org-table-maybe-recalculate-line))
4372 (call-interactively 'org-table-align)
4373 (when (orgtbl-send-table 'maybe)
4374 (run-hooks 'orgtbl-after-send-table-hook)))
4375 ((eq action 'recalc)
4376 (org-table-set-constants)
4378 (beginning-of-line 1)
4379 (skip-chars-backward " \r\n\t")
4380 (if (org-at-table-p)
4381 (org-call-with-arg 'org-table-recalculate t))))
4382 (t (let (orgtbl-mode)
4383 (call-interactively (key-binding "\C-c\C-c")))))))
4385 (defun orgtbl-create-or-convert-from-region (arg)
4386 "Create table or convert region to table, if no conflicting binding.
4387 This installs the table binding `C-c |', but only if there is no
4388 conflicting binding to this key outside orgtbl-mode."
4390 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4392 (call-interactively cmd)
4393 (call-interactively 'org-table-create-or-convert-from-region))))
4395 (defun orgtbl-tab (arg)
4396 "Justification and field motion for `orgtbl-mode'."
4398 (if arg (org-table-edit-field t)
4399 (org-table-justify-field-maybe)
4400 (org-table-next-field)))
4402 (defun orgtbl-ret ()
4403 "Justification and field motion for `orgtbl-mode'."
4407 (org-table-justify-field-maybe)
4408 (org-table-next-row)))
4410 (defun orgtbl-self-insert-command (N)
4411 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4412 If the cursor is in a table looking at whitespace, the whitespace is
4413 overwritten, and the table is not marked as requiring realignment."
4415 (if (and (org-at-table-p)
4417 (and org-table-auto-blank-field
4418 (member last-command
4419 '(orgtbl-hijacker-command-100
4420 orgtbl-hijacker-command-101
4421 orgtbl-hijacker-command-102
4422 orgtbl-hijacker-command-103
4423 orgtbl-hijacker-command-104
4424 orgtbl-hijacker-command-105
4426 (org-table-blank-field))
4429 (looking-at "[^|\n]* +|"))
4430 (let (org-table-may-need-update)
4431 (goto-char (1- (match-end 0)))
4432 (org-delete-backward-char 1)
4433 (goto-char (match-beginning 0))
4434 (self-insert-command N))
4435 (setq org-table-may-need-update t)
4438 (cmd (or (key-binding
4439 (or (and (listp function-key-map)
4440 (setq a (assoc last-input-event function-key-map))
4442 (vector last-input-event)))
4443 'self-insert-command)))
4444 (call-interactively cmd)
4445 (if (and org-self-insert-cluster-for-undo
4446 (eq cmd 'self-insert-command))
4447 (if (not (eq last-command 'orgtbl-self-insert-command))
4448 (setq org-self-insert-command-undo-counter 1)
4449 (if (>= org-self-insert-command-undo-counter 20)
4450 (setq org-self-insert-command-undo-counter 1)
4451 (and (> org-self-insert-command-undo-counter 0)
4453 (not (cadr buffer-undo-list)) ; remove nil entry
4454 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4455 (setq org-self-insert-command-undo-counter
4456 (1+ org-self-insert-command-undo-counter))))))))
4458 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4459 "Regular expression matching exponentials as produced by calc.")
4461 (defun orgtbl-gather-send-defs ()
4462 "Gather a plist of :name, :transform, :params for each destination before
4465 (goto-char (org-table-begin))
4467 (beginning-of-line 0)
4468 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4469 (let ((name (org-no-properties (match-string 1)))
4470 (transform (intern (match-string 2)))
4471 (params (if (match-end 3)
4472 (read (concat "(" (match-string 3) ")")))))
4473 (push (list :name name :transform transform :params params)
4475 (beginning-of-line 0)))
4478 (defun orgtbl-send-replace-tbl (name txt)
4479 "Find and replace table NAME with TXT."
4481 (goto-char (point-min))
4482 (unless (re-search-forward
4483 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4484 (user-error "Don't know where to insert translated table"))
4485 (goto-char (match-beginning 0))
4486 (beginning-of-line 2)
4488 (let ((beg (point)))
4489 (unless (re-search-forward
4490 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4491 (user-error "Cannot find end of insertion region"))
4492 (beginning-of-line 1)
4493 (delete-region beg (point))))
4497 (defun org-table-to-lisp (&optional txt)
4498 "Convert the table at point to a Lisp structure.
4499 The structure will be a list. Each item is either the symbol `hline'
4500 for a horizontal separator line, or a list of field values as strings.
4501 The table is taken from the parameter TXT, or from the buffer at point."
4503 (unless (org-at-table-p)
4504 (user-error "No table at point")))
4506 (buffer-substring-no-properties (org-table-begin)
4508 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4512 (if (string-match org-table-hline-regexp x)
4514 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4517 (defun orgtbl-send-table (&optional maybe)
4518 "Send a transformed version of this table to the receiver position.
4519 With argument MAYBE, fail quietly if no transformation is defined for
4523 (unless (org-at-table-p) (user-error "Not at a table"))
4524 ;; when non-interactive, we assume align has just happened.
4525 (when (org-called-interactively-p 'any) (org-table-align))
4526 (let ((dests (orgtbl-gather-send-defs))
4527 (txt (buffer-substring-no-properties (org-table-begin)
4530 (unless dests (if maybe (throw 'exit nil)
4531 (user-error "Don't know how to transform this table")))
4532 (dolist (dest dests)
4533 (let* ((name (plist-get dest :name))
4534 (transform (plist-get dest :transform))
4535 (params (plist-get dest :params))
4536 (skip (plist-get params :skip))
4537 (skipcols (plist-get params :skipcols))
4538 (no-escape (plist-get params :no-escape))
4540 (lines (org-table-clean-before-export
4542 (org-split-string txt "[ \t]*\n[ \t]*"))))
4543 (i0 (if org-table-clean-did-remove-column 2 1))
4544 (lines (if no-escape lines
4545 (mapcar (lambda(l) (replace-regexp-in-string
4546 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4549 (if (string-match org-table-hline-regexp x)
4551 (org-remove-by-index
4552 (org-split-string (org-trim x) "\\s-*|\\s-*")
4555 (fun (if (= i0 2) 'cdr 'identity))
4556 (org-table-last-alignment
4557 (org-remove-by-index (funcall fun org-table-last-alignment)
4559 (org-table-last-column-widths
4560 (org-remove-by-index (funcall fun org-table-last-column-widths)
4562 (txt (if (fboundp transform)
4563 (funcall transform table params)
4564 (user-error "No such transformation function %s" transform))))
4565 (orgtbl-send-replace-tbl name txt))
4566 (setq ntbl (1+ ntbl)))
4567 (message "Table converted and installed at %d receiver location%s"
4568 ntbl (if (> ntbl 1) "s" ""))
4573 (defun org-remove-by-index (list indices &optional i0)
4574 "Remove the elements in LIST with indices in INDICES.
4575 First element has index 0, or I0 if given."
4578 (if (integerp indices) (setq indices (list indices)))
4579 (setq i0 (1- (or i0 0)))
4580 (delq :rm (mapcar (lambda (x)
4582 (if (memq i0 indices) :rm x))
4585 (defun orgtbl-toggle-comment ()
4586 "Comment or uncomment the orgtbl at point."
4588 (let* ((case-fold-search t)
4589 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4590 (re2 (concat "^" orgtbl-line-start-regexp))
4591 (commented (save-excursion (beginning-of-line 1)
4592 (cond ((looking-at re1) t)
4593 ((looking-at re2) nil)
4594 (t (user-error "Not at an org table")))))
4595 (re (if commented re1 re2))
4598 (beginning-of-line 1)
4599 (while (looking-at re) (beginning-of-line 0))
4600 (beginning-of-line 2)
4602 (while (looking-at re) (beginning-of-line 2))
4604 (comment-region beg end (if commented '(4) nil))))
4606 (defun orgtbl-insert-radio-table ()
4607 "Insert a radio table template appropriate for this major mode."
4609 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4612 (unless e (user-error "No radio table setup defined for %s" major-mode))
4613 (setq name (read-string "Table name: "))
4614 (while (string-match "%n" txt)
4615 (setq txt (replace-match name t t txt)))
4616 (or (bolp) (insert "\n"))
4621 ;; Dynamically bound input and output for table formatting.
4622 (defvar *orgtbl-table* nil
4623 "Carries the current table through formatting routines.")
4624 (defvar *orgtbl-rtn* nil
4625 "Formatting routines push the output lines here.")
4626 ;; Formatting parameters for the current table section.
4627 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4628 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4629 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4630 (defvar *orgtbl-fmt* nil "Format for each entry.")
4631 (defvar *orgtbl-efmt* nil "Format for numbers.")
4632 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4633 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4634 (defvar *orgtbl-lstart* nil "Text starting a row.")
4635 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4636 (defvar *orgtbl-lend* nil "Text ending a row.")
4637 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4639 (defsubst orgtbl-get-fmt (fmt i)
4640 "Retrieve the format from FMT corresponding to the Ith column."
4641 (if (and (not (functionp fmt)) (consp fmt))
4645 (defsubst orgtbl-apply-fmt (fmt &rest args)
4646 "Apply format FMT to arguments ARGS.
4647 When FMT is nil, return the first argument from ARGS."
4648 (cond ((functionp fmt) (apply fmt args))
4649 (fmt (apply 'format fmt args))
4653 (defsubst orgtbl-eval-str (str)
4654 "If STR is a function, evaluate it with no arguments."
4659 (defun orgtbl-format-line (line)
4660 "Format LINE as a table row."
4661 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4667 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4668 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4669 (orgtbl-apply-fmt efmt (match-string 1 f)
4672 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4673 *orgtbl-default-fmt*)
4676 (push (if *orgtbl-lfmt*
4677 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4678 (concat (orgtbl-eval-str *orgtbl-lstart*)
4679 (mapconcat 'identity line *orgtbl-sep*)
4680 (orgtbl-eval-str *orgtbl-lend*)))
4683 (defun orgtbl-format-section (section-stopper)
4684 "Format lines until the first occurrence of SECTION-STOPPER."
4687 (while (not (eq (car *orgtbl-table*) section-stopper))
4688 (if prevline (orgtbl-format-line prevline))
4689 (setq prevline (pop *orgtbl-table*)))
4690 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4691 (*orgtbl-lend* *orgtbl-llend*)
4692 (*orgtbl-lfmt* *orgtbl-llfmt*))
4693 (orgtbl-format-line prevline))))))
4696 (defun orgtbl-to-generic (table params &optional backend)
4697 "Convert the orgtbl-mode TABLE to some other format.
4698 This generic routine can be used for many standard cases.
4699 TABLE is a list, each entry either the symbol `hline' for a horizontal
4700 separator line, or a list of fields for that line.
4701 PARAMS is a property list of parameters that can influence the conversion.
4702 A third optional argument BACKEND can be used to convert the content of
4703 the cells using a specific export back-end.
4705 For the generic converter, some parameters are obligatory: you need to
4706 specify either :lfmt, or all of (:lstart :lend :sep).
4708 Valid parameters are:
4710 :splice When set to t, return only table body lines, don't wrap
4711 them into :tstart and :tend. Default is nil. When :splice
4712 is non-nil, this also means that the exporter should not look
4713 for and interpret header and footer sections.
4715 :hline String to be inserted on horizontal separation lines.
4716 May be nil to ignore hlines.
4718 :sep Separator between two fields
4719 :remove-nil-lines Do not include lines that evaluate to nil.
4721 Each in the following group may be either a string or a function
4722 of no arguments returning a string:
4724 :tstart String to start the table. Ignored when :splice is t.
4725 :tend String to end the table. Ignored when :splice is t.
4726 :lstart String to start a new table line.
4727 :llstart String to start the last table line, defaults to :lstart.
4728 :lend String to end a table line
4729 :llend String to end the last table line, defaults to :lend.
4731 Each in the following group may be a string, a function of one
4732 argument (the field or line) returning a string, or a plist
4733 mapping columns to either of the above:
4735 :lfmt Format for entire line, with enough %s to capture all fields.
4736 If this is present, :lstart, :lend, and :sep are ignored.
4737 :llfmt Format for the entire last line, defaults to :lfmt.
4738 :fmt A format to be used to wrap the field, should contain
4739 %s for the original field value. For example, to wrap
4740 everything in dollars, you could use :fmt \"$%s$\".
4741 This may also be a property list with column numbers and
4742 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4743 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4744 Same as above, specific for the header lines in the table.
4745 All lines before the first hline are treated as header.
4746 If any of these is not present, the data line value is used.
4748 This may be either a string or a function of two arguments:
4750 :efmt Use this format to print numbers with exponentials.
4751 The format should have %s twice for inserting mantissa
4752 and exponent, for example \"%s\\\\times10^{%s}\". This
4753 may also be a property list with column numbers and
4754 formats. :fmt will still be applied after :efmt.
4756 In addition to this, the parameters :skip and :skipcols are always handled
4757 directly by `orgtbl-send-table'. See manual."
4758 (let* ((splicep (plist-get params :splice))
4759 (hline (plist-get params :hline))
4760 (skipheadrule (plist-get params :skipheadrule))
4761 (remove-nil-linesp (plist-get params :remove-nil-lines))
4762 (remove-newlines (plist-get params :remove-newlines))
4763 (*orgtbl-hline* hline)
4764 (*orgtbl-table* table)
4765 (*orgtbl-sep* (plist-get params :sep))
4766 (*orgtbl-efmt* (plist-get params :efmt))
4767 (*orgtbl-lstart* (plist-get params :lstart))
4768 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4769 (*orgtbl-lend* (plist-get params :lend))
4770 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4771 (*orgtbl-lfmt* (plist-get params :lfmt))
4772 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4773 (*orgtbl-fmt* (plist-get params :fmt))
4775 ;; Convert cells content to backend BACKEND
4777 (setq *orgtbl-table*
4783 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4789 (when (plist-member params :tstart)
4790 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4791 (if tstart (push tstart *orgtbl-rtn*)))))
4792 ;; If we have a heading, format it and handle the trailing hline.
4793 (if (and (not splicep)
4794 (or (consp (car *orgtbl-table*))
4795 (consp (nth 1 *orgtbl-table*)))
4796 (memq 'hline (cdr *orgtbl-table*)))
4798 (when (eq 'hline (car *orgtbl-table*))
4799 ;; There is a hline before the first data line
4800 (and hline (push hline *orgtbl-rtn*))
4801 (pop *orgtbl-table*))
4802 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4804 (*orgtbl-llstart* (or (plist-get params :hllstart)
4806 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4807 (*orgtbl-llend* (or (plist-get params :hllend)
4808 (plist-get params :hlend) *orgtbl-llend*))
4809 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4810 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4811 (plist-get params :hlfmt) *orgtbl-llfmt*))
4812 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4813 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4814 (orgtbl-format-section 'hline))
4815 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4816 (pop *orgtbl-table*)))
4817 ;; Now format the main section.
4818 (orgtbl-format-section nil)
4820 (when (plist-member params :tend)
4821 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4822 (if tend (push tend *orgtbl-rtn*)))))
4823 (mapconcat (if remove-newlines
4825 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4827 (nreverse (if remove-nil-linesp
4828 (remq nil *orgtbl-rtn*)
4829 *orgtbl-rtn*)) "\n")))
4832 (defun orgtbl-to-tsv (table params)
4833 "Convert the orgtbl-mode table to TAB separated material."
4834 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4836 (defun orgtbl-to-csv (table params)
4837 "Convert the orgtbl-mode table to CSV material.
4838 This does take care of the proper quoting of fields with comma or quotes."
4839 (orgtbl-to-generic table (org-combine-plists
4840 '(:sep "," :fmt org-quote-csv-field)
4844 (defun orgtbl-to-latex (table params)
4845 "Convert the orgtbl-mode TABLE to LaTeX.
4846 TABLE is a list, each entry either the symbol `hline' for a horizontal
4847 separator line, or a list of fields for that line.
4848 PARAMS is a property list of parameters that can influence the conversion.
4849 Supports all parameters from `orgtbl-to-generic'. Most important for
4852 :splice When set to t, return only table body lines, don't wrap
4853 them into a tabular environment. Default is nil.
4855 :fmt A format to be used to wrap the field, should contain %s for the
4856 original field value. For example, to wrap everything in dollars,
4857 use :fmt \"$%s$\". This may also be a property list with column
4858 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4859 The format may also be a function that formats its one argument.
4861 :efmt Format for transforming numbers with exponentials. The format
4862 should have %s twice for inserting mantissa and exponent, for
4863 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4864 This may also be a property list with column numbers and formats.
4865 The format may also be a function that formats its two arguments.
4867 :llend If you find too much space below the last line of a table,
4868 pass a value of \"\" for :llend to suppress the final \\\\.
4870 The general parameters :skip and :skipcols have already been applied when
4871 this function is called."
4872 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4873 org-table-last-alignment ""))
4876 :tstart (concat "\\begin{tabular}{" alignment "}")
4877 :tend "\\end{tabular}"
4878 :lstart "" :lend " \\\\" :sep " & "
4879 :efmt "%s\\,(%s)" :hline "\\hline")))
4881 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4884 (defun orgtbl-to-html (table params)
4885 "Convert the orgtbl-mode TABLE to HTML.
4886 TABLE is a list, each entry either the symbol `hline' for a horizontal
4887 separator line, or a list of fields for that line.
4888 PARAMS is a property list of parameters that can influence the conversion.
4889 Currently this function recognizes the following parameters:
4891 :splice When set to t, return only table body lines, don't wrap
4892 them into a <table> environment. Default is nil.
4894 The general parameters :skip and :skipcols have already been applied when
4895 this function is called. The function does *not* use `orgtbl-to-generic',
4896 so you cannot specify parameters for it."
4898 (let ((output (org-export-string-as
4899 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4900 (if (not (plist-get params :splice)) output
4902 (replace-regexp-in-string
4903 "\\`<table .*>\n" ""
4904 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4907 (defun orgtbl-to-texinfo (table params)
4908 "Convert the orgtbl-mode TABLE to TeXInfo.
4909 TABLE is a list, each entry either the symbol `hline' for a horizontal
4910 separator line, or a list of fields for that line.
4911 PARAMS is a property list of parameters that can influence the conversion.
4912 Supports all parameters from `orgtbl-to-generic'. Most important for
4915 :splice nil/t When set to t, return only table body lines, don't wrap
4916 them into a multitable environment. Default is nil.
4918 :fmt fmt A format to be used to wrap the field, should contain
4919 %s for the original field value. For example, to wrap
4920 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4921 This may also be a property list with column numbers and
4922 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4923 Each format also may be a function that formats its one
4926 :cf \"f1 f2..\" The column fractions for the table. By default these
4927 are computed automatically from the width of the columns
4930 The general parameters :skip and :skipcols have already been applied when
4931 this function is called."
4932 (let* ((total (float (apply '+ org-table-last-column-widths)))
4933 (colfrac (or (plist-get params :cf)
4935 (lambda (x) (format "%.3f" (/ (float x) total)))
4936 org-table-last-column-widths " ")))
4939 :tstart (concat "@multitable @columnfractions " colfrac)
4940 :tend "@end multitable"
4941 :lstart "@item " :lend "" :sep " @tab "
4942 :hlstart "@headitem ")))
4943 (require 'ox-texinfo)
4944 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4947 (defun orgtbl-to-orgtbl (table params)
4948 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4949 Useful when slicing one table into many. The :hline, :sep,
4950 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4951 and :tend suppress strings without splicing; they can be set to
4952 provide ORGTBL directives for the generated table."
4956 :tstart nil :tend nil
4961 (params (org-combine-plists params2 params)))
4963 (insert (orgtbl-to-generic table params))
4964 (goto-char (point-min))
4965 (while (re-search-forward org-table-hline-regexp nil t)
4967 (buffer-substring 1 (buffer-size)))))
4969 (defun orgtbl-to-table.el (table params)
4970 "Convert the orgtbl-mode TABLE into a table.el table."
4972 (insert (orgtbl-to-orgtbl table params))
4974 (replace-regexp-in-string
4976 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4978 (defun orgtbl-to-unicode (table params)
4979 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4980 You need the ascii-art-to-unicode.el package for this. You can download
4981 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4983 (insert (orgtbl-to-table.el table params))
4984 (goto-char (point-min))
4985 (if (or (featurep 'ascii-art-to-unicode)
4986 (require 'ascii-art-to-unicode nil t))
4988 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4989 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4990 "Link to ascii-art-to-unicode.el") org-stored-links))
4991 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4994 (defun org-table-get-remote-range (name-or-id form)
4995 "Get a field value or a list of values in a range from table at ID.
4997 NAME-OR-ID may be the name of a table in the current file as set
4998 by a \"#+NAME:\" directive. The first table following this line
4999 will then be used. Alternatively, it may be an ID referring to
5000 any entry, also in a different file. In this case, the first
5001 table in that entry will be referenced.
5002 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5003 \"@I$2..@II$2\". All the references must be absolute, not relative.
5005 The return value is either a single string for a single field, or a
5006 list of the fields in the rectangle."
5008 (let ((case-fold-search t) (id-loc nil)
5009 ;; Protect a bunch of variables from being overwritten
5010 ;; by the context of the remote table
5011 org-table-column-names org-table-column-name-regexp
5012 org-table-local-parameters org-table-named-field-locations
5013 org-table-current-line-types org-table-current-begin-line
5014 org-table-current-begin-pos org-table-dlines
5015 org-table-current-ncol
5016 org-table-hlines org-table-last-alignment
5017 org-table-last-column-widths org-table-last-alignment
5018 org-table-last-column-widths tbeg
5020 (setq form (org-table-convert-refs-to-rc form))
5025 (goto-char (point-min))
5026 (if (re-search-forward
5027 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5028 (regexp-quote name-or-id) "[ \t]*$")
5030 (setq buffer (current-buffer) loc (match-beginning 0))
5031 (setq id-loc (org-id-find name-or-id 'marker))
5032 (unless (and id-loc (markerp id-loc))
5033 (user-error "Can't find remote table \"%s\"" name-or-id))
5034 (setq buffer (marker-buffer id-loc)
5035 loc (marker-position id-loc))
5036 (move-marker id-loc nil)))
5037 (with-current-buffer buffer
5043 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
5044 (not (match-beginning 1)))
5045 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5046 (setq tbeg (point-at-bol))
5047 (org-table-get-specials)
5048 (setq form (org-table-formula-substitute-names
5049 (org-table-formula-handle-first/last-rc form)))
5050 (if (and (string-match org-table-range-regexp form)
5051 (> (length (match-string 0 form)) 1))
5053 (org-table-get-range (match-string 0 form) tbeg 1))
5056 (defun org-table-remote-reference-indirection (form)
5057 "Return formula with table remote references substituted by indirection.
5058 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5059 This indirection works only with the format @ROW$COLUMN. The
5060 format \"B3\" is not supported because it can not be
5061 distinguished from a plain table name or ID."
5063 (while (string-match (concat
5064 ;; Same as in `org-table-eval-formula'.
5065 "\\<remote([ \t]*\\("
5066 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5068 ;; Same as in `org-table-eval-formula'.
5069 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5072 ;; The position of the character as far as possible to the right
5073 ;; that will not be replaced and particularly not be shifted by
5075 (setq start (match-beginning 1))
5076 ;; Substitute the remote reference with the value found in the
5081 (org-table-get-range (org-table-formula-handle-first/last-rc
5082 (match-string 1 form))))
5086 (defmacro org-define-lookup-function (mode)
5087 (let ((mode-str (symbol-name mode))
5088 (first-p (equal mode 'first))
5089 (all-p (equal mode 'all)))
5090 (let ((plural-str (if all-p "s" "")))
5091 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5092 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5093 If R-LIST is nil, return matching element%s of S-LIST.
5094 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5095 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5096 This function is generated by a call to the macro `org-define-lookup-function'."
5097 mode-str plural-str plural-str plural-str)
5098 (let ,(let ((lvars '((p (or predicate 'equal))
5100 (rl (or r-list s-list))
5102 (if first-p (add-to-list 'lvars '(match-p nil)))
5104 (while ,(if first-p '(and (not match-p) sl) 'sl)
5106 (if (funcall p val (car sl))
5108 ,(if first-p '(setq match-p t))
5109 (let ((rval (car rl)))
5110 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5111 (setq sl (cdr sl) rl (cdr rl))))
5114 (org-define-lookup-function first)
5115 (org-define-lookup-function last)
5116 (org-define-lookup-function all)
5118 (provide 'org-table)
5121 ;; generated-autoload-file: "org-loaddefs.el"
5124 ;;; org-table.el ends here