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