1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org-mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org-mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
41 (declare-function org-export-string-as
"ox"
42 (string backend
&optional body-only ext-plist
))
43 (declare-function aa2u
"ext:ascii-art-to-unicode" ())
44 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
48 (defvar constants-unit-system
)
49 (defvar org-table-follow-field-mode
)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, otherwise, if table is not sent, the functions
57 (defvar org-table-TBLFM-begin-regexp
"|\n[ \t]*#\\+TBLFM: ")
59 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
60 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
61 In the optimized version, the table editor takes over all simple keys that
62 normally just insert a character. In tables, the characters are inserted
63 in a way to minimize disturbing the table structure (i.e. in overwrite mode
64 for empty fields). Outside tables, the correct binding of the keys is
67 The default for this option is t if the optimized version is also used in
68 Org-mode. See the variable `org-enable-table-editor' for details. Changing
69 this variable requires a restart of Emacs to become effective."
73 (defcustom orgtbl-radio-table-templates
74 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
75 % END RECEIVE ORGTBL %n
77 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
80 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
81 @c END RECEIVE ORGTBL %n
83 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
86 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
87 <!-- END RECEIVE ORGTBL %n -->
89 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
92 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
93 #+ END RECEIVE ORGTBL %n
95 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
98 "Templates for radio tables in different major modes.
99 Each template must define lines that will be treated as a comment and that
100 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
101 lines where \"%n\" will be replaced with the name of the table during
102 insertion of the template. The transformed table will later be inserted
105 The template should also contain a minimal table in a multiline comment.
106 If multiline comments are not possible in the buffer language,
107 you can pack it into a string that will not be used when the code
108 is compiled or executed. Above the table will you need a line with
109 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
110 convert the table into a data structure useful in the
111 language of the buffer. Check the manual for the section on
112 \"Translator functions\", and more generally check out
113 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
115 All occurrences of %n in a template will be replaced with the name of the
116 table, obtained by prompting the user."
119 (list (symbol :tag
"Major mode")
120 (string :tag
"Format"))))
122 (defgroup org-table-settings nil
123 "Settings for tables in Org-mode."
124 :tag
"Org Table Settings"
127 (defcustom org-table-default-size
"5x2"
128 "The default size for newly created tables, Columns x Rows."
129 :group
'org-table-settings
132 (defcustom org-table-number-regexp
133 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
134 "Regular expression for recognizing numbers in table columns.
135 If a table column contains mostly numbers, it will be aligned to the
136 right. If not, it will be aligned to the left.
138 The default value of this option is a regular expression which allows
139 anything which looks remotely like a number as used in scientific
140 context. For example, all of the following will be considered a
142 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
144 Other options offered by the customize interface are more restrictive."
145 :group
'org-table-settings
147 (const :tag
"Positive Integers"
149 (const :tag
"Integers"
151 (const :tag
"Floating Point Numbers"
152 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
153 (const :tag
"Floating Point Number or Integer"
154 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
155 (const :tag
"Exponential, Floating point, Integer"
156 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
157 (const :tag
"Very General Number-Like, including hex and Calc radix"
158 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
159 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
160 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
161 (string :tag
"Regexp:")))
163 (defcustom org-table-number-fraction
0.5
164 "Fraction of numbers in a column required to make the column align right.
165 In a column all non-white fields are considered. If at least
166 this fraction of fields is matched by `org-table-number-regexp',
167 alignment to the right border applies."
168 :group
'org-table-settings
171 (defgroup org-table-editing nil
172 "Behavior of tables during editing in Org-mode."
173 :tag
"Org Table Editing"
176 (defcustom org-table-automatic-realign t
177 "Non-nil means automatically re-align table when pressing TAB or RETURN.
178 When nil, aligning is only done with \\[org-table-align], or after column
180 :group
'org-table-editing
183 (defcustom org-table-auto-blank-field t
184 "Non-nil means automatically blank table field when starting to type into it.
185 This only happens when typing immediately after a field motion
186 command (TAB, S-TAB or RET).
187 Only relevant when `org-enable-table-editor' is equal to `optimized'."
188 :group
'org-table-editing
191 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
192 "Non-nil means automatically exit the follow mode.
193 When nil, the follow mode will stay on and be active in any table
194 the cursor enters. Since the table follow filed mode messes with the
195 window configuration, it is not recommended to set this variable to nil,
196 except maybe locally in a special file that has mostly tables with long
202 (defcustom org-table-fix-formulas-confirm nil
203 "Whether the user should confirm when Org fixes formulas."
204 :group
'org-table-editing
207 (const :tag
"with yes-or-no" yes-or-no-p
)
208 (const :tag
"with y-or-n" y-or-n-p
)
209 (const :tag
"no confirmation" nil
)))
210 (put 'org-table-fix-formulas-confirm
212 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
214 (defcustom org-table-tab-jumps-over-hlines t
215 "Non-nil means tab in the last column of a table with jump over a hline.
216 If a horizontal separator line is following the current line,
217 `org-table-next-field' can either create a new row before that line, or jump
218 over the line. When this option is nil, a new line will be created before
220 :group
'org-table-editing
223 (defgroup org-table-calculation nil
224 "Options concerning tables in Org-mode."
225 :tag
"Org Table Calculation"
228 (defcustom org-table-use-standard-references
'from
229 "Should org-mode work with table references like B3 instead of @3$2?
232 from accept as input, do not present for editing
233 t accept as input and present for editing"
234 :group
'org-table-calculation
236 (const :tag
"Never, don't even check user input for them" nil
)
237 (const :tag
"Always, both as user input, and when editing" t
)
238 (const :tag
"Convert user input, don't offer during editing" from
)))
240 (defcustom org-table-copy-increment t
241 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
242 :group
'org-table-calculation
244 :package-version
'(Org .
"8.3")
246 (const :tag
"Use the difference between the current and the above fields" t
)
247 (integer :tag
"Use a number" 1)
248 (const :tag
"Don't increment the value when copying a field" nil
)))
250 (defcustom org-calc-default-modes
251 '(calc-internal-prec 12
252 calc-float-format
(float 8)
255 calc-symbolic-mode nil
256 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
257 calc-display-working-message t
259 "List with Calc mode settings for use in `calc-eval' for table formulas.
260 The list must contain alternating symbols (Calc modes variables and values).
261 Don't remove any of the default settings, just change the values. Org-mode
262 relies on the variables to be present in the list."
263 :group
'org-table-calculation
266 (defcustom org-table-duration-custom-format
'hours
267 "Format for the output of calc computations like $1+$2;t.
268 The default value is 'hours, and will output the results as a
269 number of hours. Other allowed values are 'seconds, 'minutes and
270 'days, and the output will be a fraction of seconds, minutes or
272 :group
'org-table-calculation
274 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
275 (symbol :tag
"Minutes" 'minutes
)
276 (symbol :tag
"Hours " 'hours
)
277 (symbol :tag
"Days " 'days
)))
279 (defcustom org-table-formula-field-format
"%s"
280 "Format for fields which contain the result of a formula.
281 For example, using \"~%s~\" will display the result within tilde
282 characters. Beware that modifying the display can prevent the
283 field from being used in another formula."
284 :group
'org-table-settings
288 (defcustom org-table-formula-evaluate-inline t
289 "Non-nil means TAB and RET evaluate a formula in current table field.
290 If the current field starts with an equal sign, it is assumed to be a formula
291 which should be evaluated as described in the manual and in the documentation
292 string of the command `org-table-eval-formula'. This feature requires the
294 When this variable is nil, formula calculation is only available through
295 the command \\[org-table-eval-formula]."
296 :group
'org-table-calculation
299 (defcustom org-table-formula-use-constants t
300 "Non-nil means interpret constants in formulas in tables.
301 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
302 by the value given in `org-table-formula-constants', or by a value obtained
303 from the `constants.el' package."
304 :group
'org-table-calculation
307 (defcustom org-table-formula-constants nil
308 "Alist with constant names and values, for use in table formulas.
309 The car of each element is a name of a constant, without the `$' before it.
310 The cdr is the value as a string. For example, if you'd like to use the
311 speed of light in a formula, you would configure
313 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
315 and then use it in an equation like `$1*$c'.
317 Constants can also be defined on a per-file basis using a line like
319 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
320 :group
'org-table-calculation
322 (cons (string :tag
"name")
323 (string :tag
"value"))))
325 (defcustom org-table-allow-automatic-line-recalculation t
326 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
327 Automatically means when TAB or RET or C-c C-c are pressed in the line."
328 :group
'org-table-calculation
331 (defcustom org-table-error-on-row-ref-crossing-hline t
332 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
336 (defcustom org-table-relative-ref-may-cross-hline t
337 "Non-nil means relative formula references may cross hlines.
338 Here are the allowed values:
340 nil Relative references may not cross hlines. They will reference the
341 field next to the hline instead. Coming from below, the reference
342 will be to the field below the hline. Coming from above, it will be
344 t Relative references may cross hlines.
345 error An attempt to cross a hline will throw an error.
347 It is probably good to never set this variable to nil, for the sake of
348 portability of tables."
349 :group
'org-table-calculation
351 (const :tag
"Allow to cross" t
)
352 (const :tag
"Stick to hline" nil
)
353 (const :tag
"Error on attempt to cross" error
)))
355 (defgroup org-table-import-export nil
356 "Options concerning table import and export in Org-mode."
357 :tag
"Org Table Import Export"
360 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
361 "Default export parameters for `org-table-export'.
362 These can be overridden for a specific table by setting the
363 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
364 radio tables for the different export transformations and
365 available parameters."
366 :group
'org-table-import-export
369 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
370 "Detects a table line marked for automatic recalculation.")
371 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
372 "Detects a table line marked for automatic recalculation.")
373 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
374 "Detects a table line marked for automatic recalculation.")
375 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
376 "Searching from within a table (any type) this finds the first line outside the table.")
377 (defvar org-table-last-highlighted-reference nil
)
378 (defvar org-table-formula-history nil
)
380 (defvar org-table-column-names nil
381 "Alist with column names, derived from the `!' line.")
382 (defvar org-table-column-name-regexp nil
383 "Regular expression matching the current column names.")
384 (defvar org-table-local-parameters nil
385 "Alist with parameter names, derived from the `$' line.")
386 (defvar org-table-named-field-locations nil
387 "Alist with locations of named fields.")
389 (defvar org-table-current-line-types nil
390 "Table row types, non-nil only for the duration of a command.")
391 (defvar org-table-current-begin-line nil
392 "Table begin line, non-nil only for the duration of a command.")
393 (defvar org-table-current-begin-pos nil
394 "Table begin position, non-nil only for the duration of a command.")
395 (defvar org-table-current-ncol nil
396 "Number of columns in table, non-nil only for the duration of a command.")
397 (defvar org-table-dlines nil
398 "Vector of data line line numbers in the current table.")
399 (defvar org-table-hlines nil
400 "Vector of hline line numbers in the current table.")
402 (defconst org-table-range-regexp
403 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
405 "Regular expression for matching ranges in formulas.")
407 (defconst org-table-range-regexp2
409 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
411 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
412 "Match a range for reference display.")
414 (defun org-table-colgroup-line-p (line)
415 "Is this a table line colgroup information?"
417 (and (string-match "[<>]\\|&[lg]t;" line
)
418 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
424 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
425 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
427 (defun org-table-cookie-line-p (line)
428 "Is this a table line with only alignment/width cookies?"
430 (and (string-match "[<>]\\|&[lg]t;" line
)
432 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
433 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
434 (not (delq nil
(mapcar
436 (not (or (equal s
"")
438 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
440 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
442 (org-split-string (match-string 1 line
)
443 "[ \t]*|[ \t]*")))))))
445 (defvar org-table-clean-did-remove-column nil
) ; dynamically scoped
446 (defun org-table-clean-before-export (lines &optional maybe-quoted
)
447 "Check if the table has a marking column.
448 If yes remove the column and the special lines."
449 (let ((special (if maybe-quoted
450 "^[ \t]*| *\\\\?[\#!$*_^/ ] *|"
451 "^[ \t]*| *[\#!$*_^/ ] *|"))
452 (ignore (if maybe-quoted
453 "^[ \t]*| *\\\\?[!$_^/] *|"
454 "^[ \t]*| *[!$_^/] *|")))
455 (setq org-table-clean-did-remove-column
459 (or (string-match org-table-hline-regexp line
)
460 (string-match special line
)))
466 ((or (org-table-colgroup-line-p line
) ;; colgroup info
467 (org-table-cookie-line-p line
) ;; formatting cookies
468 (and org-table-clean-did-remove-column
469 (string-match ignore line
))) ;; non-exportable data
471 ((and org-table-clean-did-remove-column
472 (or (string-match "^\\([ \t]*\\)|-+\\+" line
)
473 (string-match "^\\([ \t]*\\)|[^|]*|" line
)))
474 ;; remove the first column
475 (replace-match "\\1|" t nil line
))
479 (defconst org-table-translate-regexp
480 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
481 "Match a reference that needs translation, for reference display.")
484 (defun org-table-create-with-table.el
()
485 "Use the table.el package to insert a new table.
486 If there is already a table at point, convert between Org-mode tables
487 and table.el tables."
492 (if (y-or-n-p "Convert table to Org-mode table? ")
493 (org-table-convert)))
495 (when (y-or-n-p "Convert table to table.el table? ")
497 (org-table-convert)))
498 (t (call-interactively 'table-insert
))))
501 (defun org-table-create-or-convert-from-region (arg)
502 "Convert region to table, or create an empty table.
503 If there is an active region, convert it to a table, using the function
504 `org-table-convert-region'. See the documentation of that function
505 to learn how the prefix argument is interpreted to determine the field
507 If there is no such region, create an empty table with `org-table-create'."
509 (if (org-region-active-p)
510 (org-table-convert-region (region-beginning) (region-end) arg
)
511 (org-table-create arg
)))
514 (defun org-table-create (&optional size
)
515 "Query for a size and insert a table skeleton.
516 SIZE is a string Columns x Rows like for example \"3x2\"."
519 (setq size
(read-string
520 (concat "Table size Columns x Rows [e.g. "
521 org-table-default-size
"]: ")
522 "" nil org-table-default-size
)))
525 (indent (make-string (current-column) ?\
))
526 (split (org-split-string size
" *x *"))
527 (rows (string-to-number (nth 1 split
)))
528 (columns (string-to-number (car split
)))
529 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
531 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
532 (point-at-bol) (point)))
533 (beginning-of-line 1)
535 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
536 (dotimes (i rows
) (insert line
))
539 ;; Insert a hline after the first row.
547 (defun org-table-convert-region (beg0 end0
&optional separator
)
548 "Convert region to a table.
549 The region goes from BEG0 to END0, but these borders will be moved
550 slightly, to make sure a beginning of line in the first line is included.
552 SEPARATOR specifies the field separator in the lines. It can have the
555 '(4) Use the comma as a field separator
556 '(16) Use a TAB as field separator
557 '(64) Prompt for a regular expression as field separator
558 integer When a number, use that many spaces as field separator
559 regexp When a regular expression, use it to match the separator
560 nil When nil, the command tries to be smart and figure out the
561 separator in the following way:
562 - when each line contains a TAB, assume TAB-separated material
563 - when each line contains a comma, assume CSV material
564 - else, assume one or more SPACE characters as separator."
566 (let* ((beg (min beg0 end0
))
567 (end (max beg0 end0
))
569 (if (equal separator
'(64))
570 (setq separator
(read-regexp "Regexp for field separator")))
572 (beginning-of-line 1)
573 (setq beg
(point-marker))
575 (if (bolp) (backward-char 1) (end-of-line 1))
576 (setq end
(point-marker))
577 ;; Get the right field separator
582 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
583 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
586 (if (equal separator
'(4))
587 (while (< (point) end
)
588 ;; parse the csv stuff
590 ((looking-at "^") (insert "| "))
591 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
592 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
593 (replace-match "\\1")
594 (if (looking-at "\"") (insert "\"")))
595 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
596 ((looking-at "[ \t]*,") (replace-match " | "))
597 (t (beginning-of-line 2))))
599 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
600 ((equal separator
'(16)) "^\\|\t")
601 ((integerp separator
)
603 (user-error "Number of spaces in separator must be >= 1")
604 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
606 (format "^ *\\|%s" separator
))
607 (t (error "This should not happen"))))
608 (while (re-search-forward re end t
)
609 (replace-match "| " t t
)))
614 (defun org-table-import (file arg
)
615 "Import FILE as a table.
616 The file is assumed to be tab-separated. Such files can be produced by most
617 spreadsheet and database applications. If no tabs (at least one per line)
618 are found, lines will be split on whitespace into fields."
620 (or (bolp) (newline))
623 (insert-file-contents file
)
624 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
627 (defvar org-table-last-alignment
)
628 (defvar org-table-last-column-widths
)
630 (defun org-table-export (&optional file format
)
631 "Export table to a file, with configurable format.
632 Such a file can be imported into usual spreadsheet programs.
634 FILE can be the output file name. If not given, it will be taken
635 from a TABLE_EXPORT_FILE property in the current entry or higher
636 up in the hierarchy, or the user will be prompted for a file
637 name. FORMAT can be an export format, of the same kind as it
638 used when `orgtbl-mode' sends a table in a different format.
640 The command suggests a format depending on TABLE_EXPORT_FORMAT,
641 whether it is set locally or up in the hierarchy, then on the
642 extension of the given file name, and finally on the variable
643 `org-table-export-default-format'."
645 (unless (org-at-table-p) (user-error "No table at point"))
646 (org-table-align) ;; make sure we have everything we need
647 (let* ((beg (org-table-begin))
648 (end (org-table-end))
649 (txt (buffer-substring-no-properties beg end
))
650 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
651 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
652 "orgtbl-to-latex" "orgtbl-to-html"
653 "orgtbl-to-generic" "orgtbl-to-texinfo"
656 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
657 buf deffmt-readable fileext
)
659 (setq file
(read-file-name "Export table to: "))
660 (unless (or (not (file-exists-p file
))
661 (y-or-n-p (format "Overwrite file %s? " file
)))
662 (user-error "File not written")))
663 (if (file-directory-p file
)
664 (user-error "This is a directory path, not a file"))
665 (if (and (buffer-file-name)
666 (equal (file-truename file
)
667 (file-truename (buffer-file-name))))
668 (user-error "Please specify a file name that is different from current"))
669 (setq fileext
(concat (file-name-extension file
) "$"))
671 (setq deffmt-readable
672 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
673 org-table-export-default-format
))
674 (while (string-match "\t" deffmt-readable
)
675 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
676 (while (string-match "\n" deffmt-readable
)
677 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
678 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
679 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
680 (let* ((transform (intern (match-string 1 format
)))
681 (params (if (match-end 2)
682 (read (concat "(" (match-string 2 format
) ")"))))
683 (skip (plist-get params
:skip
))
684 (skipcols (plist-get params
:skipcols
))
685 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
686 (lines (org-table-clean-before-export lines
))
687 (i0 (if org-table-clean-did-remove-column
2 1))
690 (if (string-match org-table-hline-regexp x
)
693 (org-split-string (org-trim x
) "\\s-*|\\s-*")
696 (fun (if (= i0
2) 'cdr
'identity
))
697 (org-table-last-alignment
698 (org-remove-by-index (funcall fun org-table-last-alignment
)
700 (org-table-last-column-widths
701 (org-remove-by-index (funcall fun org-table-last-column-widths
)
704 (unless (fboundp transform
)
705 (user-error "No such transformation function %s" transform
))
706 (setq txt
(funcall transform table params
))
708 (with-current-buffer (find-file-noselect file
)
709 (setq buf
(current-buffer))
715 (message "Export done."))
716 (user-error "TABLE_EXPORT_FORMAT invalid"))))
718 (defvar org-table-aligned-begin-marker
(make-marker)
719 "Marker at the beginning of the table last aligned.
720 Used to check if cursor still is in that table, to minimize realignment.")
721 (defvar org-table-aligned-end-marker
(make-marker)
722 "Marker at the end of the table last aligned.
723 Used to check if cursor still is in that table, to minimize realignment.")
724 (defvar org-table-last-alignment nil
725 "List of flags for flushright alignment, from the last re-alignment.
726 This is being used to correctly align a single field after TAB or RET.")
727 (defvar org-table-last-column-widths nil
728 "List of max width of fields in each column.
729 This is being used to correctly align a single field after TAB or RET.")
730 (defvar org-table-formula-debug nil
731 "Non-nil means debug table formulas.
732 When nil, simply write \"#ERROR\" in corrupted fields.")
733 (make-variable-buffer-local 'org-table-formula-debug
)
734 (defvar org-table-overlay-coordinates nil
735 "Overlay coordinates after each align of a table.")
736 (make-variable-buffer-local 'org-table-overlay-coordinates
)
738 (defvar org-last-recalc-line nil
)
739 (defvar org-table-do-narrow t
) ; for dynamic scoping
740 (defconst org-narrow-column-arrow
"=>"
741 "Used as display property in narrowed table columns.")
744 (defun org-table-align ()
745 "Align the table at point by aligning all vertical bars."
749 (beg (org-table-begin))
750 (end (org-table-end))
751 ;; Current cursor position
752 (linepos (org-current-line))
753 (colpos (org-table-current-column))
754 (winstart (window-start))
755 (winstartline (org-current-line (min winstart
(1- (point-max)))))
756 lines
(new "") lengths l typenums ty fields maxfields i
764 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
766 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
767 emptystrings links dates emph raise narrow
768 falign falign1 fmax f1 f2 len c e space
)
770 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
771 ;; Check if we have links or dates
773 (setq links
(re-search-forward org-bracket-link-regexp end t
))
775 (setq emph
(and org-hide-emphasis-markers
776 (re-search-forward org-emph-re end t
)))
778 (setq raise
(and org-use-sub-superscripts
779 (re-search-forward org-match-substring-regexp end t
)))
781 (setq dates
(and org-display-custom-times
782 (re-search-forward org-ts-regexp-both end t
)))
783 ;; Make sure the link properties are right
784 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
785 ;; Make sure the date properties are right
786 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
787 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
788 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
790 ;; Check if we are narrowing any columns
792 (setq narrow
(and org-table-do-narrow
793 org-format-transports-properties-p
794 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
796 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
799 (setq lines
(org-split-string
800 (buffer-substring beg end
) "\n"))
801 ;; Store the indentation of the first line
802 (if (string-match "^ *" (car lines
))
803 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
804 ;; Mark the hlines by setting the corresponding element to nil
805 ;; At the same time, we remove trailing space.
806 (setq lines
(mapcar (lambda (l)
807 (if (string-match "^ *|-" l
)
809 (if (string-match "[ \t]+$" l
)
810 (substring l
0 (match-beginning 0))
813 ;; Get the data fields by splitting the lines.
816 (org-split-string l
" *| *"))
817 (delq nil
(copy-sequence lines
))))
818 ;; How many fields in the longest line?
820 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
822 (kill-region beg end
)
823 (org-table-create org-table-default-size
)
824 (user-error "Empty table - created default table")))
825 ;; A list of empty strings to fill any short rows on output
826 (setq emptystrings
(make-list maxfields
""))
827 ;; Check for special formatting.
829 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
830 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
831 ;; Check if there is an explicit width specified
833 (when (or narrow falign
)
834 (setq c column fmax nil falign1 nil
)
837 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
838 (if (match-end 1) (setq falign1
(match-string 1 e
)))
839 (if (and org-table-do-narrow
(match-end 2))
840 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
841 ;; Find fields that are wider than fmax, and shorten them
843 (loop for xx in column do
844 (when (and (stringp xx
)
845 (> (org-string-width xx
) fmax
))
846 (org-add-props xx nil
848 (concat "Clipped table field, use C-c ` to edit. Full value is:\n"
849 (org-no-properties (copy-sequence xx
))))
850 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
852 (user-error "Cannot narrow field starting with wide link \"%s\""
853 (match-string 0 xx
)))
854 (setq f2
(length xx
))
855 (if (= (org-string-width xx
)
859 (while (< (org-string-width (substring xx
0 f2
))
862 (add-text-properties f2
(length xx
) (list 'org-cwidth t
) xx
)
863 (add-text-properties (if (>= (string-width (substring xx
(1- f2
) f2
)) 2)
865 (list 'display org-narrow-column-arrow
)
867 ;; Get the maximum width for each column
868 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
870 ;; Get the fraction of numbers, to decide about alignment of the column
872 (push (equal (downcase falign1
) "r") typenums
)
873 (setq cnt
0 frac
0.0)
874 (loop for x in column do
877 (setq frac
( / (+ (* frac cnt
)
878 (if (string-match org-table-number-regexp x
) 1 0))
879 (setq cnt
(1+ cnt
))))))
880 (push (>= frac org-table-number-fraction
) typenums
)))
881 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
883 ;; Store the alignment of this table, for later editing of single fields
884 (setq org-table-last-alignment typenums
885 org-table-last-column-widths lengths
)
887 ;; With invisible characters, `format' does not get the field width right
888 ;; So we need to make these fields wide by hand.
889 (when (or links emph raise
)
890 (loop for i from
0 upto
(1- maxfields
) do
891 (setq len
(nth i lengths
))
892 (loop for j from
0 upto
(1- (length fields
)) do
893 (setq c
(nthcdr i
(car (nthcdr j fields
))))
894 (if (and (stringp (car c
))
895 (or (text-property-any 0 (length (car c
))
896 'invisible
'org-link
(car c
))
897 (text-property-any 0 (length (car c
))
898 'org-dwidth t
(car c
)))
899 (< (org-string-width (car c
)) len
))
901 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
902 (setcar c
(if (nth i typenums
)
903 (concat space
(car c
))
904 (concat (car c
) space
))))))))
906 ;; Compute the formats needed for output of the table
907 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
908 (while (setq l
(pop lengths
))
909 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
910 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
911 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
912 (setq rfmt
(concat rfmt
"\n")
913 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
917 (if l
(apply 'format rfmt
918 (append (pop fields
) emptystrings
))
921 (move-marker org-table-aligned-begin-marker
(point))
923 ;; Replace the old one
924 (delete-region (point) end
)
925 (move-marker end nil
)
926 (move-marker org-table-aligned-end-marker
(point))
927 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
928 (goto-char org-table-aligned-begin-marker
)
929 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
930 ;; Try to move to the old location
931 (org-goto-line winstartline
)
932 (setq winstart
(point-at-bol))
933 (org-goto-line linepos
)
934 (when (eq (window-buffer (selected-window)) (current-buffer))
935 (set-window-start (selected-window) winstart
'noforce
))
936 (org-table-goto-column colpos
)
937 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
938 (setq org-table-may-need-update nil
)
942 (defun org-table-begin (&optional table-type
)
943 "Find the beginning of the table and return its position.
944 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
946 (if (not (re-search-backward
947 (if table-type org-table-any-border-regexp
948 org-table-border-regexp
)
950 (progn (goto-char (point-min)) (point))
951 (goto-char (match-beginning 0))
952 (beginning-of-line 2)
956 (defun org-table-end (&optional table-type
)
957 "Find the end of the table and return its position.
958 With argument TABLE-TYPE, go to the end of a table.el-type table."
960 (if (not (re-search-forward
961 (if table-type org-table-any-border-regexp
962 org-table-border-regexp
)
964 (goto-char (point-max))
965 (goto-char (match-beginning 0)))
969 (defun org-table-justify-field-maybe (&optional new
)
970 "Justify the current field, text to left, number to right.
971 Optional argument NEW may specify text to replace the current field content."
973 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
974 ((org-at-table-hline-p))
976 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
978 (< (point) org-table-aligned-begin-marker
)
979 (>= (point) org-table-aligned-end-marker
)))
980 ;; This is not the same table, force a full re-align
981 (setq org-table-may-need-update t
))
982 (t ;; realign the current field, based on previous full realign
983 (let* ((pos (point)) s
984 (col (org-table-current-column))
985 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
988 (skip-chars-backward "^|\n")
989 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
991 (setq s
(match-string 1)
995 (buffer-substring-no-properties
996 (match-end 0) (match-beginning 0))) 3))
997 e
(not (= (match-beginning 2) (match-end 2))))
998 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
999 l
(if e
"|" (setq org-table-may-need-update t
) ""))
1002 (if (<= (org-string-width new
) l
)
1003 (setq n
(format f new
))
1004 (setq n
(concat new
"|") org-table-may-need-update t
)))
1005 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
1007 (let (org-table-may-need-update)
1008 (replace-match n t t
))))
1009 (setq org-table-may-need-update t
))
1010 (goto-char pos
))))))
1013 (defun org-table-next-field ()
1014 "Go to the next field in the current table, creating new lines as needed.
1015 Before doing so, re-align the table if necessary."
1017 (org-table-maybe-eval-formula)
1018 (org-table-maybe-recalculate-line)
1019 (if (and org-table-automatic-realign
1020 org-table-may-need-update
)
1022 (let ((end (org-table-end)))
1023 (if (org-at-table-hline-p)
1027 (re-search-forward "|" end
)
1028 (if (looking-at "[ \t]*$")
1029 (re-search-forward "|" end
))
1030 (if (and (looking-at "-")
1031 org-table-tab-jumps-over-hlines
1032 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1033 (goto-char (match-beginning 1)))
1034 (if (looking-at "-")
1036 (beginning-of-line 0)
1037 (org-table-insert-row 'below
))
1038 (if (looking-at " ") (forward-char 1))))
1040 (org-table-insert-row 'below
)))))
1043 (defun org-table-previous-field ()
1044 "Go to the previous field in the table.
1045 Before doing so, re-align the table if necessary."
1047 (org-table-justify-field-maybe)
1048 (org-table-maybe-recalculate-line)
1049 (if (and org-table-automatic-realign
1050 org-table-may-need-update
)
1052 (if (org-at-table-hline-p)
1056 (re-search-backward "|" (org-table-begin))
1057 (re-search-backward "|" (org-table-begin)))
1058 (error (user-error "Cannot move to previous table field")))
1059 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1060 (re-search-backward "|" (org-table-begin)))
1061 (if (looking-at "| ?")
1062 (goto-char (match-end 0))))
1064 (defun org-table-beginning-of-field (&optional n
)
1065 "Move to the end of the current table field.
1066 If already at or after the end, move to the end of the next table field.
1067 With numeric argument N, move N-1 fields forward first."
1069 (let ((pos (point)))
1072 (org-table-previous-field))
1073 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1074 (user-error "No more table fields before the current")
1075 (goto-char (match-end 0))
1076 (and (looking-at " ") (forward-char 1)))
1077 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1079 (defun org-table-end-of-field (&optional n
)
1080 "Move to the beginning of the current table field.
1081 If already at or before the beginning, move to the beginning of the
1083 With numeric argument N, move N-1 fields backward first."
1085 (let ((pos (point)))
1088 (org-table-next-field))
1089 (when (re-search-forward "|" (point-at-eol 1) t
)
1091 (skip-chars-backward " ")
1092 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1094 (if (<= (point) pos
) (org-table-end-of-field 2))))
1097 (defun org-table-next-row ()
1098 "Go to the next row (same column) in the current table.
1099 Before doing so, re-align the table if necessary."
1101 (org-table-maybe-eval-formula)
1102 (org-table-maybe-recalculate-line)
1103 (if (or (looking-at "[ \t]*$")
1104 (save-excursion (skip-chars-backward " \t") (bolp)))
1106 (if (and org-table-automatic-realign
1107 org-table-may-need-update
)
1109 (let ((col (org-table-current-column)))
1110 (beginning-of-line 2)
1111 (if (or (not (org-at-table-p))
1112 (org-at-table-hline-p))
1114 (beginning-of-line 0)
1115 (org-table-insert-row 'below
)))
1116 (org-table-goto-column col
)
1117 (skip-chars-backward "^|\n\r")
1118 (if (looking-at " ") (forward-char 1)))))
1121 (defun org-table-copy-down (n)
1122 "Copy the value of the current field one row below.
1124 If the field at the cursor is empty, copy the content of the
1125 nearest non-empty field above. With argument N, use the Nth
1128 If the current field is not empty, it is copied down to the next
1129 row, and the cursor is moved with it. Therefore, repeating this
1130 command causes the column to be filled row-by-row.
1132 If the variable `org-table-copy-increment' is non-nil and the
1133 field is an integer or a timestamp, it will be incremented while
1134 copying. By default, increment by the difference between the
1135 value in the current field and the one in the field above. To
1136 increment using a fixed integer, set `org-table-copy-increment'
1137 to a number. In the case of a timestamp, increment by days."
1139 (let* ((colpos (org-table-current-column))
1140 (col (current-column))
1141 (field (save-excursion (org-table-get-field)))
1142 (field-up (or (save-excursion
1143 (org-table-get (1- (org-table-current-line))
1144 (org-table-current-column))) ""))
1145 (non-empty (string-match "[^ \t]" field
))
1146 (non-empty-up (string-match "[^ \t]" field-up
))
1147 (beg (org-table-begin))
1150 (org-table-check-inside-data-field)
1155 (while (progn (beginning-of-line 1)
1156 (re-search-backward org-table-dataline-regexp
1158 (org-table-goto-column colpos t
)
1159 (if (and (looking-at
1160 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1161 (<= (setq n
(1- n
)) 0))
1162 (throw 'exit
(match-string 1))))))
1165 (while (progn (beginning-of-line 1)
1166 (re-search-backward org-table-dataline-regexp
1168 (org-table-goto-column colpos t
)
1169 (if (and (looking-at
1170 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1171 (<= (setq n
(1- n
)) 0))
1172 (throw 'exit
(match-string 1))))))
1173 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1174 ;; Above field was not empty, go down to the next row
1175 (setq txt
(org-trim field
))
1176 (org-table-next-row)
1177 (org-table-blank-field))
1178 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1180 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1181 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1182 (string-match org-ts-regexp3 txt
))
1183 (- (org-time-string-to-absolute txt
)
1184 (org-time-string-to-absolute txt-up
)))
1185 ((string-match org-ts-regexp3 txt
) 1)
1186 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1187 (- (string-to-number txt
)
1188 (string-to-number (match-string 0 txt-up
))))
1192 (user-error "No non-empty field found")
1193 (if (and org-table-copy-increment
1194 (not (equal orig-n
0))
1195 (string-match "^[-+^/*0-9eE.]+$" txt
)
1196 (< (string-to-number txt
) 100000000))
1197 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1199 (org-move-to-column col
)
1200 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1201 (org-timestamp-up-day inc
)
1202 (org-table-maybe-recalculate-line))
1204 (org-move-to-column col
))))
1206 (defun org-table-check-inside-data-field (&optional noerror
)
1207 "Is point inside a table data field?
1208 I.e. not on a hline or before the first or after the last column?
1209 This actually throws an error, so it aborts the current command."
1210 (if (or (not (org-at-table-p))
1211 (= (org-table-current-column) 0)
1212 (org-at-table-hline-p)
1213 (looking-at "[ \t]*$"))
1216 (user-error "Not in table data field"))
1219 (defvar org-table-clip nil
1220 "Clipboard for table regions.")
1222 (defun org-table-get (line column
)
1223 "Get the field in table line LINE, column COLUMN.
1224 If LINE is larger than the number of data lines in the table, the function
1225 returns nil. However, if COLUMN is too large, we will simply return an
1227 If LINE is nil, use the current line.
1228 If column is nil, use the current column."
1229 (setq column
(or column
(org-table-current-column)))
1231 (and (or (not line
) (org-table-goto-line line
))
1232 (org-trim (org-table-get-field column
)))))
1234 (defun org-table-put (line column value
&optional align
)
1235 "Put VALUE into line LINE, column COLUMN.
1236 When ALIGN is set, also realign the table."
1237 (setq column
(or column
(org-table-current-column)))
1238 (prog1 (save-excursion
1239 (and (or (not line
) (org-table-goto-line line
))
1240 (progn (org-table-goto-column column nil
'force
) t
)
1241 (org-table-get-field column value
)))
1242 (and align
(org-table-align))))
1244 (defun org-table-current-line ()
1245 "Return the index of the current data line."
1246 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1248 (goto-char (org-table-begin))
1249 (while (and (re-search-forward org-table-dataline-regexp end t
)
1251 (< (point-at-eol) pos
))))
1254 (defun org-table-goto-line (N)
1255 "Go to the Nth data line in the current table.
1256 Return t when the line exists, nil if it does not exist."
1257 (goto-char (org-table-begin))
1258 (let ((end (org-table-end)) (cnt 0))
1259 (while (and (re-search-forward org-table-dataline-regexp end t
)
1260 (< (setq cnt
(1+ cnt
)) N
)))
1264 (defun org-table-blank-field ()
1265 "Blank the current table field or active region."
1267 (org-table-check-inside-data-field)
1268 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1269 (let (org-table-clip)
1270 (org-table-cut-region (region-beginning) (region-end)))
1271 (skip-chars-backward "^|")
1273 (if (looking-at "|[^|\n]+")
1274 (let* ((pos (match-beginning 0))
1275 (match (match-string 0))
1276 (len (org-string-width match
)))
1277 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1278 (goto-char (+ 2 pos
))
1279 (substring match
1)))))
1281 (defun org-table-get-field (&optional n replace
)
1282 "Return the value of the field in column N of current row.
1283 N defaults to current field.
1284 If REPLACE is a string, replace field with this value. The return value
1285 is always the old value."
1286 (and n
(org-table-goto-column n
))
1287 (skip-chars-backward "^|\n")
1289 (if (looking-at "|[^|\r\n]*")
1290 (let* ((pos (match-beginning 0))
1291 (val (buffer-substring (1+ pos
) (match-end 0))))
1293 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1295 (goto-char (min (point-at-eol) (+ 2 pos
)))
1297 (forward-char 1) ""))
1300 (defun org-table-field-info (arg)
1301 "Show info about the current field, and highlight any reference at point."
1303 (unless (org-at-table-p) (user-error "Not at a table"))
1304 (org-table-get-specials)
1306 (let* ((pos (point))
1307 (col (org-table-current-column))
1308 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1309 (name (car (rassoc (list (org-current-line) col
)
1310 org-table-named-field-locations
)))
1311 (eql (org-table-expand-lhs-ranges
1314 (cons (org-table-formula-handle-first/last-rc
1316 (org-table-get-stored-formulas))))
1317 (dline (org-table-current-dline))
1318 (ref (format "@%d$%d" dline col
))
1319 (ref1 (org-table-convert-refs-to-an ref
))
1320 (fequation (or (assoc name eql
) (assoc ref eql
)))
1321 (cequation (assoc (int-to-string col
) eql
))
1322 (eqn (or fequation cequation
)))
1323 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1324 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1327 (org-table-show-reference 'local
)
1329 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1331 (if cname
(concat " or $" cname
) "")
1333 (if name
(concat " or $" name
) "")
1334 ;; FIXME: formula info not correct if special table line
1336 (concat ", formula: "
1337 (org-table-formula-to-user
1339 (if (string-match "^[$@]"(car eqn
)) "" "$")
1340 (car eqn
) "=" (cdr eqn
))))
1343 (defun org-table-current-column ()
1344 "Find out which column we are in."
1346 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1348 (let ((cnt 0) (pos (point)))
1349 (beginning-of-line 1)
1350 (while (search-forward "|" pos t
)
1351 (setq cnt
(1+ cnt
)))
1352 (when (org-called-interactively-p 'interactive
)
1353 (message "In table column %d" cnt
))
1357 (defun org-table-current-dline ()
1358 "Find out what table data line we are in.
1359 Only data lines count for this."
1361 (when (org-called-interactively-p 'any
)
1362 (org-table-check-inside-data-field))
1364 (let ((cnt 0) (pos (point)))
1365 (goto-char (org-table-begin))
1366 (while (<= (point) pos
)
1367 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1368 (beginning-of-line 2))
1369 (when (org-called-interactively-p 'any
)
1370 (message "This is table line %d" cnt
))
1374 (defun org-table-goto-column (n &optional on-delim force
)
1375 "Move the cursor to the Nth column in the current table line.
1376 With optional argument ON-DELIM, stop with point before the left delimiter
1378 If there are less than N fields, just go to after the last delimiter.
1379 However, when FORCE is non-nil, create new columns if necessary."
1381 (beginning-of-line 1)
1383 (while (and (> (setq n
(1- n
)) -
1)
1384 (or (search-forward "|" (point-at-eol) t
)
1386 (progn (end-of-line 1)
1387 (skip-chars-backward "^|")
1390 (when (and force
(not (looking-at ".*|")))
1391 (save-excursion (end-of-line 1) (insert " | ")))
1394 (if (looking-at " ") (forward-char 1)))))
1397 (defun org-table-insert-column ()
1398 "Insert a new column into the table."
1400 (if (not (org-at-table-p))
1401 (user-error "Not at a table"))
1402 (org-table-find-dataline)
1403 (let* ((col (max 1 (org-table-current-column)))
1404 (beg (org-table-begin))
1405 (end (org-table-end))
1406 ;; Current cursor position
1407 (linepos (org-current-line))
1410 (while (< (point) end
)
1411 (if (org-at-table-hline-p)
1413 (org-table-goto-column col t
)
1415 (beginning-of-line 2))
1416 (move-marker end nil
)
1417 (org-goto-line linepos
)
1418 (org-table-goto-column colpos
)
1420 (when (or (not org-table-fix-formulas-confirm
)
1421 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1422 (org-table-fix-formulas "$" nil
(1- col
) 1)
1423 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1425 (defun org-table-find-dataline ()
1426 "Find a data line in the current table, which is needed for column commands."
1427 (if (and (org-at-table-p)
1428 (not (org-at-table-hline-p)))
1430 (let ((col (current-column))
1431 (end (org-table-end)))
1432 (org-move-to-column col
)
1433 (while (and (< (point) end
)
1434 (or (not (= (current-column) col
))
1435 (org-at-table-hline-p)))
1436 (beginning-of-line 2)
1437 (org-move-to-column col
))
1438 (if (and (org-at-table-p)
1439 (not (org-at-table-hline-p)))
1442 "Please position cursor in a data line for column operations")))))
1444 (defun org-table-line-to-dline (line &optional above
)
1445 "Turn a buffer line number into a data line number.
1446 If there is no data line in this line, return nil.
1447 If there is no matching dline (most likely te reference was a hline), the
1448 first dline below it is used. When ABOVE is non-nil, the one above is used."
1450 (let ((ll (length org-table-dlines
))
1456 (if (<= (aref org-table-dlines i
) line
)
1461 (if (>= (aref org-table-dlines i
) line
)
1467 (defun org-table-delete-column ()
1468 "Delete a column from the table."
1470 (if (not (org-at-table-p))
1471 (user-error "Not at a table"))
1472 (org-table-find-dataline)
1473 (org-table-check-inside-data-field)
1474 (let* ((col (org-table-current-column))
1475 (beg (org-table-begin))
1476 (end (org-table-end))
1477 ;; Current cursor position
1478 (linepos (org-current-line))
1481 (while (< (point) end
)
1482 (if (org-at-table-hline-p)
1484 (org-table-goto-column col t
)
1485 (and (looking-at "|[^|\n]+|")
1486 (replace-match "|")))
1487 (beginning-of-line 2))
1488 (move-marker end nil
)
1489 (org-goto-line linepos
)
1490 (org-table-goto-column colpos
)
1492 (when (or (not org-table-fix-formulas-confirm
)
1493 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1494 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1496 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1500 (defun org-table-move-column-right ()
1501 "Move column to the right."
1503 (org-table-move-column nil
))
1505 (defun org-table-move-column-left ()
1506 "Move column to the left."
1508 (org-table-move-column 'left
))
1511 (defun org-table-move-column (&optional left
)
1512 "Move the current column to the right. With arg LEFT, move to the left."
1514 (if (not (org-at-table-p))
1515 (user-error "Not at a table"))
1516 (org-table-find-dataline)
1517 (org-table-check-inside-data-field)
1518 (let* ((col (org-table-current-column))
1519 (col1 (if left
(1- col
) col
))
1520 (beg (org-table-begin))
1521 (end (org-table-end))
1522 ;; Current cursor position
1523 (linepos (org-current-line))
1524 (colpos (if left
(1- col
) (1+ col
))))
1525 (if (and left
(= col
1))
1526 (user-error "Cannot move column further left"))
1527 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1528 (user-error "Cannot move column further right"))
1530 (while (< (point) end
)
1531 (if (org-at-table-hline-p)
1533 (org-table-goto-column col1 t
)
1534 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1535 (replace-match "|\\2|\\1|")))
1536 (beginning-of-line 2))
1537 (move-marker end nil
)
1538 (org-goto-line linepos
)
1539 (org-table-goto-column colpos
)
1541 (when (or (not org-table-fix-formulas-confirm
)
1542 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1543 (org-table-fix-formulas
1544 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1545 (cons (number-to-string colpos
) (number-to-string col
))))
1546 (org-table-fix-formulas
1547 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1548 (cons (number-to-string colpos
) (number-to-string col
)))))))
1551 (defun org-table-move-row-down ()
1552 "Move table row down."
1554 (org-table-move-row nil
))
1556 (defun org-table-move-row-up ()
1557 "Move table row up."
1559 (org-table-move-row 'up
))
1562 (defun org-table-move-row (&optional up
)
1563 "Move the current table line down. With arg UP, move it up."
1565 (let* ((col (current-column))
1567 (hline1p (save-excursion (beginning-of-line 1)
1568 (looking-at org-table-hline-regexp
)))
1569 (dline1 (org-table-current-dline))
1570 (dline2 (+ dline1
(if up -
1 1)))
1573 (beginning-of-line tonew
)
1574 (unless (org-at-table-p)
1576 (user-error "Cannot move row further"))
1577 (setq hline2p
(looking-at org-table-hline-regexp
))
1579 (beginning-of-line 1)
1581 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1582 (delete-region (point) (1+ (point-at-eol)))
1583 (beginning-of-line tonew
)
1585 (beginning-of-line 0)
1586 (org-move-to-column col
)
1587 (unless (or hline1p hline2p
1588 (not (or (not org-table-fix-formulas-confirm
)
1589 (funcall org-table-fix-formulas-confirm
1590 "Fix formulas? "))))
1591 (org-table-fix-formulas
1592 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1593 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1596 (defun org-table-insert-row (&optional arg
)
1597 "Insert a new row above the current line into the table.
1598 With prefix ARG, insert below the current line."
1600 (if (not (org-at-table-p))
1601 (user-error "Not at a table"))
1602 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1603 (new (org-table-clean-line line
)))
1604 ;; Fix the first field if necessary
1605 (if (string-match "^[ \t]*| *[#$] *|" line
)
1606 (setq new
(replace-match (match-string 0 line
) t t new
)))
1607 (beginning-of-line (if arg
2 1))
1608 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1609 (beginning-of-line 0)
1610 (re-search-forward "| ?" (point-at-eol) t
)
1611 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1613 (when (or (not org-table-fix-formulas-confirm
)
1614 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1615 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1618 (defun org-table-insert-hline (&optional above
)
1619 "Insert a horizontal-line below the current line into the table.
1620 With prefix ABOVE, insert above the current line."
1622 (if (not (org-at-table-p))
1623 (user-error "Not at a table"))
1624 (when (eobp) (insert "\n") (backward-char 1))
1625 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1627 (let ((line (org-table-clean-line
1628 (buffer-substring (point-at-bol) (point-at-eol))))
1629 (col (current-column)))
1630 (while (string-match "|\\( +\\)|" line
)
1631 (setq line
(replace-match
1632 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1633 ?-
) "|") t t line
)))
1634 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1635 (beginning-of-line (if above
1 2))
1637 (beginning-of-line (if above
1 -
1))
1638 (org-move-to-column col
)
1639 (and org-table-overlay-coordinates
(org-table-align))))
1642 (defun org-table-hline-and-move (&optional same-column
)
1643 "Insert a hline and move to the row below that line."
1645 (let ((col (org-table-current-column)))
1646 (org-table-maybe-eval-formula)
1647 (org-table-maybe-recalculate-line)
1648 (org-table-insert-hline)
1650 (if (looking-at "\n[ \t]*|-")
1651 (progn (insert "\n|") (org-table-align))
1652 (org-table-next-field))
1653 (if same-column
(org-table-goto-column col
))))
1655 (defun org-table-clean-line (s)
1656 "Convert a table line S into a string with only \"|\" and space.
1657 In particular, this does handle wide and invisible characters."
1658 (if (string-match "^[ \t]*|-" s
)
1659 ;; It's a hline, just map the characters
1660 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1661 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1662 (setq s
(replace-match
1663 (concat "|" (make-string (org-string-width (match-string 1 s
))
1669 (defun org-table-kill-row ()
1670 "Delete the current row or horizontal line from the table."
1672 (if (not (org-at-table-p))
1673 (user-error "Not at a table"))
1674 (let ((col (current-column))
1675 (dline (org-table-current-dline)))
1676 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1677 (if (not (org-at-table-p)) (beginning-of-line 0))
1678 (org-move-to-column col
)
1679 (when (or (not org-table-fix-formulas-confirm
)
1680 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1681 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1685 (defun org-table-sort-lines (with-case &optional sorting-type
)
1686 "Sort table lines according to the column at point.
1688 The position of point indicates the column to be used for
1689 sorting, and the range of lines is the range between the nearest
1690 horizontal separator lines, or the entire table of no such lines
1691 exist. If point is before the first column, you will be prompted
1692 for the sorting column. If there is an active region, the mark
1693 specifies the first line and the sorting column, while point
1694 should be in the last line to be included into the sorting.
1696 The command then prompts for the sorting type which can be
1697 alphabetically, numerically, or by time (as given in a time stamp
1698 in the field, or as a HH:MM value). Sorting in reverse order is
1701 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1703 If SORTING-TYPE is specified when this function is called from a Lisp
1704 program, no prompting will take place. SORTING-TYPE must be a character,
1705 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1706 should be done in reverse order."
1708 (let* ((thisline (org-current-line))
1709 (thiscol (org-table-current-column))
1710 (otc org-table-overlay-coordinates
)
1711 beg end bcol ecol tend tbeg column lns pos
)
1712 (when (equal thiscol
0)
1713 (if (org-called-interactively-p 'any
)
1716 (read-string "Use column N for sorting: ")))
1718 (org-table-goto-column thiscol
))
1719 (org-table-check-inside-data-field)
1720 (if (org-region-active-p)
1722 (setq beg
(region-beginning) end
(region-end))
1724 (setq column
(org-table-current-column)
1727 (setq end
(point-at-bol 2)))
1728 (setq column
(org-table-current-column)
1730 tbeg
(org-table-begin)
1731 tend
(org-table-end))
1732 (if (re-search-backward org-table-hline-regexp tbeg t
)
1733 (setq beg
(point-at-bol 2))
1735 (setq beg
(point-at-bol 1)))
1737 (if (re-search-forward org-table-hline-regexp tend t
)
1738 (setq end
(point-at-bol 1))
1740 (setq end
(point-at-bol))))
1741 (setq beg
(move-marker (make-marker) beg
)
1742 end
(move-marker (make-marker) end
))
1745 (org-table-goto-column column
)
1746 (skip-chars-backward "^|")
1747 (setq bcol
(current-column))
1748 (org-table-goto-column (1+ column
))
1749 (skip-chars-backward "^|")
1750 (setq ecol
(1- (current-column)))
1751 (org-table-goto-column column
)
1752 (setq lns
(mapcar (lambda(x) (cons
1753 (org-sort-remove-invisible
1755 (org-split-string x
"[ \t]*|[ \t]*")))
1757 (org-split-string (buffer-substring beg end
) "\n")))
1758 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1759 (when org-table-overlay-coordinates
1760 (org-table-toggle-coordinate-overlays))
1761 (delete-region beg end
)
1762 (move-marker beg nil
)
1763 (move-marker end nil
)
1764 (insert (mapconcat 'cdr lns
"\n") "\n")
1765 (org-goto-line thisline
)
1766 (org-table-goto-column thiscol
)
1767 (when otc
(org-table-toggle-coordinate-overlays))
1768 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1771 (defun org-table-cut-region (beg end
)
1772 "Copy region in table to the clipboard and blank all relevant fields.
1773 If there is no active region, use just the field at point."
1775 (if (org-region-active-p) (region-beginning) (point))
1776 (if (org-region-active-p) (region-end) (point))))
1777 (org-table-copy-region beg end
'cut
))
1780 (defun org-table-copy-region (beg end
&optional cut
)
1781 "Copy rectangular region in table to clipboard.
1782 A special clipboard is used which can only be accessed
1783 with `org-table-paste-rectangle'."
1785 (if (org-region-active-p) (region-beginning) (point))
1786 (if (org-region-active-p) (region-end) (point))
1787 current-prefix-arg
))
1788 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1790 (rpl (if cut
" " nil
)))
1792 (org-table-check-inside-data-field)
1793 (setq l01
(org-current-line)
1794 c01
(org-table-current-column))
1796 (org-table-check-inside-data-field)
1797 (setq l02
(org-current-line)
1798 c02
(org-table-current-column))
1799 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1800 c1
(min c01 c02
) c2
(max c01 c02
))
1804 (if (> l1 l2
) (throw 'exit t
))
1806 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1807 (setq cols nil ic1 c1 ic2 c2
)
1808 (while (< ic1
(1+ ic2
))
1809 (push (org-table-get-field ic1 rpl
) cols
)
1810 (setq ic1
(1+ ic1
)))
1811 (push (nreverse cols
) region
)
1812 (setq l1
(1+ l1
)))))
1813 (setq org-table-clip
(nreverse region
))
1814 (if cut
(org-table-align))
1818 (defun org-table-paste-rectangle ()
1819 "Paste a rectangular region into a table.
1820 The upper right corner ends up in the current field. All involved fields
1821 will be overwritten. If the rectangle does not fit into the present table,
1822 the table is enlarged as needed. The process ignores horizontal separator
1825 (unless (and org-table-clip
(listp org-table-clip
))
1826 (user-error "First cut/copy a region to paste!"))
1827 (org-table-check-inside-data-field)
1828 (let* ((clip org-table-clip
)
1829 (line (org-current-line))
1830 (col (org-table-current-column))
1831 (org-enable-table-editor t
)
1832 (org-table-automatic-realign nil
)
1834 (while (setq cols
(pop clip
))
1835 (while (org-at-table-hline-p) (beginning-of-line 2))
1836 (if (not (org-at-table-p))
1837 (progn (end-of-line 0) (org-table-next-field)))
1839 (while (setq field
(pop cols
))
1840 (org-table-goto-column c nil
'force
)
1841 (org-table-get-field nil field
)
1843 (beginning-of-line 2))
1844 (org-goto-line line
)
1845 (org-table-goto-column col
)
1849 (defun org-table-convert ()
1850 "Convert from `org-mode' table to table.el and back.
1851 Obviously, this only works within limits. When an Org-mode table is
1852 converted to table.el, all horizontal separator lines get lost, because
1853 table.el uses these as cell boundaries and has no notion of horizontal lines.
1854 A table.el table can be converted to an Org-mode table only if it does not
1855 do row or column spanning. Multiline cells will become multiple cells.
1856 Beware, Org-mode does not test if the table can be successfully converted - it
1857 blindly applies a recipe that works for simple tables."
1860 (if (org-at-table.el-p
)
1861 ;; convert to Org-mode table
1862 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1863 (end (move-marker (make-marker) (org-table-end t
))))
1864 (table-unrecognize-region beg end
)
1866 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1869 (if (org-at-table-p)
1870 ;; convert to table.el table
1871 (let ((beg (move-marker (make-marker) (org-table-begin)))
1872 (end (move-marker (make-marker) (org-table-end))))
1873 ;; first, get rid of all horizontal lines
1875 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1877 ;; insert a hline before first
1879 (org-table-insert-hline 'above
)
1880 (beginning-of-line -
1)
1881 ;; insert a hline after each line
1882 (while (progn (beginning-of-line 3) (< (point) end
))
1883 (org-table-insert-hline))
1885 (setq end
(move-marker end
(org-table-end)))
1886 ;; replace "+" at beginning and ending of hlines
1887 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1888 (replace-match "\\1+-"))
1890 (while (re-search-forward "-|[ \t]*$" end t
)
1891 (replace-match "-+"))
1894 (defun org-table-transpose-table-at-point ()
1895 "Transpose Org table at point and eliminate hlines.
1903 will be transposed as
1910 Note that horizontal lines disappear."
1912 (let* ((table (delete 'hline
(org-table-to-lisp)))
1913 (dline_old (org-table-current-line))
1914 (col_old (org-table-current-column))
1915 (contents (mapcar (lambda (p)
1921 (setq tp
(cdr tp
))))
1924 (goto-char (org-table-begin))
1925 (re-search-forward "|")
1927 (delete-region (point) (org-table-end))
1930 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1932 (org-table-goto-line col_old
)
1933 (org-table-goto-column dline_old
))
1937 (defun org-table-wrap-region (arg)
1938 "Wrap several fields in a column like a paragraph.
1939 This is useful if you'd like to spread the contents of a field over several
1940 lines, in order to keep the table compact.
1942 If there is an active region, and both point and mark are in the same column,
1943 the text in the column is wrapped to minimum width for the given number of
1944 lines. Generally, this makes the table more compact. A prefix ARG may be
1945 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1946 formats the selected text to two lines. If the region was longer than two
1947 lines, the remaining lines remain empty. A negative prefix argument reduces
1948 the current number of lines by that amount. The wrapped text is pasted back
1949 into the table. If you formatted it to more lines than it was before, fields
1950 further down in the table get overwritten - so you might need to make space in
1953 If there is no region, the current field is split at the cursor position and
1954 the text fragment to the right of the cursor is prepended to the field one
1957 If there is no region, but you specify a prefix ARG, the current field gets
1958 blank, and the content is appended to the field above."
1960 (org-table-check-inside-data-field)
1961 (if (org-region-active-p)
1962 ;; There is a region: fill as a paragraph
1963 (let* ((beg (region-beginning))
1964 (cline (save-excursion (goto-char beg
) (org-current-line)))
1965 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1967 (org-table-cut-region (region-beginning) (region-end))
1968 (if (> (length (car org-table-clip
)) 1)
1969 (user-error "Region must be limited to single column"))
1970 (setq nlines
(if arg
1972 (+ (length org-table-clip
) arg
)
1974 (length org-table-clip
)))
1975 (setq org-table-clip
1976 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1978 (org-goto-line cline
)
1979 (org-table-goto-column ccol
)
1980 (org-table-paste-rectangle))
1981 ;; No region, split the current field at point
1982 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1983 (skip-chars-forward "^\r\n|"))
1985 ;; combine with field above
1986 (let ((s (org-table-blank-field))
1987 (col (org-table-current-column)))
1988 (beginning-of-line 0)
1989 (while (org-at-table-hline-p) (beginning-of-line 0))
1990 (org-table-goto-column col
)
1991 (skip-chars-forward "^|")
1992 (skip-chars-backward " ")
1993 (insert " " (org-trim s
))
1996 (if (looking-at "\\([^|]+\\)+|")
1997 (let ((s (match-string 1)))
1998 (replace-match " |")
1999 (goto-char (match-beginning 0))
2000 (org-table-next-row)
2001 (insert (org-trim s
) " ")
2003 (org-table-next-row)))))
2005 (defvar org-field-marker nil
)
2008 (defun org-table-edit-field (arg)
2009 "Edit table field in a different window.
2010 This is mainly useful for fields that contain hidden parts.
2011 When called with a \\[universal-argument] prefix, just make the full field visible so that
2012 it can be edited in place."
2016 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2018 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2019 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2020 (remove-text-properties b e
'(org-cwidth t invisible t
2021 display t intangible t
))
2022 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2023 (font-lock-fontify-block))))
2025 (let ((pos (point-marker))
2027 (if (eq org-table-use-standard-references t
)
2028 (concat (org-number-to-letters (org-table-current-column))
2029 (int-to-string (org-table-current-dline)))
2030 (concat "@" (int-to-string (org-table-current-dline))
2031 "$" (int-to-string (org-table-current-column)))))
2032 (field (org-table-get-field))
2033 (cw (current-window-configuration))
2036 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2037 (when (and (local-variable-p 'org-field-marker
)
2038 (markerp org-field-marker
))
2039 (move-marker org-field-marker nil
))
2041 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2042 (let ((org-inhibit-startup t
)) (org-mode))
2044 (setq truncate-lines nil
)
2046 (goto-char (setq p
(point-max)))
2047 (insert (org-trim field
))
2048 (remove-text-properties p
(point-max)
2049 '(invisible t org-cwidth t display t
2052 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
2053 (org-set-local 'org-window-configuration cw
)
2054 (org-set-local 'org-field-marker pos
)
2055 (message "Edit and finish with C-c C-c")))))
2057 (defun org-table-finish-edit-field ()
2058 "Finish editing a table data field.
2059 Remove all newline characters, insert the result into the table, realign
2060 the table and kill the editing buffer."
2061 (let ((pos org-field-marker
)
2062 (cw org-window-configuration
)
2063 (cb (current-buffer))
2065 (goto-char (point-min))
2066 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2067 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2068 (replace-match " "))
2069 (setq text
(org-trim (buffer-string)))
2070 (set-window-configuration cw
)
2072 (select-window (get-buffer-window (marker-buffer pos
)))
2074 (move-marker pos nil
)
2075 (org-table-check-inside-data-field)
2076 (org-table-get-field nil text
)
2078 (message "New field value inserted")))
2080 (define-minor-mode org-table-follow-field-mode
2081 "Minor mode to make the table field editor window follow the cursor.
2082 When this mode is active, the field editor window will always show the
2083 current field. The mode exits automatically when the cursor leaves the
2084 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2085 nil
" TblFollow" nil
2086 (if org-table-follow-field-mode
2087 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2089 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2090 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2091 (win (and buf
(get-buffer-window buf
))))
2092 (when win
(delete-window win
))
2094 (with-current-buffer buf
2095 (move-marker org-field-marker nil
))
2096 (kill-buffer buf
)))))
2098 (defun org-table-follow-fields-with-editor ()
2099 (if (and org-table-exit-follow-field-mode-when-leaving-table
2100 (not (org-at-table-p)))
2101 ;; We have left the table, exit the follow mode
2102 (org-table-follow-field-mode -
1)
2103 (when (org-table-check-inside-data-field 'noerror
)
2104 (let ((win (selected-window)))
2105 (org-table-edit-field nil
)
2106 (org-fit-window-to-buffer)
2107 (select-window win
)))))
2109 (defvar org-timecnt
) ; dynamically scoped parameter
2112 (defun org-table-sum (&optional beg end nlast
)
2113 "Sum numbers in region of current table column.
2114 The result will be displayed in the echo area, and will be available
2115 as kill to be inserted with \\[yank].
2117 If there is an active region, it is interpreted as a rectangle and all
2118 numbers in that rectangle will be summed. If there is no active
2119 region and point is located in a table column, sum all numbers in that
2122 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2123 numbers are assumed to be times as well (in decimal hours) and the
2124 numbers are added as such.
2126 If NLAST is a number, only the NLAST fields will actually be summed."
2129 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2131 ((and beg end
)) ; beg and end given explicitly
2132 ((org-region-active-p)
2133 (setq beg
(region-beginning) end
(region-end)))
2135 (setq col
(org-table-current-column))
2136 (goto-char (org-table-begin))
2137 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2138 (user-error "No table data"))
2139 (org-table-goto-column col
)
2141 (goto-char (org-table-end))
2142 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2143 (user-error "No table data"))
2144 (org-table-goto-column col
)
2145 (setq end
(point))))
2146 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2147 (items1 (cond ((not nlast
) items
)
2148 ((>= nlast
(length items
)) items
)
2149 (t (setq items
(reverse items
))
2150 (setcdr (nthcdr (1- nlast
) items
) nil
)
2152 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2154 (res (apply '+ numbers
))
2155 (sres (if (= org-timecnt
0)
2156 (number-to-string res
)
2157 (setq diff
(* 3600 res
)
2158 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2159 m
(floor (/ diff
60)) diff
(mod diff
60)
2161 (format "%.0f:%02.0f:%02.0f" h m s
))))
2163 (if (org-called-interactively-p 'interactive
)
2165 (substitute-command-keys
2166 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2167 (length numbers
) sres
))))
2170 (defun org-table-get-number-for-summing (s)
2172 (if (string-match "^ *|? *" s
)
2173 (setq s
(replace-match "" nil nil s
)))
2174 (if (string-match " *|? *$" s
)
2175 (setq s
(replace-match "" nil nil s
)))
2176 (setq n
(string-to-number s
))
2178 ((and (string-match "0" s
)
2179 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2180 ((string-match "\\`[ \t]+\\'" s
) nil
)
2181 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2182 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2183 (m (string-to-number (or (match-string 2 s
) "0")))
2184 (s (string-to-number (or (match-string 4 s
) "0"))))
2185 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2186 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2190 (defun org-table-current-field-formula (&optional key noerror
)
2191 "Return the formula active for the current field.
2192 Assumes that specials are in place.
2193 If KEY is given, return the key to this formula.
2194 Otherwise return the formula preceded with \"=\" or \":=\"."
2195 (let* ((name (car (rassoc (list (org-current-line)
2196 (org-table-current-column))
2197 org-table-named-field-locations
)))
2198 (col (org-table-current-column))
2199 (scol (int-to-string col
))
2200 (ref (format "@%d$%d" (org-table-current-dline) col
))
2201 (stored-list (org-table-get-stored-formulas noerror
))
2202 (ass (or (assoc name stored-list
)
2203 (assoc ref stored-list
)
2204 (assoc scol stored-list
))))
2207 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2210 (defun org-table-get-formula (&optional equation named
)
2211 "Read a formula from the minibuffer, offer stored formula as default.
2212 When NAMED is non-nil, look for a named equation."
2213 (let* ((stored-list (org-table-get-stored-formulas))
2214 (name (car (rassoc (list (org-current-line)
2215 (org-table-current-column))
2216 org-table-named-field-locations
)))
2217 (ref (format "@%d$%d" (org-table-current-dline)
2218 (org-table-current-column)))
2219 (refass (assoc ref stored-list
))
2220 (nameass (assoc name stored-list
))
2222 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2225 (int-to-string (org-table-current-column))))
2226 (dummy (and (or nameass refass
) (not named
)
2227 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2228 (message "Formula not replaced")))
2229 (name (or name ref
))
2230 (org-table-may-need-update nil
)
2231 (stored (cdr (assoc scol stored-list
)))
2233 ((and stored equation
(string-match "^ *=? *$" equation
))
2237 (t (org-table-formula-from-user
2239 (org-table-formula-to-user
2240 (format "%s formula %s%s="
2241 (if named
"Field" "Column")
2242 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2244 (if stored
(org-table-formula-to-user stored
) "")
2245 'org-table-formula-history
2248 (when (not (string-match "\\S-" eq
))
2250 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2251 (org-table-store-formulas stored-list
)
2252 (user-error "Formula removed"))
2253 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2254 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2255 (if (and name
(not named
))
2256 ;; We set the column equation, delete the named one.
2257 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2260 (setcdr (assoc scol stored-list
) eq
)
2261 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2262 (if (or mustsave
(not (equal stored eq
)))
2263 (org-table-store-formulas stored-list
))
2266 (defun org-table-store-formulas (alist)
2267 "Store the list of formulas below the current table."
2268 (setq alist
(sort alist
'org-table-formula-less-p
))
2269 (let ((case-fold-search t
))
2271 (goto-char (org-table-end))
2272 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2274 ;; don't overwrite TBLFM, we might use text properties to store stuff
2275 (goto-char (match-beginning 3))
2276 (delete-region (match-beginning 3) (match-end 0)))
2278 (insert (or (match-string 2) "#+TBLFM:")))
2280 (mapconcat (lambda (x)
2282 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2283 (car x
) "=" (cdr x
)))
2287 (defsubst org-table-formula-make-cmp-string
(a)
2288 (when (string-match "\\`$[<>]" a
)
2289 (let ((arrow (string-to-char (substring a
1))))
2290 ;; Fake a high number to make sure this is sorted at the end.
2291 (setq a
(org-table-formula-handle-first/last-rc a
))
2292 (setq a
(format "$%d" (+ 10000
2293 (if (= arrow ?
<) -
1000 0)
2294 (string-to-number (substring a
1)))))))
2296 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2300 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2302 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2304 (concat "@@" (match-string 5 a
))))))
2306 (defun org-table-formula-less-p (a b
)
2307 "Compare two formulas for sorting."
2308 (let ((as (org-table-formula-make-cmp-string (car a
)))
2309 (bs (org-table-formula-make-cmp-string (car b
))))
2310 (and as bs
(string< as bs
))))
2313 (defun org-table-get-stored-formulas (&optional noerror
)
2314 "Return an alist with the stored formulas directly after current table."
2315 (interactive) ;; FIXME interactive?
2316 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2318 (goto-char (org-table-end))
2319 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2320 (setq strings
(org-split-string (org-match-string-no-properties 2)
2322 (while (setq string
(pop strings
))
2323 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2324 (setq scol
(if (match-end 2)
2325 (match-string 2 string
)
2326 (match-string 1 string
))
2327 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2328 (concat "$" scol
) scol
)
2329 eq
(match-string 3 string
)
2330 eq-alist
(cons (cons scol eq
) eq-alist
))
2331 (if (member scol seen
)
2334 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2337 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2338 (push scol seen
))))))
2339 (nreverse eq-alist
)))
2341 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2342 "Modify the equations after the table structure has been edited.
2343 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2344 For all numbers larger than LIMIT, shift them by DELTA."
2346 (goto-char (org-table-end))
2347 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2348 (let ((msg "The formulas in #+TBLFM have been updated")
2349 (re (concat key
"\\([0-9]+\\)"))
2352 (if (or (equal key
"$") (equal key
"$LR"))
2353 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2354 (regexp-quote key
) remove
)
2355 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2358 (while (re-search-forward re2
(point-at-eol) t
)
2359 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2360 (if (equal (char-before (match-beginning 0)) ?.
)
2362 "Change makes TBLFM term %s invalid, use undo to recover"
2364 (replace-match "")))))
2365 (while (re-search-forward re
(point-at-eol) t
)
2366 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2367 (setq s
(match-string 1) n
(string-to-number s
))
2369 ((setq a
(assoc s replace
))
2370 (replace-match (concat key
(cdr a
)) t t
)
2372 ((and limit
(> n limit
))
2373 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2377 (defun org-table-get-specials ()
2378 "Get the column names and local parameters for this table."
2380 (let ((beg (org-table-begin)) (end (org-table-end))
2381 names name fields fields1 field cnt
2382 c v l line col types dlines hlines last-dline
)
2383 (setq org-table-column-names nil
2384 org-table-local-parameters nil
2385 org-table-named-field-locations nil
2386 org-table-current-begin-line nil
2387 org-table-current-begin-pos nil
2388 org-table-current-line-types nil
2389 org-table-current-ncol
0)
2391 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2392 (setq names
(org-split-string (match-string 1) " *| *")
2394 (while (setq name
(pop names
))
2396 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2397 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2398 (setq org-table-column-names
(nreverse org-table-column-names
))
2399 (setq org-table-column-name-regexp
2400 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2402 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2403 (setq fields
(org-split-string (match-string 1) " *| *"))
2404 (while (setq field
(pop fields
))
2405 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2406 (push (cons (match-string 1 field
) (match-string 2 field
))
2407 org-table-local-parameters
))))
2409 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2410 (setq c
(match-string 1)
2411 fields
(org-split-string (match-string 2) " *| *"))
2413 (beginning-of-line (if (equal c
"_") 2 0))
2414 (setq line
(org-current-line) col
1)
2415 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2416 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2417 (while (and fields1
(setq field
(pop fields
)))
2418 (setq v
(pop fields1
) col
(1+ col
))
2419 (when (and (stringp field
) (stringp v
)
2420 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2421 (push (cons field v
) org-table-local-parameters
)
2422 (push (list field line col
) org-table-named-field-locations
))))
2423 ;; Analyse the line types
2425 (setq org-table-current-begin-line
(org-current-line)
2426 org-table-current-begin-pos
(point)
2427 l org-table-current-begin-line
)
2428 (while (looking-at "[ \t]*|\\(-\\)?")
2429 (push (if (match-end 1) 'hline
'dline
) types
)
2430 (if (match-end 1) (push l hlines
) (push l dlines
))
2431 (beginning-of-line 2)
2433 (push 'hline types
) ;; add an imaginary extra hline to the end
2434 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2435 last-dline
(car dlines
)
2436 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2437 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2438 (org-goto-line last-dline
)
2439 (let* ((l last-dline
)
2440 (fields (org-split-string
2441 (buffer-substring (point-at-bol) (point-at-eol))
2443 (nfields (length fields
))
2445 (setq org-table-current-ncol nfields
)
2446 (loop for i from
1 to nfields do
2447 (push (list (format "LR%d" i
) l i
) al
)
2448 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2449 (setq org-table-named-field-locations
2450 (append org-table-named-field-locations al
))
2451 (setq org-table-local-parameters
2452 (append org-table-local-parameters al2
))))))
2455 (defun org-table-maybe-eval-formula ()
2456 "Check if the current field starts with \"=\" or \":=\".
2457 If yes, store the formula and apply it."
2458 ;; We already know we are in a table. Get field will only return a formula
2459 ;; when appropriate. It might return a separator line, but no problem.
2460 (when org-table-formula-evaluate-inline
2461 (let* ((field (org-trim (or (org-table-get-field) "")))
2463 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2464 (setq named
(equal (string-to-char field
) ?
:)
2465 eq
(match-string 1 field
))
2466 (if (or (fboundp 'calc-eval
)
2467 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2468 (org-table-eval-formula (if named
'(4) nil
)
2469 (org-table-formula-from-user eq
))
2470 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2472 (defvar org-recalc-commands nil
2473 "List of commands triggering the recalculation of a line.
2474 Will be filled automatically during use.")
2476 (defvar org-recalc-marks
2477 '((" " .
"Unmarked: no special line, no automatic recalculation")
2478 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2479 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2480 ("!" .
"Column name definition line. Reference in formula as $name.")
2481 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2482 ("_" .
"Names for values in row below this one.")
2483 ("^" .
"Names for values in row above this one.")))
2486 (defun org-table-rotate-recalc-marks (&optional newchar
)
2487 "Rotate the recalculation mark in the first column.
2488 If in any row, the first field is not consistent with a mark,
2489 insert a new column for the markers.
2490 When there is an active region, change all the lines in the region,
2491 after prompting for the marking character.
2492 After each change, a message will be displayed indicating the meaning
2495 (unless (org-at-table-p) (user-error "Not at a table"))
2496 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2497 (beg (org-table-begin))
2498 (end (org-table-end))
2499 (l (org-current-line))
2500 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2501 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2505 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2506 (col (org-table-current-column))
2507 (forcenew (car (assoc newchar org-recalc-marks
)))
2510 (message "Change region to what mark? Type # * ! $ or SPC: ")
2511 (setq newchar
(char-to-string (read-char-exclusive))
2512 forcenew
(car (assoc newchar org-recalc-marks
))))
2513 (if (and newchar
(not forcenew
))
2514 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2516 (if l1
(org-goto-line l1
))
2518 (beginning-of-line 1)
2519 (unless (looking-at org-table-dataline-regexp
)
2520 (user-error "Not at a table data line")))
2522 (org-table-goto-column 1)
2523 (org-table-insert-column)
2524 (org-table-goto-column (1+ col
)))
2525 (setq epos
(point-at-eol))
2527 (beginning-of-line 1)
2528 (org-table-get-field
2529 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2531 (setq new
(or forcenew
2532 (cadr (member (match-string 1) marks
))))
2538 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2539 (and (looking-at org-table-dataline-regexp
)
2540 (org-table-get-field 1 (concat " " new
" "))))
2541 (org-goto-line l1
)))
2542 (if (not (= epos
(point-at-eol))) (org-table-align))
2544 (and (org-called-interactively-p 'interactive
)
2545 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2548 (defun org-table-maybe-recalculate-line ()
2549 "Recompute the current line if marked for it, and if we haven't just done it."
2551 (and org-table-allow-automatic-line-recalculation
2552 (not (and (memq last-command org-recalc-commands
)
2553 (equal org-last-recalc-line
(org-current-line))))
2554 (save-excursion (beginning-of-line 1)
2555 (looking-at org-table-auto-recalculate-regexp
))
2556 (org-table-recalculate) t
))
2558 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2559 (defsubst org-set-calc-mode
(var &optional value
)
2561 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2562 ("R" calc-angle-mode rad
)
2563 ("F" calc-prefer-frac t
)
2564 ("S" calc-symbolic-mode t
)))
2565 value
(nth 2 var
) var
(nth 1 var
)))
2566 (if (memq var org-tbl-calc-modes
)
2567 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2568 (cons var
(cons value org-tbl-calc-modes
)))
2572 (defun org-table-eval-formula (&optional arg equation
2573 suppress-align suppress-const
2574 suppress-store suppress-analysis
)
2575 "Replace the table field value at the cursor by the result of a calculation.
2577 This function makes use of Dave Gillespie's Calc package, in my view the
2578 most exciting program ever written for GNU Emacs. So you need to have Calc
2579 installed in order to use this function.
2581 In a table, this command replaces the value in the current field with the
2582 result of a formula. It also installs the formula as the \"current\" column
2583 formula, by storing it in a special line below the table. When called
2584 with a `C-u' prefix, the current field must be a named field, and the
2585 formula is installed as valid in only this specific field.
2587 When called with two `C-u' prefixes, insert the active equation
2588 for the field back into the current field, so that it can be
2589 edited there. This is useful in order to use \\[org-table-show-reference]
2590 to check the referenced fields.
2592 When called, the command first prompts for a formula, which is read in
2593 the minibuffer. Previously entered formulas are available through the
2594 history list, and the last used formula is offered as a default.
2595 These stored formulas are adapted correctly when moving, inserting, or
2596 deleting columns with the corresponding commands.
2598 The formula can be any algebraic expression understood by the Calc package.
2599 For details, see the Org-mode manual.
2601 This function can also be called from Lisp programs and offers
2602 additional arguments: EQUATION can be the formula to apply. If this
2603 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2604 used to speed-up recursive calls by by-passing unnecessary aligns.
2605 SUPPRESS-CONST suppresses the interpretation of constants in the
2606 formula, assuming that this has been done already outside the function.
2607 SUPPRESS-STORE means the formula should not be stored, either because
2608 it is already stored, or because it is a modified equation that should
2609 not overwrite the stored one."
2611 (org-table-check-inside-data-field)
2612 (or suppress-analysis
(org-table-get-specials))
2613 (if (equal arg
'(16))
2614 (let ((eq (org-table-current-field-formula)))
2615 (or eq
(user-error "No equation active for current field"))
2616 (org-table-get-field nil eq
)
2618 (setq org-table-may-need-update t
))
2620 (ndown (if (integerp arg
) arg
1))
2621 (org-table-automatic-realign nil
)
2622 (case-fold-search nil
)
2624 (formula (if (and equation suppress-store
)
2626 (org-table-get-formula equation
(equal arg
'(4)))))
2627 (n0 (org-table-current-column))
2628 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2629 (numbers nil
) ; was a variable, now fixed default
2631 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2632 duration duration-output-format
)
2633 ;; Parse the format string. Since we have a lot of modes, this is
2634 ;; a lot of work. However, I think calc still uses most of the time.
2635 (if (string-match ";" formula
)
2636 (let ((tmp (org-split-string formula
";")))
2637 (setq formula
(car tmp
)
2638 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2640 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2641 (setq c
(string-to-char (match-string 1 fmt
))
2642 n
(string-to-number (match-string 2 fmt
)))
2644 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2645 (setq org-tbl-calc-modes
2648 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2649 (?s . sci
) (?e . eng
))))
2651 (setq fmt
(replace-match "" t t fmt
)))
2652 (if (string-match "T" fmt
)
2653 (setq duration t numbers t
2654 duration-output-format nil
2655 fmt
(replace-match "" t t fmt
)))
2656 (if (string-match "t" fmt
)
2658 duration-output-format org-table-duration-custom-format
2660 fmt
(replace-match "" t t fmt
)))
2661 (if (string-match "N" fmt
)
2663 fmt
(replace-match "" t t fmt
)))
2664 (if (string-match "L" fmt
)
2666 fmt
(replace-match "" t t fmt
)))
2667 (if (string-match "E" fmt
)
2669 fmt
(replace-match "" t t fmt
)))
2670 (while (string-match "[DRFS]" fmt
)
2671 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2672 (setq fmt
(replace-match "" t t fmt
)))
2673 (unless (string-match "\\S-" fmt
)
2675 (if (and (not suppress-const
) org-table-formula-use-constants
)
2676 (setq formula
(org-table-formula-substitute-names formula
)))
2677 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2679 (setq fields
(org-split-string
2680 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2682 ;; replace fields with duration values if relevant
2685 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2688 (setq fields
(mapcar
2690 (if (string-match "\\S-" x
)
2691 (number-to-string (string-to-number x
))
2694 (setq ndown
(1- ndown
))
2695 (setq form
(copy-sequence formula
)
2696 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2697 (if (and lispp literal
) (setq lispp
'literal
))
2699 ;; Insert row and column number of formula result field
2700 (while (string-match "[@$]#" form
)
2705 (if (equal (substring form
(match-beginning 0)
2706 (1+ (match-beginning 0)))
2708 (org-table-current-dline)
2709 (org-table-current-column))))
2712 ;; Check for old vertical references
2713 (setq form
(org-table-rewrite-old-row-references form
))
2714 ;; Insert remote references
2715 (setq form
(org-table-remote-reference-indirection form
))
2716 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2720 (org-table-make-reference
2721 (let ((rmtrng (org-table-get-remote-range
2722 (match-string 1 form
) (match-string 2 form
))))
2725 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2726 (org-table-time-string-to-seconds rmtrng
))
2728 keep-empty numbers lispp
))
2730 ;; Insert complex ranges
2731 (while (and (string-match org-table-range-regexp form
)
2732 (> (length (match-string 0 form
)) 1))
2733 (setq formrg
(save-match-data
2734 (org-table-get-range (match-string 0 form
) nil n0
)))
2737 (org-table-make-reference
2738 ;; possibly handle durations
2741 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2742 (org-table-time-string-to-seconds formrg
))
2744 keep-empty numbers lispp
)))
2745 (if (not (save-match-data
2746 (string-match (regexp-quote form
) formrpl
)))
2747 (setq form
(replace-match formrpl t t form
))
2748 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2749 ;; Insert simple ranges
2750 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2754 (org-table-make-reference
2756 fields
(string-to-number (match-string 1 form
))
2757 (string-to-number (match-string 2 form
)))
2758 keep-empty numbers lispp
))
2761 ;; Insert the references to fields in same row
2762 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2763 (setq n
(+ (string-to-number (match-string 1 form
))
2764 (if (match-end 2) n0
0))
2765 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2766 formrpl
(save-match-data
2767 (org-table-make-reference
2768 x keep-empty numbers lispp
)))
2771 (string-match (regexp-quote formula
) formrpl
)))
2772 (user-error "Invalid field specifier \"%s\""
2773 (match-string 0 form
)))
2774 (setq form
(replace-match formrpl t t form
)))
2777 (setq ev
(condition-case nil
2778 (eval (eval (read form
)))
2780 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2781 ev
(if duration
(org-table-time-seconds-to-string
2782 (string-to-number ev
)
2783 duration-output-format
) ev
))
2784 (or (fboundp 'calc-eval
)
2785 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2786 ;; Use <...> time-stamps so that Calc can handle them
2787 (while (string-match (concat "\\[" org-ts-regexp1
"\\]") form
)
2788 (setq form
(replace-match "<\\1>" nil nil form
)))
2789 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2790 (when (string-match org-ts-regexp2 form
)
2791 (let* ((ts (match-string 0 form
))
2792 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2793 (system-time-locale "C")
2794 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2795 (cdr org-time-stamp-formats
))
2796 (car org-time-stamp-formats
))))
2797 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2799 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2801 (calc-eval (cons form org-tbl-calc-modes
)
2802 (when (and (not keep-empty
) numbers
) 'num
)))
2803 ev
(if duration
(org-table-time-seconds-to-string
2804 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2805 (string-to-number (org-table-time-string-to-seconds ev
))
2806 (string-to-number ev
))
2807 duration-output-format
)
2810 (when org-table-formula-debug
2811 (with-output-to-temp-buffer "*Substitution History*"
2812 (princ (format "Substitution history of formula
2816 $1-> %s\n" orig formula form0 form
))
2818 (princ (format " %s^\nError: %s"
2819 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2820 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2822 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2823 (setq bw
(get-buffer-window "*Substitution History*"))
2824 (org-fit-window-to-buffer bw
)
2825 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2826 (unless (let (inhibit-redisplay)
2827 (y-or-n-p "Debugging Formula. Continue to next? "))
2829 (user-error "Abort"))
2832 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2833 (org-table-justify-field-maybe
2834 (format org-table-formula-field-format
2835 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2836 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2837 (call-interactively 'org-return
)
2839 (and down
(org-table-maybe-recalculate-line))
2840 (or suppress-align
(and org-table-may-need-update
2841 (org-table-align))))))
2843 (defun org-table-put-field-property (prop value
)
2845 (put-text-property (progn (skip-chars-backward "^|") (point))
2846 (progn (skip-chars-forward "^|") (point))
2849 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2850 "Get a calc vector from a column, according to descriptor DESC.
2851 Optional arguments TBEG and COL can give the beginning of the table and
2852 the current column, to avoid unnecessary parsing.
2854 HIGHLIGHT means just highlight the range.
2856 When CORNERS-ONLY is set, only return the corners of the range as
2857 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2858 in the buffer and column1 and column2 are table column numbers."
2859 (if (not (equal (string-to-char desc
) ?
@))
2860 (setq desc
(concat "@" desc
)))
2862 (or tbeg
(setq tbeg
(org-table-begin)))
2863 (or col
(setq col
(org-table-current-column)))
2864 (let ((thisline (org-current-line))
2865 beg end c1 c2 r1 r2 rangep tmp
)
2866 (unless (string-match org-table-range-regexp desc
)
2867 (user-error "Invalid table range specifier `%s'" desc
))
2868 (setq rangep
(match-end 3)
2869 r1
(and (match-end 1) (match-string 1 desc
))
2870 r2
(and (match-end 4) (match-string 4 desc
))
2871 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2872 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2874 (and c1
(setq c1
(+ (string-to-number c1
)
2875 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2876 (and c2
(setq c2
(+ (string-to-number c2
)
2877 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2878 (if (equal r1
"") (setq r1 nil
))
2879 (if (equal r2
"") (setq r2 nil
))
2880 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2881 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2882 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2883 (if (not r1
) (setq r1 thisline
))
2884 (if (not r2
) (setq r2 thisline
))
2885 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2886 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2887 (if (and (not corners-only
)
2888 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2892 (while (not (looking-at org-table-dataline-regexp
))
2893 (beginning-of-line 2))
2894 (prog1 (org-trim (org-table-get-field c1
))
2895 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2896 ;; A range, return a vector
2897 ;; First sort the numbers to get a regular rectangle
2898 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2899 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2901 ;; Only return the corners of the range
2903 ;; Copy the range values into a list
2905 (while (not (looking-at org-table-dataline-regexp
))
2906 (beginning-of-line 2))
2907 (org-table-goto-column c1
)
2910 (while (not (looking-at org-table-dataline-regexp
))
2911 (beginning-of-line 0))
2912 (org-table-goto-column c2
)
2915 (org-table-highlight-rectangle
2916 beg
(progn (skip-chars-forward "^|\n") (point))))
2917 ;; return string representation of calc vector
2919 (apply 'append
(org-table-copy-region beg end
))))))))
2921 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2922 "Analyze descriptor DESC and retrieve the corresponding line number.
2923 The cursor is currently in line CLINE, the table begins in line BLINE,
2924 and TABLE is a vector with line types."
2925 (if (string-match "^[0-9]+$" desc
)
2926 (aref org-table-dlines
(string-to-number desc
))
2927 (setq cline
(or cline
(org-current-line))
2928 bline
(or bline org-table-current-begin-line
)
2929 table
(or table org-table-current-line-types
))
2931 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2933 (and (not (match-end 3)) (not (match-end 6)))
2934 (and (match-end 3) (match-end 6) (not (match-end 5))))
2935 (user-error "Invalid row descriptor `%s'" desc
))
2936 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2937 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2938 (odir (and (match-end 5) (match-string 5 desc
)))
2939 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2941 (rel (and (match-end 6)
2942 (or (and (match-end 1) (not (match-end 3)))
2944 (if (and hn
(not hdir
))
2947 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2948 (if (and (not hn
) on
(not odir
))
2949 (user-error "Should never happen");;(aref org-table-dlines on)
2950 (if (and hn
(> hn
0))
2951 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2952 nil hn cline desc
)))
2954 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2955 rel on cline desc
)))
2958 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2959 "FIXME: Needs more documentation."
2960 (let ((l (length table
)))
2962 (while (and (setq i
(+ i
(if backwards -
1 1)))
2964 (not (eq (aref table i
) type
))
2965 (if (and relative
(eq (aref table i
) 'hline
))
2967 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2968 ((eq org-table-relative-ref-may-cross-hline
'error
)
2969 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2970 (t (setq i
(- i
(if backwards -
1 1))
2975 (if (or (< i
0) (>= i l
))
2976 (user-error "Row descriptor %s used in line %d leads outside table"
2980 (defun org-table-rewrite-old-row-references (s)
2981 (if (string-match "&[-+0-9I]" s
)
2982 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2985 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2986 "Convert list ELEMENTS to something appropriate to insert into formula.
2987 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2988 NUMBERS indicates that everything should be converted to numbers.
2989 LISPP non-nil means to return something appropriate for a Lisp
2990 list, 'literal is for the format specifier L."
2991 ;; Calc nan (not a number) is used for the conversion of the empty
2992 ;; field to a reference for several reasons: (i) It is accepted in a
2993 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2994 ;; (ii) In a single field (not in range) it can be distinguished
2995 ;; from "(nan)" which is the reference made from a single field
2996 ;; containing "nan".
2997 (if (stringp elements
)
3000 (if (eq lispp
'literal
)
3002 (if (and (eq elements
"") (not keep-empty
))
3005 (if numbers
(string-to-number elements
) elements
))))
3006 (if (string-match "\\S-" elements
)
3008 (when numbers
(setq elements
(number-to-string
3009 (string-to-number elements
))))
3010 (concat "(" elements
")"))
3011 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3016 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3018 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3022 (if (eq lispp
'literal
)
3024 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3026 (concat "[" (mapconcat
3028 (if (string-match "\\S-" x
)
3030 (number-to-string (string-to-number x
))
3032 (if (or (not keep-empty
) numbers
) "0" "nan")))
3037 (defun org-table-set-constants ()
3038 "Set `org-table-formula-constants-local' in the current buffer."
3039 (let (cst consts const-str
)
3041 (goto-char (point-min))
3042 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
3043 (setq const-str
(substring-no-properties (match-string 1)))
3044 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
3047 (while (setq e
(pop consts
))
3048 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
3049 (if (assoc-string (match-string 1 e
) cst
)
3050 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
3051 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
3052 (setq org-table-formula-constants-local cst
)))))))
3055 (defun org-table-recalculate (&optional all noalign
)
3056 "Recalculate the current table line by applying all stored formulas.
3057 With prefix arg ALL, do this for all lines in the table.
3058 With the prefix argument ALL is `(16)' \
3059 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3060 it is the symbol `iterate', recompute the table until it no longer changes.
3061 If NOALIGN is not nil, do not re-align the table after the computations
3062 are done. This is typically used internally to save time, if it is
3063 known that the table will be realigned a little later anyway."
3065 (or (memq this-command org-recalc-commands
)
3066 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
3067 (unless (org-at-table-p) (user-error "Not at a table"))
3068 (if (or (eq all
'iterate
) (equal all
'(16)))
3070 (org-table-get-specials)
3071 (let* ((eqlist (sort (org-table-get-stored-formulas)
3072 (lambda (a b
) (string< (car a
) (car b
)))))
3073 (eqlist1 (copy-sequence eqlist
))
3074 (inhibit-redisplay (not debug-on-error
))
3075 (line-re org-table-dataline-regexp
)
3076 (thisline (org-current-line))
3077 (thiscol (org-table-current-column))
3079 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3080 ;; Insert constants in all formulas
3083 (if (string-match "^@-?I+" (car x
))
3084 (user-error "Can't assign to hline relative reference"))
3085 (when (string-match "\\`$[<>]" (car x
))
3087 (setq x
(cons (substring
3088 (org-table-formula-handle-first/last-rc
3091 (if (assoc (car x
) eqlist1
)
3092 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3095 (org-table-formula-handle-first/last-rc
(car x
))
3096 (org-table-formula-substitute-names
3097 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3099 ;; Split the equation list
3100 (while (setq eq
(pop eqlist
))
3101 (if (<= (string-to-char (car eq
)) ?
9)
3104 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3105 ;; Expand ranges in lhs of formulas
3106 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3108 ;; Get the correct line range to process
3111 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3112 (goto-char (setq beg
(org-table-begin)))
3113 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3114 ;; This is a table with marked lines, compute selected lines
3115 (setq line-re org-table-recalculate-regexp
)
3116 ;; Move forward to the first non-header line
3117 (if (and (re-search-forward org-table-dataline-regexp end t
)
3118 (re-search-forward org-table-hline-regexp end t
)
3119 (re-search-forward org-table-dataline-regexp end t
))
3120 (setq beg
(match-beginning 0))
3121 nil
))) ;; just leave beg where it is
3122 (setq beg
(point-at-bol)
3123 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3125 (and all
(message "Re-applying formulas to full table..."))
3127 ;; First find the named fields, and mark them untouchable.
3128 ;; Also check if several field/range formulas try to set the same field.
3129 (remove-text-properties beg end
'(org-untouchable t
))
3130 (while (setq eq
(pop eqlname
))
3132 a
(assoc name org-table-named-field-locations
))
3134 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3136 (when (member name1 seen-fields
)
3137 (user-error "Several field/range formulas try to set %s" name1
))
3138 (push name1 seen-fields
)
3141 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3144 (aref org-table-dlines
3145 (string-to-number (match-string 1 name
)))
3146 (error (user-error "Invalid row number in %s"
3148 (string-to-number (match-string 2 name
)))))
3149 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3150 (message "Re-applying formula to field: %s" name
)
3151 (org-goto-line (nth 1 a
))
3152 (org-table-goto-column (nth 2 a
))
3153 (push (append a
(list (cdr eq
))) eqlname1
)
3154 (org-table-put-field-property :org-untouchable t
)))
3155 (setq eqlname1
(nreverse eqlname1
))
3157 ;; Now evaluate the column formulas, but skip fields covered by
3160 (while (re-search-forward line-re end t
)
3161 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3162 ;; Unprotected line, recalculate
3163 (and all
(message "Re-applying formulas to full table...(line %d)"
3164 (setq cnt
(1+ cnt
))))
3165 (setq org-last-recalc-line
(org-current-line))
3167 (while (setq entry
(pop eql
))
3168 (org-goto-line org-last-recalc-line
)
3169 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3170 (unless (get-text-property (point) :org-untouchable
)
3171 (org-table-eval-formula nil
(cdr entry
)
3172 'noalign
'nocst
'nostore
'noanalysis
)))))
3174 ;; Now evaluate the field formulas
3175 (while (setq eq
(pop eqlname1
))
3176 (message "Re-applying formula to field: %s" (car eq
))
3177 (org-goto-line (nth 1 eq
))
3178 (org-table-goto-column (nth 2 eq
))
3179 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3180 'nostore
'noanalysis
))
3182 (org-goto-line thisline
)
3183 (org-table-goto-column thiscol
)
3184 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3185 (or noalign
(and org-table-may-need-update
(org-table-align))
3186 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3188 ;; back to initial position
3189 (message "Re-applying formulas...done")
3190 (org-goto-line thisline
)
3191 (org-table-goto-column thiscol
)
3192 (or noalign
(and org-table-may-need-update
(org-table-align))
3193 (and all
(message "Re-applying formulas...done"))))))
3196 (defun org-table-iterate (&optional arg
)
3197 "Recalculate the table until it does not change anymore.
3198 The maximum number of iterations is 10, but you can choose a different value
3199 with the prefix ARG."
3201 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3203 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3208 (org-table-recalculate 'all
)
3209 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3210 (if (not (string= lasttbl thistbl
))
3211 (setq lasttbl thistbl
)
3213 (message "Convergence after %d iterations" i
)
3214 (message "Table was already stable"))
3216 (user-error "No convergence after %d iterations" i
))))
3219 (defun org-table-recalculate-buffer-tables ()
3220 "Recalculate all tables in the current buffer."
3225 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3228 (defun org-table-iterate-buffer-tables ()
3229 "Iterate all tables in the buffer, to converge inter-table dependencies."
3233 (checksum (md5 (buffer-string)))
3241 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3242 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3244 (message "Convergence after %d iterations" (- imax i
))
3246 (setq checksum c1
)))
3247 (user-error "No convergence after %d iterations" imax
))))))
3249 (defun org-table-calc-current-TBLFM (&optional arg
)
3250 "Apply the #+TBLFM in the line at point to the table."
3252 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3253 (let ((formula (buffer-substring
3258 ;; Insert a temporary formula at right after the table
3259 (goto-char (org-table-TBLFM-begin))
3260 (setq s
(set-marker (make-marker) (point)))
3261 (insert (concat formula
"\n"))
3262 (setq e
(set-marker (make-marker) (point)))
3263 ;; Recalculate the table
3264 (beginning-of-line 0) ; move to the inserted line
3265 (skip-chars-backward " \r\n\t")
3266 (if (org-at-table-p)
3268 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3269 ;; delete the formula inserted temporarily
3270 (delete-region s e
))))))
3272 (defun org-table-TBLFM-begin ()
3273 "Find the beginning of the TBLFM lines and return its position.
3274 Return nil when the beginning of TBLFM line was not found."
3276 (when (progn (forward-line 1)
3278 org-table-TBLFM-begin-regexp
3282 (defun org-table-expand-lhs-ranges (equations)
3283 "Expand list of formulas.
3284 If some of the RHS in the formulas are ranges or a row reference, expand
3285 them to individual field equations for each field."
3286 (let (e res lhs rhs range r1 r2 c1 c2
)
3287 (while (setq e
(pop equations
))
3288 (setq lhs
(car e
) rhs
(cdr e
))
3290 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3291 ;; This just refers to one fixed field
3293 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3294 ;; This just refers to one fixed named field
3296 ((string-match "^@[0-9]+$" lhs
)
3297 (loop for ic from
1 to org-table-current-ncol do
3298 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3299 (put-text-property 0 (length (caar res
))
3300 :orig-eqn e
(caar res
))))
3302 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3304 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3305 r2
(nth 2 range
) c2
(nth 3 range
))
3306 (setq r1
(org-table-line-to-dline r1
))
3307 (setq r2
(org-table-line-to-dline r2
'above
))
3308 (loop for ir from r1 to r2 do
3309 (loop for ic from c1 to c2 do
3310 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3311 (put-text-property 0 (length (caar res
))
3312 :orig-eqn e
(caar res
)))))))
3315 (defun org-table-formula-handle-first/last-rc
(s)
3316 "Replace @<, @>, $<, $> with first/last row/column of the table.
3317 So @< and $< will always be replaced with @1 and $1, respectively.
3318 The advantage of these special markers are that structure editing of
3319 the table will not change them, while @1 and $1 will be modified
3320 when a line/row is swapped out of that privileged position. So for
3321 formulas that use a range of rows or columns, it may often be better
3322 to anchor the formula with \"I\" row markers, or to offset from the
3323 borders of the table using the @< @> $< $> makers."
3324 (let (n nmax len char
(start 0))
3325 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3328 (setq start
(match-end 3))
3329 (setq nmax
(if (equal (match-string 1 s
) "@")
3330 (1- (length org-table-dlines
))
3331 org-table-current-ncol
)
3332 len
(- (match-end 2) (match-beginning 2))
3333 char
(string-to-char (match-string 2 s
))
3337 (if (or (< n
1) (> n nmax
))
3338 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3339 (match-string 0 s
) s
))
3340 (setq start
(match-beginning 0))
3341 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3344 (defun org-table-formula-substitute-names (f)
3345 "Replace $const with values in string F."
3346 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3347 ;; First, check for column names
3348 (while (setq start
(string-match org-table-column-name-regexp f start
))
3349 (setq start
(1+ start
))
3350 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3351 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3352 ;; Parameters and constants
3354 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3356 (setq start
(match-end 2))
3357 (setq start
(1+ start
))
3358 (if (setq a
(save-match-data
3359 (org-table-get-constant (match-string 1 f
))))
3360 (setq f
(replace-match
3361 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3362 (if org-table-formula-debug
3363 (put-text-property 0 (length f
) :orig-formula f1 f
))
3366 (defun org-table-get-constant (const)
3367 "Find the value for a parameter or constant in a formula.
3368 Parameters get priority."
3369 (or (cdr (assoc const org-table-local-parameters
))
3370 (cdr (assoc const org-table-formula-constants-local
))
3371 (cdr (assoc const org-table-formula-constants
))
3372 (and (fboundp 'constants-get
) (constants-get const
))
3373 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3374 (org-entry-get nil
(substring const
5) 'inherit
))
3377 (defvar org-table-fedit-map
3378 (let ((map (make-sparse-keymap)))
3379 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3380 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3381 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3382 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3383 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3384 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3385 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3386 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3387 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3388 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3389 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3390 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3391 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3392 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3393 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3394 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3395 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3396 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3397 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3398 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3401 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3403 ["Finish and Install" org-table-fedit-finish t
]
3404 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3405 ["Abort" org-table-fedit-abort t
]
3407 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3408 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3410 "Shift Reference at Point"
3411 ["Up" org-table-fedit-ref-up t
]
3412 ["Down" org-table-fedit-ref-down t
]
3413 ["Left" org-table-fedit-ref-left t
]
3414 ["Right" org-table-fedit-ref-right t
]
3416 "Change Test Row for Column Formulas"
3417 ["Up" org-table-fedit-line-up t
]
3418 ["Down" org-table-fedit-line-down t
]
3420 ["Scroll Table Window" org-table-fedit-scroll t
]
3421 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3422 ["Show Table Grid" org-table-fedit-toggle-coordinates
3423 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3424 org-table-overlay-coordinates
)]
3426 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3427 :style toggle
:selected org-table-buffer-is-an
]))
3432 (defun org-table-edit-formulas ()
3433 "Edit the formulas of the current table in a separate buffer."
3435 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3436 (beginning-of-line 0))
3437 (unless (org-at-table-p) (user-error "Not at a table"))
3438 (org-table-get-specials)
3439 (let ((key (org-table-current-field-formula 'key
'noerror
))
3440 (eql (sort (org-table-get-stored-formulas 'noerror
)
3441 'org-table-formula-less-p
))
3442 (pos (point-marker))
3444 (wc (current-window-configuration))
3445 (sel-win (selected-window))
3446 (titles '((column .
"# Column Formulas\n")
3447 (field .
"# Field and Range Formulas\n")
3448 (named .
"# Named Field Formulas\n")))
3450 (org-switch-to-buffer-other-window "*Edit Formulas*")
3452 ;; Keep global-font-lock-mode from turning on font-lock-mode
3453 (let ((font-lock-global-modes '(not fundamental-mode
)))
3455 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3456 (org-set-local 'org-pos pos
)
3457 (org-set-local 'org-window-configuration wc
)
3458 (org-set-local 'org-selected-window sel-win
)
3459 (use-local-map org-table-fedit-map
)
3460 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3461 (easy-menu-add org-table-fedit-menu
)
3462 (setq startline
(org-current-line))
3463 (while (setq entry
(pop eql
))
3465 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3466 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3467 ((string-match "^[0-9]" (car entry
)) 'column
)
3469 (when (setq title
(assq type titles
))
3470 (or (bobp) (insert "\n"))
3471 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3472 (setq titles
(remove title titles
)))
3473 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3474 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3475 (car entry
) " = " (cdr entry
) "\n"))
3476 (remove-text-properties 0 (length s
) '(face nil
) s
)
3478 (if (eq org-table-use-standard-references t
)
3479 (org-table-fedit-toggle-ref-type))
3480 (org-goto-line startline
)
3481 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3483 (defun org-table-fedit-post-command ()
3484 (when (not (memq this-command
'(lisp-complete-symbol)))
3485 (let ((win (selected-window)))
3488 (org-table-show-reference)
3490 (select-window win
)))))
3492 (defun org-table-formula-to-user (s)
3493 "Convert a formula from internal to user representation."
3494 (if (eq org-table-use-standard-references t
)
3495 (org-table-convert-refs-to-an s
)
3498 (defun org-table-formula-from-user (s)
3499 "Convert a formula from user to internal representation."
3500 (if org-table-use-standard-references
3501 (org-table-convert-refs-to-rc s
)
3504 (defun org-table-convert-refs-to-rc (s)
3505 "Convert spreadsheet references from A7 to @7$28.
3506 Works for single references, but also for entire formulas and even the
3509 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3512 ;; format match, just advance
3513 (setq start
(match-end 0)))
3514 ((and (> (match-beginning 0) 0)
3515 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3516 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3517 ;; 3.e5 or something like this.
3518 (setq start
(match-end 0)))
3519 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3520 ;; (member (match-string 1 s)
3521 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3523 ;; function name, just advance
3524 (setq start
(match-end 0)))
3526 (setq start
(match-beginning 0)
3528 (if (equal (match-string 2 s
) "&")
3529 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3531 (string-to-number (match-string 2 s
))
3532 (org-letters-to-number (match-string 1 s
))))
3536 (defun org-table-convert-refs-to-an (s)
3537 "Convert spreadsheet references from to @7$28 to AB7.
3538 Works for single references, but also for entire formulas and even the
3540 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3541 (setq s
(replace-match
3543 (org-number-to-letters
3544 (string-to-number (match-string 2 s
)))
3545 (string-to-number (match-string 1 s
)))
3547 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3548 (setq s
(replace-match (concat "\\1"
3549 (org-number-to-letters
3550 (string-to-number (match-string 2 s
))) "&")
3554 (defun org-letters-to-number (s)
3555 "Convert a base 26 number represented by letters into an integer.
3556 For example: AB -> 28."
3559 (while (> (length s
) 0)
3560 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3564 (defun org-number-to-letters (n)
3565 "Convert an integer into a base 26 number represented by letters.
3566 For example: 28 -> AB."
3569 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3573 (defun org-table-time-string-to-seconds (s)
3574 "Convert a time string into numerical duration in seconds.
3575 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3576 If S is a string representing a number, keep this number."
3579 (let (hour minus min sec res
)
3581 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3582 (setq minus
(< 0 (length (match-string 1 s
)))
3583 hour
(string-to-number (match-string 2 s
))
3584 min
(string-to-number (match-string 3 s
))
3585 sec
(string-to-number (match-string 4 s
)))
3587 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3588 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3589 ((and (not (string-match org-ts-regexp-both s
))
3590 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3591 (setq minus
(< 0 (length (match-string 1 s
)))
3592 hour
(string-to-number (match-string 2 s
))
3593 min
(string-to-number (match-string 3 s
)))
3595 (setq res
(- (+ (* hour
3600) (* min
60))))
3596 (setq res
(+ (* hour
3600) (* min
60)))))
3597 (t (setq res
(string-to-number s
))))
3598 (number-to-string res
))))
3600 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3601 "Convert a number of seconds to a time string.
3602 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3603 minutes or seconds."
3604 (let* ((secs0 (abs secs
))
3606 (cond ((eq output-format
'days
)
3607 (format "%.3f" (/ (float secs0
) 86400)))
3608 ((eq output-format
'hours
)
3609 (format "%.2f" (/ (float secs0
) 3600)))
3610 ((eq output-format
'minutes
)
3611 (format "%.1f" (/ (float secs0
) 60)))
3612 ((eq output-format
'seconds
)
3613 (format "%d" secs0
))
3614 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3615 (if (< secs
0) (concat "-" res
) res
)))
3617 (defun org-table-fedit-convert-buffer (function)
3618 "Convert all references in this buffer, using FUNCTION."
3619 (let ((line (org-current-line)))
3620 (goto-char (point-min))
3622 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3623 (delete-region (point) (point-at-eol))
3624 (or (eobp) (forward-char 1)))
3625 (org-goto-line line
)))
3627 (defun org-table-fedit-toggle-ref-type ()
3628 "Convert all references in the buffer from B3 to @3$2 and back."
3630 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3631 (org-table-fedit-convert-buffer
3632 (if org-table-buffer-is-an
3633 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3634 (message "Reference type switched to %s"
3635 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3637 (defun org-table-fedit-ref-up ()
3638 "Shift the reference at point one row/hline up."
3640 (org-table-fedit-shift-reference 'up
))
3641 (defun org-table-fedit-ref-down ()
3642 "Shift the reference at point one row/hline down."
3644 (org-table-fedit-shift-reference 'down
))
3645 (defun org-table-fedit-ref-left ()
3646 "Shift the reference at point one field to the left."
3648 (org-table-fedit-shift-reference 'left
))
3649 (defun org-table-fedit-ref-right ()
3650 "Shift the reference at point one field to the right."
3652 (org-table-fedit-shift-reference 'right
))
3654 (defun org-table-fedit-shift-reference (dir)
3656 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3657 (if (memq dir
'(left right
))
3658 (org-rematch-and-replace 1 (eq dir
'left
))
3659 (user-error "Cannot shift reference in this direction")))
3660 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3661 ;; A B3-like reference
3662 (if (memq dir
'(up down
))
3663 (org-rematch-and-replace 2 (eq dir
'up
))
3664 (org-rematch-and-replace 1 (eq dir
'left
))))
3666 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3667 ;; An internal reference
3668 (if (memq dir
'(up down
))
3669 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3670 (org-rematch-and-replace 5 (eq dir
'left
))))))
3672 (defun org-rematch-and-replace (n &optional decr hline
)
3673 "Re-match the group N, and replace it with the shifted reference."
3674 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3675 (goto-char (match-beginning n
))
3676 (and (looking-at (regexp-quote (match-string n
)))
3677 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3680 (defun org-table-shift-refpart (ref &optional decr hline
)
3681 "Shift a reference part REF.
3682 If DECR is set, decrease the references row/column, else increase.
3683 If HLINE is set, this may be a hline reference, it certainly is not
3684 a translation reference."
3686 (let* ((sign (string-match "^[-+]" ref
)) n
)
3688 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3690 ((and hline
(string-match "^I+" ref
))
3691 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3692 (setq n
(+ n
(if decr -
1 1)))
3693 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3695 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3697 (concat sign
(make-string n ?I
)))
3699 ((string-match "^[0-9]+" ref
)
3700 (setq n
(string-to-number (concat sign ref
)))
3701 (setq n
(+ n
(if decr -
1 1)))
3703 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3704 (number-to-string (max 1 n
))))
3706 ((string-match "^[a-zA-Z]+" ref
)
3707 (org-number-to-letters
3708 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3710 (t (user-error "Cannot shift reference"))))))
3712 (defun org-table-fedit-toggle-coordinates ()
3713 "Toggle the display of coordinates in the referenced table."
3715 (let ((pos (marker-position org-pos
)))
3716 (with-current-buffer (marker-buffer org-pos
)
3719 (org-table-toggle-coordinate-overlays)))))
3721 (defun org-table-fedit-finish (&optional arg
)
3722 "Parse the buffer for formula definitions and install them.
3723 With prefix ARG, apply the new formulas to the table."
3725 (org-table-remove-rectangle-highlight)
3726 (if org-table-use-standard-references
3728 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3729 (setq org-table-buffer-is-an nil
)))
3730 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3731 (goto-char (point-min))
3732 (while (re-search-forward
3733 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3735 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3736 form
(match-string 3))
3737 (setq form
(org-trim form
))
3738 (when (not (equal form
""))
3739 (while (string-match "[ \t]*\n[ \t]*" form
)
3740 (setq form
(replace-match " " t t form
)))
3741 (when (assoc var eql
)
3742 (user-error "Double formulas for %s" var
))
3743 (push (cons var form
) eql
)))
3745 (set-window-configuration org-window-configuration
)
3746 (select-window sel-win
)
3748 (unless (org-at-table-p)
3749 (user-error "Lost table position - cannot install formulas"))
3750 (org-table-store-formulas eql
)
3751 (move-marker pos nil
)
3752 (kill-buffer "*Edit Formulas*")
3754 (org-table-recalculate 'all
)
3755 (message "New formulas installed - press C-u C-c C-c to apply."))))
3757 (defun org-table-fedit-abort ()
3758 "Abort editing formulas, without installing the changes."
3760 (org-table-remove-rectangle-highlight)
3761 (let ((pos org-pos
) (sel-win org-selected-window
))
3762 (set-window-configuration org-window-configuration
)
3763 (select-window sel-win
)
3765 (move-marker pos nil
)
3766 (message "Formula editing aborted without installing changes")))
3768 (defun org-table-fedit-lisp-indent ()
3769 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3771 (let ((pos (point)) beg end ind
)
3772 (beginning-of-line 1)
3774 ((looking-at "[ \t]")
3776 (call-interactively 'lisp-indent-line
))
3777 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3778 ((not (fboundp 'pp-buffer
))
3779 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3780 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3781 (goto-char (- (match-end 0) 2))
3783 (setq ind
(make-string (current-column) ?\
))
3784 (condition-case nil
(forward-sexp 1)
3786 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3789 (narrow-to-region beg end
)
3790 (if (eq last-command this-command
)
3792 (goto-char (point-min))
3793 (setq this-command nil
)
3794 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3795 (replace-match " ")))
3797 (untabify (point-min) (point-max))
3798 (goto-char (1+ (point-min)))
3799 (while (re-search-forward "^." nil t
)
3800 (beginning-of-line 1)
3802 (goto-char (point-max))
3803 (org-delete-backward-char 1)))
3807 (defvar org-show-positions nil
)
3809 (defun org-table-show-reference (&optional local
)
3810 "Show the location/value of the $ expression at point."
3812 (org-table-remove-rectangle-highlight)
3814 (let ((pos (if local
(point) org-pos
))
3816 (org-inhibit-highlight-removal t
)
3817 (win (selected-window))
3818 (org-show-positions nil
)
3819 var name e what match dest
)
3820 (if local
(org-table-get-specials))
3822 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3823 (setq match
(concat (substring (match-string 0) 0 -
1)
3825 (substring (match-string 0) 0 -
1)
3828 ((or (org-at-regexp-p org-table-range-regexp2
)
3829 (org-at-regexp-p org-table-translate-regexp
)
3830 (org-at-regexp-p org-table-range-regexp
))
3833 (org-table-convert-refs-to-rc (match-string 0))))
3835 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3836 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3838 (t (user-error "No reference at point")))
3839 match
(and what
(or match
(match-string 0))))
3840 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3841 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3842 'secondary-selection
))
3843 (org-add-hook 'before-change-functions
3844 'org-table-remove-rectangle-highlight
)
3845 (if (eq what
'name
) (setq var
(substring match
1)))
3846 (when (eq what
'range
)
3847 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3848 (setq match
(org-table-formula-substitute-names match
)))
3852 (re-search-backward "^\\S-" nil t
)
3853 (beginning-of-line 1)
3854 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3857 (org-table-convert-refs-to-rc (match-string 1))))
3858 (org-table-add-rectangle-overlay
3859 (match-beginning 1) (match-end 1) face2
))))
3860 (if (and (markerp pos
) (marker-buffer pos
))
3861 (if (get-buffer-window (marker-buffer pos
))
3862 (select-window (get-buffer-window (marker-buffer pos
)))
3863 (org-switch-to-buffer-other-window (get-buffer-window
3864 (marker-buffer pos
)))))
3866 (org-table-force-dataline)
3868 (setq name
(substring dest
1))
3870 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3871 (setq e
(assoc name org-table-named-field-locations
))
3872 (org-goto-line (nth 1 e
))
3873 (org-table-goto-column (nth 2 e
)))
3874 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3875 (let ((l (string-to-number (match-string 1 dest
)))
3876 (c (string-to-number (match-string 2 dest
))))
3877 (org-goto-line (aref org-table-dlines l
))
3878 (org-table-goto-column c
)))
3879 (t (org-table-goto-column (string-to-number name
))))
3880 (move-marker pos
(point))
3881 (org-table-highlight-rectangle nil nil face2
))
3883 ((equal dest match
))
3888 (org-table-get-range match nil nil
'highlight
))
3890 ((setq e
(assoc var org-table-named-field-locations
))
3891 (org-goto-line (nth 1 e
))
3892 (org-table-goto-column (nth 2 e
))
3893 (org-table-highlight-rectangle (point) (point))
3894 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3895 ((setq e
(assoc var org-table-column-names
))
3896 (org-table-goto-column (string-to-number (cdr e
)))
3897 (org-table-highlight-rectangle (point) (point))
3898 (goto-char (org-table-begin))
3899 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3902 (goto-char (match-beginning 1))
3903 (org-table-highlight-rectangle)
3904 (message "Named column (column %s)" (cdr e
)))
3905 (user-error "Column name not found")))
3908 (org-table-goto-column (string-to-number (substring match
1)))
3909 (org-table-highlight-rectangle (point) (point))
3910 (message "Column %s" (substring match
1)))
3911 ((setq e
(assoc var org-table-local-parameters
))
3912 (goto-char (org-table-begin))
3913 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3915 (goto-char (match-beginning 1))
3916 (org-table-highlight-rectangle)
3917 (message "Local parameter."))
3918 (user-error "Parameter not found")))
3921 ((not var
) (user-error "No reference at point"))
3922 ((setq e
(assoc var org-table-formula-constants-local
))
3923 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3925 ((setq e
(assoc var org-table-formula-constants
))
3926 (message "Constant: $%s=%s in `org-table-formula-constants'."
3928 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3929 (message "Constant: $%s=%s, from `constants.el'%s."
3930 var e
(format " (%s units)" constants-unit-system
)))
3931 (t (user-error "Undefined name $%s" var
)))))
3933 (when (and org-show-positions
3934 (not (memq this-command
'(org-table-fedit-scroll
3935 org-table-fedit-scroll-down
))))
3936 (push pos org-show-positions
)
3937 (push org-table-current-begin-pos org-show-positions
)
3938 (let ((min (apply 'min org-show-positions
))
3939 (max (apply 'max org-show-positions
)))
3940 (set-window-start (selected-window) min
)
3942 (or (pos-visible-in-window-p max
)
3943 (set-window-start (selected-window) max
))))
3944 (select-window win
))))
3946 (defun org-table-force-dataline ()
3947 "Make sure the cursor is in a dataline in a table."
3948 (unless (save-excursion
3949 (beginning-of-line 1)
3950 (looking-at org-table-dataline-regexp
))
3951 (let* ((re org-table-dataline-regexp
)
3952 (p1 (save-excursion (re-search-forward re nil
'move
)))
3953 (p2 (save-excursion (re-search-backward re nil
'move
))))
3955 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3957 ((or p1 p2
) (goto-char (or p1 p2
)))
3958 (t (user-error "No table dataline around here"))))))
3960 (defun org-table-fedit-line-up ()
3961 "Move cursor one line up in the window showing the table."
3963 (org-table-fedit-move 'previous-line
))
3965 (defun org-table-fedit-line-down ()
3966 "Move cursor one line down in the window showing the table."
3968 (org-table-fedit-move 'next-line
))
3970 (defun org-table-fedit-move (command)
3971 "Move the cursor in the window showing the table.
3972 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3973 (let ((org-table-allow-automatic-line-recalculation nil
)
3974 (pos org-pos
) (win (selected-window)) p
)
3975 (select-window (get-buffer-window (marker-buffer org-pos
)))
3977 (call-interactively command
)
3978 (while (and (org-at-table-p)
3979 (org-at-table-hline-p))
3980 (call-interactively command
))
3981 (or (org-at-table-p) (goto-char p
))
3982 (move-marker pos
(point))
3983 (select-window win
)))
3985 (defun org-table-fedit-scroll (N)
3987 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3988 (scroll-other-window N
)))
3990 (defun org-table-fedit-scroll-down (N)
3992 (org-table-fedit-scroll (- N
)))
3994 (defvar org-table-rectangle-overlays nil
)
3996 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3997 "Add a new overlay."
3998 (let ((ov (make-overlay beg end
)))
3999 (overlay-put ov
'face
(or face
'secondary-selection
))
4000 (push ov org-table-rectangle-overlays
)))
4002 (defun org-table-highlight-rectangle (&optional beg end face
)
4003 "Highlight rectangular region in a table."
4004 (setq beg
(or beg
(point)) end
(or end
(point)))
4005 (let ((b (min beg end
))
4008 (and (boundp 'org-show-positions
)
4009 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4010 (goto-char (min beg end
))
4011 (setq l1
(org-current-line)
4012 c1
(org-table-current-column))
4013 (goto-char (max beg end
))
4014 (setq l2
(org-current-line)
4015 c2
(org-table-current-column))
4016 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
4018 (beginning-of-line 1)
4019 (loop for line from l1 to l2 do
4020 (when (looking-at org-table-dataline-regexp
)
4021 (org-table-goto-column c1
)
4022 (skip-chars-backward "^|\n") (setq beg
(point))
4023 (org-table-goto-column c2
)
4024 (skip-chars-forward "^|\n") (setq end
(point))
4025 (org-table-add-rectangle-overlay beg end face
))
4026 (beginning-of-line 2))
4028 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
4030 (defun org-table-remove-rectangle-highlight (&rest ignore
)
4031 "Remove the rectangle overlays."
4032 (unless org-inhibit-highlight-removal
4033 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4034 (mapc 'delete-overlay org-table-rectangle-overlays
)
4035 (setq org-table-rectangle-overlays nil
)))
4037 (defvar org-table-coordinate-overlays nil
4038 "Collects the coordinate grid overlays, so that they can be removed.")
4039 (make-variable-buffer-local 'org-table-coordinate-overlays
)
4041 (defun org-table-overlay-coordinates ()
4042 "Add overlays to the table at point, to show row/column coordinates."
4044 (mapc 'delete-overlay org-table-coordinate-overlays
)
4045 (setq org-table-coordinate-overlays nil
)
4047 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4048 (goto-char (org-table-begin))
4049 (while (org-at-table-p)
4050 (setq eol
(point-at-eol))
4051 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4052 (push ov org-table-coordinate-overlays
)
4053 (setq hline
(looking-at org-table-hline-regexp
))
4054 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4055 (format "%4d" (setq id
(1+ id
)))))
4056 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4059 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4060 (setq beg
(1+ (match-beginning 0))
4062 s1
(concat "$" (int-to-string ic
))
4063 s2
(org-number-to-letters ic
)
4064 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4065 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4066 (push ov org-table-coordinate-overlays
)
4067 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4068 (beginning-of-line 2)))))
4071 (defun org-table-toggle-coordinate-overlays ()
4072 "Toggle the display of Row/Column numbers in tables."
4074 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4075 (message "Tables Row/Column numbers display turned %s"
4076 (if org-table-overlay-coordinates
"on" "off"))
4077 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4079 (unless org-table-overlay-coordinates
4080 (mapc 'delete-overlay org-table-coordinate-overlays
)
4081 (setq org-table-coordinate-overlays nil
)))
4084 (defun org-table-toggle-formula-debugger ()
4085 "Toggle the formula debugger in tables."
4087 (setq org-table-formula-debug
(not org-table-formula-debug
))
4088 (message "Formula debugging has been turned %s"
4089 (if org-table-formula-debug
"on" "off")))
4091 ;;; The orgtbl minor mode
4093 ;; Define a minor mode which can be used in other modes in order to
4094 ;; integrate the org-mode table editor.
4096 ;; This is really a hack, because the org-mode table editor uses several
4097 ;; keys which normally belong to the major mode, for example the TAB and
4098 ;; RET keys. Here is how it works: The minor mode defines all the keys
4099 ;; necessary to operate the table editor, but wraps the commands into a
4100 ;; function which tests if the cursor is currently inside a table. If that
4101 ;; is the case, the table editor command is executed. However, when any of
4102 ;; those keys is used outside a table, the function uses `key-binding' to
4103 ;; look up if the key has an associated command in another currently active
4104 ;; keymap (minor modes, major mode, global), and executes that command.
4105 ;; There might be problems if any of the keys used by the table editor is
4106 ;; otherwise used as a prefix key.
4108 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4109 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4110 ;; addresses this by checking explicitly for both bindings.
4112 ;; The optimized version (see variable `orgtbl-optimized') takes over
4113 ;; all keys which are bound to `self-insert-command' in the *global map*.
4114 ;; Some modes bind other commands to simple characters, for example
4115 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4116 ;; active, this binding is ignored inside tables and replaced with a
4117 ;; modified self-insert.
4120 (defvar orgtbl-mode-map
(make-keymap)
4121 "Keymap for `orgtbl-mode'.")
4123 (defvar org-old-auto-fill-inhibit-regexp nil
4124 "Local variable used by `orgtbl-mode'.")
4126 (defconst orgtbl-line-start-regexp
4127 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4128 "Matches a line belonging to an orgtbl.")
4130 (defconst orgtbl-extra-font-lock-keywords
4131 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4132 0 (quote 'org-table
) 'prepend
))
4133 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4135 ;; Install it as a minor mode.
4136 (put 'orgtbl-mode
:included t
)
4137 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4140 (define-minor-mode orgtbl-mode
4141 "The `org-mode' table editor as a minor mode for use in other modes."
4142 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4143 (org-load-modules-maybe)
4145 ((derived-mode-p 'org-mode
)
4146 ;; Exit without error, in case some hook functions calls this
4147 ;; by accident in org-mode.
4148 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4150 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4151 ;; Make sure we are first in minor-mode-map-alist
4152 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4153 ;; FIXME: maybe it should use emulation-mode-map-alists?
4154 (and c
(setq minor-mode-map-alist
4155 (cons c
(delq c minor-mode-map-alist
)))))
4156 (org-set-local (quote org-table-may-need-update
) t
)
4157 (org-add-hook 'before-change-functions
'org-before-change-function
4159 (org-set-local 'org-old-auto-fill-inhibit-regexp
4160 auto-fill-inhibit-regexp
)
4161 (org-set-local 'auto-fill-inhibit-regexp
4162 (if auto-fill-inhibit-regexp
4163 (concat orgtbl-line-start-regexp
"\\|"
4164 auto-fill-inhibit-regexp
)
4165 orgtbl-line-start-regexp
))
4166 (add-to-invisibility-spec '(org-cwidth))
4167 (when (fboundp 'font-lock-add-keywords
)
4168 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4169 (org-restart-font-lock))
4170 (easy-menu-add orgtbl-mode-menu
))
4172 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4173 (org-table-cleanup-narrow-column-properties)
4174 (org-remove-from-invisibility-spec '(org-cwidth))
4175 (remove-hook 'before-change-functions
'org-before-change-function t
)
4176 (when (fboundp 'font-lock-remove-keywords
)
4177 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4178 (org-restart-font-lock))
4179 (easy-menu-remove orgtbl-mode-menu
)
4180 (force-mode-line-update 'all
))))
4182 (defun org-table-cleanup-narrow-column-properties ()
4183 "Remove all properties related to narrow-column invisibility."
4184 (let ((s (point-min)))
4185 (while (setq s
(text-property-any s
(point-max)
4186 'display org-narrow-column-arrow
))
4187 (remove-text-properties s
(1+ s
) '(display t
)))
4188 (setq s
(point-min))
4189 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4190 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4191 (setq s
(point-min))
4192 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4193 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4195 (defun orgtbl-make-binding (fun n
&rest keys
)
4196 "Create a function for binding in the table minor mode.
4197 FUN is the command to call inside a table. N is used to create a unique
4198 command name. KEYS are keys that should be checked in for a command
4199 to execute outside of tables."
4202 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4204 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4205 "Outside of tables, run the binding of `"
4206 (mapconcat #'key-description keys
"' or `")
4211 (list 'call-interactively
(list 'quote fun
))
4212 (list 'let
'(orgtbl-mode)
4213 (list 'call-interactively
4216 (list 'key-binding k
))
4218 '('orgtbl-error
))))))))
4220 (defun orgtbl-error ()
4221 "Error when there is no default binding for a table key."
4223 (user-error "This key has no function outside tables"))
4225 (defun orgtbl-setup ()
4226 "Setup orgtbl keymaps."
4229 '(([(meta shift left
)] org-table-delete-column
)
4230 ([(meta left
)] org-table-move-column-left
)
4231 ([(meta right
)] org-table-move-column-right
)
4232 ([(meta shift right
)] org-table-insert-column
)
4233 ([(meta shift up
)] org-table-kill-row
)
4234 ([(meta shift down
)] org-table-insert-row
)
4235 ([(meta up
)] org-table-move-row-up
)
4236 ([(meta down
)] org-table-move-row-down
)
4237 ("\C-c\C-w" org-table-cut-region
)
4238 ("\C-c\M-w" org-table-copy-region
)
4239 ("\C-c\C-y" org-table-paste-rectangle
)
4240 ("\C-c\C-w" org-table-wrap-region
)
4241 ("\C-c-" org-table-insert-hline
)
4242 ("\C-c}" org-table-toggle-coordinate-overlays
)
4243 ("\C-c{" org-table-toggle-formula-debugger
)
4244 ("\C-m" org-table-next-row
)
4245 ([(shift return
)] org-table-copy-down
)
4246 ("\C-c?" org-table-field-info
)
4247 ("\C-c " org-table-blank-field
)
4248 ("\C-c+" org-table-sum
)
4249 ("\C-c=" org-table-eval-formula
)
4250 ("\C-c'" org-table-edit-formulas
)
4251 ("\C-c`" org-table-edit-field
)
4252 ("\C-c*" org-table-recalculate
)
4253 ("\C-c^" org-table-sort-lines
)
4254 ("\M-a" org-table-beginning-of-field
)
4255 ("\M-e" org-table-end-of-field
)
4256 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4258 (while (setq elt
(pop bindings
))
4259 (setq nfunc
(1+ nfunc
))
4260 (setq key
(org-key (car elt
))
4262 cmd
(orgtbl-make-binding fun nfunc key
))
4263 (org-defkey orgtbl-mode-map key cmd
))
4265 ;; Special treatment needed for TAB and RET
4266 (org-defkey orgtbl-mode-map
[(return)]
4267 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4268 (org-defkey orgtbl-mode-map
"\C-m"
4269 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4271 (org-defkey orgtbl-mode-map
[(tab)]
4272 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4273 (org-defkey orgtbl-mode-map
"\C-i"
4274 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4276 (org-defkey orgtbl-mode-map
[(shift tab
)]
4277 (orgtbl-make-binding 'org-table-previous-field
104
4278 [(shift tab
)] [(tab)] "\C-i"))
4281 (unless (featurep 'xemacs
)
4282 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4283 (orgtbl-make-binding 'org-table-previous-field
107
4284 [S-iso-lefttab
] [backtab] [(shift tab)]
4287 (org-defkey orgtbl-mode-map [backtab]
4288 (orgtbl-make-binding 'org-table-previous-field
108
4289 [backtab] [S-iso-lefttab] [(shift tab)]
4292 (org-defkey orgtbl-mode-map "\M-\C-m"
4293 (orgtbl-make-binding 'org-table-wrap-region 105
4294 "\M-\C-m" [(meta return)]))
4295 (org-defkey orgtbl-mode-map [(meta return)]
4296 (orgtbl-make-binding 'org-table-wrap-region 106
4297 [(meta return)] "\M-\C-m"))
4299 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4300 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4302 (when orgtbl-optimized
4303 ;; If the user wants maximum table support, we need to hijack
4304 ;; some standard editing functions
4305 (org-remap orgtbl-mode-map
4306 'self-insert-command 'orgtbl-self-insert-command
4307 'delete-char 'org-delete-char
4308 'delete-backward-char 'org-delete-backward-char)
4309 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4310 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4312 ["Create or convert" org-table-create-or-convert-from-region
4313 :active (not (org-at-table-p)) :keys "C-c |" ]
4315 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4316 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4317 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4318 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4320 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4321 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4322 ["Copy Field from Above"
4323 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4326 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4327 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4328 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4329 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
4330 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c p"])
4332 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4333 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4334 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4335 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4336 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4338 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4340 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4341 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4342 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4343 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4346 ["Insert table template" orgtbl-insert-radio-table
4347 (assq major-mode orgtbl-radio-table-templates)]
4348 ["Comment/uncomment table" orgtbl-toggle-comment t])
4350 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4351 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4352 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4353 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4354 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4355 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4356 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4357 ["Sum Column/Rectangle" org-table-sum
4358 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4359 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4361 org-table-toggle-formula-debugger :active (org-at-table-p)
4363 :style toggle :selected org-table-formula-debug]
4364 ["Show Col/Row Numbers"
4365 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4367 :style toggle :selected org-table-overlay-coordinates]
4371 (defun orgtbl-ctrl-c-ctrl-c (arg)
4372 "If the cursor is inside a table, realign the table.
4373 If it is a table to be sent away to a receiver, do it.
4374 With prefix arg, also recompute table."
4376 (let ((case-fold-search t) (pos (point)) action)
4378 (beginning-of-line 1)
4380 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4381 ((looking-at "[ \t]*|") pos)
4382 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4386 (org-table-maybe-eval-formula)
4388 (call-interactively 'org-table-recalculate)
4389 (org-table-maybe-recalculate-line))
4390 (call-interactively 'org-table-align)
4391 (when (orgtbl-send-table 'maybe)
4392 (run-hooks 'orgtbl-after-send-table-hook)))
4393 ((eq action 'recalc)
4394 (org-table-set-constants)
4396 (beginning-of-line 1)
4397 (skip-chars-backward " \r\n\t")
4398 (if (org-at-table-p)
4399 (org-call-with-arg 'org-table-recalculate t))))
4400 (t (let (orgtbl-mode)
4401 (call-interactively (key-binding "\C-c\C-c")))))))
4403 (defun orgtbl-create-or-convert-from-region (arg)
4404 "Create table or convert region to table, if no conflicting binding.
4405 This installs the table binding `C-c |', but only if there is no
4406 conflicting binding to this key outside orgtbl-mode."
4408 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4410 (call-interactively cmd)
4411 (call-interactively 'org-table-create-or-convert-from-region))))
4413 (defun orgtbl-tab (arg)
4414 "Justification and field motion for `orgtbl-mode'."
4416 (if arg (org-table-edit-field t)
4417 (org-table-justify-field-maybe)
4418 (org-table-next-field)))
4420 (defun orgtbl-ret ()
4421 "Justification and field motion for `orgtbl-mode'."
4425 (org-table-justify-field-maybe)
4426 (org-table-next-row)))
4428 (defun orgtbl-self-insert-command (N)
4429 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4430 If the cursor is in a table looking at whitespace, the whitespace is
4431 overwritten, and the table is not marked as requiring realignment."
4433 (if (and (org-at-table-p)
4435 (and org-table-auto-blank-field
4436 (member last-command
4437 '(orgtbl-hijacker-command-100
4438 orgtbl-hijacker-command-101
4439 orgtbl-hijacker-command-102
4440 orgtbl-hijacker-command-103
4441 orgtbl-hijacker-command-104
4442 orgtbl-hijacker-command-105
4444 (org-table-blank-field))
4447 (looking-at "[^|\n]* +|"))
4448 (let (org-table-may-need-update)
4449 (goto-char (1- (match-end 0)))
4450 (org-delete-backward-char 1)
4451 (goto-char (match-beginning 0))
4452 (self-insert-command N))
4453 (setq org-table-may-need-update t)
4456 (cmd (or (key-binding
4457 (or (and (listp function-key-map)
4458 (setq a (assoc last-input-event function-key-map))
4460 (vector last-input-event)))
4461 'self-insert-command)))
4462 (call-interactively cmd)
4463 (if (and org-self-insert-cluster-for-undo
4464 (eq cmd 'self-insert-command))
4465 (if (not (eq last-command 'orgtbl-self-insert-command))
4466 (setq org-self-insert-command-undo-counter 1)
4467 (if (>= org-self-insert-command-undo-counter 20)
4468 (setq org-self-insert-command-undo-counter 1)
4469 (and (> org-self-insert-command-undo-counter 0)
4471 (not (cadr buffer-undo-list)) ; remove nil entry
4472 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4473 (setq org-self-insert-command-undo-counter
4474 (1+ org-self-insert-command-undo-counter))))))))
4476 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4477 "Regular expression matching exponentials as produced by calc.")
4479 (defun orgtbl-gather-send-defs ()
4480 "Gather a plist of :name, :transform, :params for each destination before
4483 (goto-char (org-table-begin))
4485 (beginning-of-line 0)
4486 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4487 (let ((name (org-no-properties (match-string 1)))
4488 (transform (intern (match-string 2)))
4489 (params (if (match-end 3)
4490 (read (concat "(" (match-string 3) ")")))))
4491 (push (list :name name :transform transform :params params)
4493 (beginning-of-line 0)))
4496 (defun orgtbl-send-replace-tbl (name txt)
4497 "Find and replace table NAME with TXT."
4499 (goto-char (point-min))
4500 (unless (re-search-forward
4501 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4502 (user-error "Don't know where to insert translated table"))
4503 (goto-char (match-beginning 0))
4504 (beginning-of-line 2)
4506 (let ((beg (point)))
4507 (unless (re-search-forward
4508 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4509 (user-error "Cannot find end of insertion region"))
4510 (beginning-of-line 1)
4511 (delete-region beg (point))))
4515 (defun org-table-to-lisp (&optional txt)
4516 "Convert the table at point to a Lisp structure.
4517 The structure will be a list. Each item is either the symbol `hline'
4518 for a horizontal separator line, or a list of field values as strings.
4519 The table is taken from the parameter TXT, or from the buffer at point."
4521 (unless (org-at-table-p)
4522 (user-error "No table at point")))
4524 (buffer-substring-no-properties (org-table-begin)
4526 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4530 (if (string-match org-table-hline-regexp x)
4532 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4535 (defun orgtbl-send-table (&optional maybe)
4536 "Send a transformed version of this table to the receiver position.
4537 With argument MAYBE, fail quietly if no transformation is defined for
4541 (unless (org-at-table-p) (user-error "Not at a table"))
4542 ;; when non-interactive, we assume align has just happened.
4543 (when (org-called-interactively-p 'any) (org-table-align))
4544 (let ((dests (orgtbl-gather-send-defs))
4545 (txt (buffer-substring-no-properties (org-table-begin)
4548 (unless dests (if maybe (throw 'exit nil)
4549 (user-error "Don't know how to transform this table")))
4550 (dolist (dest dests)
4551 (let* ((name (plist-get dest :name))
4552 (transform (plist-get dest :transform))
4553 (params (plist-get dest :params))
4554 (skip (plist-get params :skip))
4555 (skipcols (plist-get params :skipcols))
4556 (no-escape (plist-get params :no-escape))
4558 (lines (org-table-clean-before-export
4560 (org-split-string txt "[ \t]*\n[ \t]*"))))
4561 (i0 (if org-table-clean-did-remove-column 2 1))
4562 (lines (if no-escape lines
4563 (mapcar (lambda(l) (replace-regexp-in-string
4564 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4567 (if (string-match org-table-hline-regexp x)
4569 (org-remove-by-index
4570 (org-split-string (org-trim x) "\\s-*|\\s-*")
4573 (fun (if (= i0 2) 'cdr 'identity))
4574 (org-table-last-alignment
4575 (org-remove-by-index (funcall fun org-table-last-alignment)
4577 (org-table-last-column-widths
4578 (org-remove-by-index (funcall fun org-table-last-column-widths)
4580 (txt (if (fboundp transform)
4581 (funcall transform table params)
4582 (user-error "No such transformation function %s" transform))))
4583 (orgtbl-send-replace-tbl name txt))
4584 (setq ntbl (1+ ntbl)))
4585 (message "Table converted and installed at %d receiver location%s"
4586 ntbl (if (> ntbl 1) "s" ""))
4591 (defun org-remove-by-index (list indices &optional i0)
4592 "Remove the elements in LIST with indices in INDICES.
4593 First element has index 0, or I0 if given."
4596 (if (integerp indices) (setq indices (list indices)))
4597 (setq i0 (1- (or i0 0)))
4598 (delq :rm (mapcar (lambda (x)
4600 (if (memq i0 indices) :rm x))
4603 (defun orgtbl-toggle-comment ()
4604 "Comment or uncomment the orgtbl at point."
4606 (let* ((case-fold-search t)
4607 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4608 (re2 (concat "^" orgtbl-line-start-regexp))
4609 (commented (save-excursion (beginning-of-line 1)
4610 (cond ((looking-at re1) t)
4611 ((looking-at re2) nil)
4612 (t (user-error "Not at an org table")))))
4613 (re (if commented re1 re2))
4616 (beginning-of-line 1)
4617 (while (looking-at re) (beginning-of-line 0))
4618 (beginning-of-line 2)
4620 (while (looking-at re) (beginning-of-line 2))
4622 (comment-region beg end (if commented '(4) nil))))
4624 (defun orgtbl-insert-radio-table ()
4625 "Insert a radio table template appropriate for this major mode."
4627 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4630 (unless e (user-error "No radio table setup defined for %s" major-mode))
4631 (setq name (read-string "Table name: "))
4632 (while (string-match "%n" txt)
4633 (setq txt (replace-match name t t txt)))
4634 (or (bolp) (insert "\n"))
4639 ;; Dynamically bound input and output for table formatting.
4640 (defvar *orgtbl-table* nil
4641 "Carries the current table through formatting routines.")
4642 (defvar *orgtbl-rtn* nil
4643 "Formatting routines push the output lines here.")
4644 ;; Formatting parameters for the current table section.
4645 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4646 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4647 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4648 (defvar *orgtbl-fmt* nil "Format for each entry.")
4649 (defvar *orgtbl-efmt* nil "Format for numbers.")
4650 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4651 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4652 (defvar *orgtbl-lstart* nil "Text starting a row.")
4653 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4654 (defvar *orgtbl-lend* nil "Text ending a row.")
4655 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4657 (defsubst orgtbl-get-fmt (fmt i)
4658 "Retrieve the format from FMT corresponding to the Ith column."
4659 (if (and (not (functionp fmt)) (consp fmt))
4663 (defsubst orgtbl-apply-fmt (fmt &rest args)
4664 "Apply format FMT to arguments ARGS.
4665 When FMT is nil, return the first argument from ARGS."
4666 (cond ((functionp fmt) (apply fmt args))
4667 (fmt (apply 'format fmt args))
4671 (defsubst orgtbl-eval-str (str)
4672 "If STR is a function, evaluate it with no arguments."
4677 (defun orgtbl-format-line (line)
4678 "Format LINE as a table row."
4679 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4685 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4686 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4687 (orgtbl-apply-fmt efmt (match-string 1 f)
4690 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4691 *orgtbl-default-fmt*)
4694 (push (if *orgtbl-lfmt*
4695 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4696 (concat (orgtbl-eval-str *orgtbl-lstart*)
4697 (mapconcat 'identity line *orgtbl-sep*)
4698 (orgtbl-eval-str *orgtbl-lend*)))
4701 (defun orgtbl-format-section (section-stopper)
4702 "Format lines until the first occurrence of SECTION-STOPPER."
4705 (while (not (eq (car *orgtbl-table*) section-stopper))
4706 (if prevline (orgtbl-format-line prevline))
4707 (setq prevline (pop *orgtbl-table*)))
4708 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4709 (*orgtbl-lend* *orgtbl-llend*)
4710 (*orgtbl-lfmt* *orgtbl-llfmt*))
4711 (orgtbl-format-line prevline))))))
4714 (defun orgtbl-to-generic (table params &optional backend)
4715 "Convert the orgtbl-mode TABLE to some other format.
4716 This generic routine can be used for many standard cases.
4717 TABLE is a list, each entry either the symbol `hline' for a horizontal
4718 separator line, or a list of fields for that line.
4719 PARAMS is a property list of parameters that can influence the conversion.
4720 A third optional argument BACKEND can be used to convert the content of
4721 the cells using a specific export back-end.
4723 For the generic converter, some parameters are obligatory: you need to
4724 specify either :lfmt, or all of (:lstart :lend :sep).
4726 Valid parameters are:
4728 :splice When set to t, return only table body lines, don't wrap
4729 them into :tstart and :tend. Default is nil. When :splice
4730 is non-nil, this also means that the exporter should not look
4731 for and interpret header and footer sections.
4733 :hline String to be inserted on horizontal separation lines.
4734 May be nil to ignore hlines.
4736 :sep Separator between two fields
4737 :remove-nil-lines Do not include lines that evaluate to nil.
4739 Each in the following group may be either a string or a function
4740 of no arguments returning a string:
4742 :tstart String to start the table. Ignored when :splice is t.
4743 :tend String to end the table. Ignored when :splice is t.
4744 :lstart String to start a new table line.
4745 :llstart String to start the last table line, defaults to :lstart.
4746 :lend String to end a table line
4747 :llend String to end the last table line, defaults to :lend.
4749 Each in the following group may be a string, a function of one
4750 argument (the field or line) returning a string, or a plist
4751 mapping columns to either of the above:
4753 :lfmt Format for entire line, with enough %s to capture all fields.
4754 If this is present, :lstart, :lend, and :sep are ignored.
4755 :llfmt Format for the entire last line, defaults to :lfmt.
4756 :fmt A format to be used to wrap the field, should contain
4757 %s for the original field value. For example, to wrap
4758 everything in dollars, you could use :fmt \"$%s$\".
4759 This may also be a property list with column numbers and
4760 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4761 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4762 Same as above, specific for the header lines in the table.
4763 All lines before the first hline are treated as header.
4764 If any of these is not present, the data line value is used.
4766 This may be either a string or a function of two arguments:
4768 :efmt Use this format to print numbers with exponentials.
4769 The format should have %s twice for inserting mantissa
4770 and exponent, for example \"%s\\\\times10^{%s}\". This
4771 may also be a property list with column numbers and
4772 formats. :fmt will still be applied after :efmt.
4774 In addition to this, the parameters :skip and :skipcols are always handled
4775 directly by `orgtbl-send-table'. See manual."
4776 (let* ((splicep (plist-get params :splice))
4777 (hline (plist-get params :hline))
4778 (skipheadrule (plist-get params :skipheadrule))
4779 (remove-nil-linesp (plist-get params :remove-nil-lines))
4780 (remove-newlines (plist-get params :remove-newlines))
4781 (*orgtbl-hline* hline)
4782 (*orgtbl-table* table)
4783 (*orgtbl-sep* (plist-get params :sep))
4784 (*orgtbl-efmt* (plist-get params :efmt))
4785 (*orgtbl-lstart* (plist-get params :lstart))
4786 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4787 (*orgtbl-lend* (plist-get params :lend))
4788 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4789 (*orgtbl-lfmt* (plist-get params :lfmt))
4790 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4791 (*orgtbl-fmt* (plist-get params :fmt))
4793 ;; Convert cells content to backend BACKEND
4795 (setq *orgtbl-table*
4801 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4807 (when (plist-member params :tstart)
4808 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4809 (if tstart (push tstart *orgtbl-rtn*)))))
4810 ;; If we have a heading, format it and handle the trailing hline.
4811 (if (and (not splicep)
4812 (or (consp (car *orgtbl-table*))
4813 (consp (nth 1 *orgtbl-table*)))
4814 (memq 'hline (cdr *orgtbl-table*)))
4816 (when (eq 'hline (car *orgtbl-table*))
4817 ;; There is a hline before the first data line
4818 (and hline (push hline *orgtbl-rtn*))
4819 (pop *orgtbl-table*))
4820 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4822 (*orgtbl-llstart* (or (plist-get params :hllstart)
4824 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4825 (*orgtbl-llend* (or (plist-get params :hllend)
4826 (plist-get params :hlend) *orgtbl-llend*))
4827 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4828 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4829 (plist-get params :hlfmt) *orgtbl-llfmt*))
4830 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4831 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4832 (orgtbl-format-section 'hline))
4833 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4834 (pop *orgtbl-table*)))
4835 ;; Now format the main section.
4836 (orgtbl-format-section nil)
4838 (when (plist-member params :tend)
4839 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4840 (if tend (push tend *orgtbl-rtn*)))))
4841 (mapconcat (if remove-newlines
4843 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4845 (nreverse (if remove-nil-linesp
4846 (remq nil *orgtbl-rtn*)
4847 *orgtbl-rtn*)) "\n")))
4850 (defun orgtbl-to-tsv (table params)
4851 "Convert the orgtbl-mode table to TAB separated material."
4852 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4854 (defun orgtbl-to-csv (table params)
4855 "Convert the orgtbl-mode table to CSV material.
4856 This does take care of the proper quoting of fields with comma or quotes."
4857 (orgtbl-to-generic table (org-combine-plists
4858 '(:sep "," :fmt org-quote-csv-field)
4862 (defun orgtbl-to-latex (table params)
4863 "Convert the orgtbl-mode TABLE to LaTeX.
4864 TABLE is a list, each entry either the symbol `hline' for a horizontal
4865 separator line, or a list of fields for that line.
4866 PARAMS is a property list of parameters that can influence the conversion.
4867 Supports all parameters from `orgtbl-to-generic'. Most important for
4870 :splice When set to t, return only table body lines, don't wrap
4871 them into a tabular environment. Default is nil.
4873 :fmt A format to be used to wrap the field, should contain %s for the
4874 original field value. For example, to wrap everything in dollars,
4875 use :fmt \"$%s$\". This may also be a property list with column
4876 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4877 The format may also be a function that formats its one argument.
4879 :efmt Format for transforming numbers with exponentials. The format
4880 should have %s twice for inserting mantissa and exponent, for
4881 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4882 This may also be a property list with column numbers and formats.
4883 The format may also be a function that formats its two arguments.
4885 :llend If you find too much space below the last line of a table,
4886 pass a value of \"\" for :llend to suppress the final \\\\.
4888 The general parameters :skip and :skipcols have already been applied when
4889 this function is called."
4890 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4891 org-table-last-alignment ""))
4894 :tstart (concat "\\begin{tabular}{" alignment "}")
4895 :tend "\\end{tabular}"
4896 :lstart "" :lend " \\\\" :sep " & "
4897 :efmt "%s\\,(%s)" :hline "\\hline")))
4899 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4902 (defun orgtbl-to-html (table params)
4903 "Convert the orgtbl-mode TABLE to HTML.
4904 TABLE is a list, each entry either the symbol `hline' for a horizontal
4905 separator line, or a list of fields for that line.
4906 PARAMS is a property list of parameters that can influence the conversion.
4907 Currently this function recognizes the following parameters:
4909 :splice When set to t, return only table body lines, don't wrap
4910 them into a <table> environment. Default is nil.
4912 The general parameters :skip and :skipcols have already been applied when
4913 this function is called. The function does *not* use `orgtbl-to-generic',
4914 so you cannot specify parameters for it."
4916 (let ((output (org-export-string-as
4917 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4918 (if (not (plist-get params :splice)) output
4920 (replace-regexp-in-string
4921 "\\`<table .*>\n" ""
4922 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4925 (defun orgtbl-to-texinfo (table params)
4926 "Convert the orgtbl-mode TABLE to TeXInfo.
4927 TABLE is a list, each entry either the symbol `hline' for a horizontal
4928 separator line, or a list of fields for that line.
4929 PARAMS is a property list of parameters that can influence the conversion.
4930 Supports all parameters from `orgtbl-to-generic'. Most important for
4933 :splice nil/t When set to t, return only table body lines, don't wrap
4934 them into a multitable environment. Default is nil.
4936 :fmt fmt A format to be used to wrap the field, should contain
4937 %s for the original field value. For example, to wrap
4938 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4939 This may also be a property list with column numbers and
4940 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4941 Each format also may be a function that formats its one
4944 :cf \"f1 f2..\" The column fractions for the table. By default these
4945 are computed automatically from the width of the columns
4948 The general parameters :skip and :skipcols have already been applied when
4949 this function is called."
4950 (let* ((total (float (apply '+ org-table-last-column-widths)))
4951 (colfrac (or (plist-get params :cf)
4953 (lambda (x) (format "%.3f" (/ (float x) total)))
4954 org-table-last-column-widths " ")))
4957 :tstart (concat "@multitable @columnfractions " colfrac)
4958 :tend "@end multitable"
4959 :lstart "@item " :lend "" :sep " @tab "
4960 :hlstart "@headitem ")))
4961 (require 'ox-texinfo)
4962 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4965 (defun orgtbl-to-orgtbl (table params)
4966 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4967 Useful when slicing one table into many. The :hline, :sep,
4968 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4969 and :tend suppress strings without splicing; they can be set to
4970 provide ORGTBL directives for the generated table."
4974 :tstart nil :tend nil
4979 (params (org-combine-plists params2 params)))
4981 (insert (orgtbl-to-generic table params))
4982 (goto-char (point-min))
4983 (while (re-search-forward org-table-hline-regexp nil t)
4985 (buffer-substring 1 (buffer-size)))))
4987 (defun orgtbl-to-table.el (table params)
4988 "Convert the orgtbl-mode TABLE into a table.el table."
4990 (insert (orgtbl-to-orgtbl table params))
4992 (replace-regexp-in-string
4994 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4996 (defun orgtbl-to-unicode (table params)
4997 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4998 You need the ascii-art-to-unicode.el package for this. You can download
4999 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
5001 (insert (orgtbl-to-table.el table params))
5002 (goto-char (point-min))
5003 (if (or (featurep 'ascii-art-to-unicode)
5004 (require 'ascii-art-to-unicode nil t))
5006 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
5007 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
5008 "Link to ascii-art-to-unicode.el") org-stored-links))
5009 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
5012 ;; Put the cursor in a column containing numerical values
5013 ;; of an Org-Mode table,
5015 ;; A new column is added with a bar plot.
5016 ;; When the table is refreshed (C-u C-c *),
5017 ;; the plot is updated to reflect the new values.
5019 (defun orgtbl-ascii-draw (value min max &optional width characters)
5020 "Draw an ascii bar in a table.
5021 VALUE is a the value to plot, the width of the bar to draw. A
5022 value equal to MIN will be displayed as empty (zero width bar).
5023 A value equal to MAX will draw a bar filling all the WIDTH.
5024 WIDTH is the expected width in characters of the column.
5025 CHARACTERS is a string that will compose the bar, with shades of
5026 grey from pure white to pure black. It defaults to a 10
5027 characters string of regular ascii characters."
5028 (let* ((characters (or characters " .:;c!lhVHW"))
5029 (width (or width 12))
5030 (value (if (numberp value) value (string-to-number value)))
5031 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5033 ((< value 0) "too small")
5034 ((> value width) "too large")
5036 (let ((len (1- (length characters))))
5038 (make-string (floor value) (elt characters len))
5039 (string (elt characters
5040 (floor (* (- value (floor value)) len))))))))))
5043 (defun orgtbl-ascii-plot (&optional ask)
5044 "Draw an ascii bar plot in a column.
5045 With cursor in a column containing numerical values, this
5046 function will draw a plot in a new column.
5047 ASK, if given, is a numeric prefix to override the default 12
5048 characters width of the plot. ASK may also be the
5049 \\[universal-argument] prefix, which will prompt for the width."
5051 (let ((col (org-table-current-column))
5052 (min 1e999) ; 1e999 will be converted to infinity
5053 (max -1e999) ; which is the desired result
5054 (table (org-table-to-lisp))
5057 (read-number "Length of column " 12))
5060 ;; Skip any hline a the top of table.
5061 (while (eq (car table) 'hline) (setq table (cdr table)))
5062 ;; Skip table header if any.
5063 (dolist (x (or (cdr (memq 'hline table)) table))
5065 (setq x (nth (1- col) x))
5067 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5069 (setq x (string-to-number x))
5070 (when (> min x) (setq min x))
5071 (when (< max x) (setq max x)))))
5072 (org-table-insert-column)
5073 (org-table-move-column-right)
5074 (org-table-store-formulas
5077 (number-to-string (1+ col))
5078 (format "'(%s $%s %s %s %s)"
5079 "orgtbl-ascii-draw" col min max length))
5080 (org-table-get-stored-formulas)))
5081 (org-table-recalculate t)))
5083 ;; Example of extension: unicode characters
5084 ;; Here are two examples of different styles.
5086 ;; Unicode block characters are used to give a smooth effect.
5087 ;; See http://en.wikipedia.org/wiki/Block_Elements
5088 ;; Use one of those drawing functions
5089 ;; - orgtbl-ascii-draw (the default ascii)
5090 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5091 ;; - orgtbl-uc-draw-cont (smooth unicode)
5093 ;; This is best viewed with the "DejaVu Sans Mono" font
5094 ;; (use M-x set-default-font).
5096 (defun orgtbl-uc-draw-grid (value min max &optional width)
5097 "Draw a bar in a table using block unicode characters.
5098 It is a variant of orgtbl-ascii-draw with Unicode block
5099 characters, for a smooth display. Bars appear as grids (to the
5100 extent the font allows)."
5101 ;; http://en.wikipedia.org/wiki/Block_Elements
5102 ;; best viewed with the "DejaVu Sans Mono" font.
5103 (orgtbl-ascii-draw value min max width
5104 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5106 (defun orgtbl-uc-draw-cont (value min max &optional width)
5107 "Draw a bar in a table using block unicode characters.
5108 It is a variant of orgtbl-ascii-draw with Unicode block
5109 characters, for a smooth display. Bars are solid (to the extent
5111 (orgtbl-ascii-draw value min max width
5112 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5114 (defun org-table-get-remote-range (name-or-id form)
5115 "Get a field value or a list of values in a range from table at ID.
5117 NAME-OR-ID may be the name of a table in the current file as set
5118 by a \"#+NAME:\" directive. The first table following this line
5119 will then be used. Alternatively, it may be an ID referring to
5120 any entry, also in a different file. In this case, the first
5121 table in that entry will be referenced.
5122 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5123 \"@I$2..@II$2\". All the references must be absolute, not relative.
5125 The return value is either a single string for a single field, or a
5126 list of the fields in the rectangle."
5128 (let ((case-fold-search t) (id-loc nil)
5129 ;; Protect a bunch of variables from being overwritten
5130 ;; by the context of the remote table
5131 org-table-column-names org-table-column-name-regexp
5132 org-table-local-parameters org-table-named-field-locations
5133 org-table-current-line-types org-table-current-begin-line
5134 org-table-current-begin-pos org-table-dlines
5135 org-table-current-ncol
5136 org-table-hlines org-table-last-alignment
5137 org-table-last-column-widths org-table-last-alignment
5138 org-table-last-column-widths tbeg
5140 (setq form (org-table-convert-refs-to-rc form))
5145 (goto-char (point-min))
5146 (if (re-search-forward
5147 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5148 (regexp-quote name-or-id) "[ \t]*$")
5150 (setq buffer (current-buffer) loc (match-beginning 0))
5151 (setq id-loc (org-id-find name-or-id 'marker))
5152 (unless (and id-loc (markerp id-loc))
5153 (user-error "Can't find remote table \"%s\"" name-or-id))
5154 (setq buffer (marker-buffer id-loc)
5155 loc (marker-position id-loc))
5156 (move-marker id-loc nil)))
5157 (with-current-buffer buffer
5163 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5164 (not (match-beginning 1)))
5165 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5166 (setq tbeg (point-at-bol))
5167 (org-table-get-specials)
5168 (setq form (org-table-formula-substitute-names
5169 (org-table-formula-handle-first/last-rc form)))
5170 (if (and (string-match org-table-range-regexp form)
5171 (> (length (match-string 0 form)) 1))
5173 (org-table-get-range (match-string 0 form) tbeg 1))
5176 (defun org-table-remote-reference-indirection (form)
5177 "Return formula with table remote references substituted by indirection.
5178 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5179 This indirection works only with the format @ROW$COLUMN. The
5180 format \"B3\" is not supported because it can not be
5181 distinguished from a plain table name or ID."
5183 (while (string-match (concat
5184 ;; Same as in `org-table-eval-formula'.
5185 "\\<remote([ \t]*\\("
5186 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5188 ;; Same as in `org-table-eval-formula'.
5189 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5192 ;; The position of the character as far as possible to the right
5193 ;; that will not be replaced and particularly not be shifted by
5195 (setq start (match-beginning 1))
5196 ;; Substitute the remote reference with the value found in the
5201 (org-table-get-range (org-table-formula-handle-first/last-rc
5202 (match-string 1 form))))
5206 (defmacro org-define-lookup-function (mode)
5207 (let ((mode-str (symbol-name mode))
5208 (first-p (equal mode 'first))
5209 (all-p (equal mode 'all)))
5210 (let ((plural-str (if all-p "s" "")))
5211 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5212 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5213 If R-LIST is nil, return matching element%s of S-LIST.
5214 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5215 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5216 This function is generated by a call to the macro `org-define-lookup-function'."
5217 mode-str plural-str plural-str plural-str)
5218 (let ,(let ((lvars '((p (or predicate 'equal))
5220 (rl (or r-list s-list))
5222 (if first-p (add-to-list 'lvars '(match-p nil)))
5224 (while ,(if first-p '(and (not match-p) sl) 'sl)
5226 (if (funcall p val (car sl))
5228 ,(if first-p '(setq match-p t))
5229 (let ((rval (car rl)))
5230 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5231 (setq sl (cdr sl) rl (cdr rl))))
5234 (org-define-lookup-function first)
5235 (org-define-lookup-function last)
5236 (org-define-lookup-function all)
5238 (provide 'org-table)
5241 ;; generated-autoload-file: "org-loaddefs.el"
5244 ;;; org-table.el ends here