1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2015 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org-mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org-mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
41 (declare-function org-element-at-point
"org-element" ())
42 (declare-function org-element-contents
"org-element" (element))
43 (declare-function org-element-extract-element
"org-element" (element))
44 (declare-function org-element-interpret-data
"org-element" (data))
45 (declare-function org-element-lineage
"org-element"
46 (blob &optional types with-self
))
47 (declare-function org-element-map
"org-element"
49 &optional info first-match no-recursion with-affiliated
))
50 (declare-function org-element-property
"org-element" (property element
))
52 (declare-function org-export-string-as
"ox"
53 (string backend
&optional body-only ext-plist
))
54 (declare-function org-export-create-backend
"ox")
55 (declare-function org-export-get-backend
"ox" (name))
57 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
59 (defvar orgtbl-mode
) ; defined below
60 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
61 (defvar constants-unit-system
)
62 (defvar org-table-follow-field-mode
)
64 (defvar orgtbl-after-send-table-hook nil
65 "Hook for functions attaching to `C-c C-c', if the table is sent.
66 This can be used to add additional functionality after the table is sent
67 to the receiver position, otherwise, if table is not sent, the functions
70 (defvar org-table-TBLFM-begin-regexp
"^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
72 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
73 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
74 In the optimized version, the table editor takes over all simple keys that
75 normally just insert a character. In tables, the characters are inserted
76 in a way to minimize disturbing the table structure (i.e. in overwrite mode
77 for empty fields). Outside tables, the correct binding of the keys is
80 The default for this option is t if the optimized version is also used in
81 Org-mode. See the variable `org-enable-table-editor' for details. Changing
82 this variable requires a restart of Emacs to become effective."
86 (defcustom orgtbl-radio-table-templates
87 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
88 % END RECEIVE ORGTBL %n
90 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
93 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
94 @c END RECEIVE ORGTBL %n
96 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
99 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
100 <!-- END RECEIVE ORGTBL %n -->
102 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
105 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
106 #+ END RECEIVE ORGTBL %n
108 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
111 "Templates for radio tables in different major modes.
112 Each template must define lines that will be treated as a comment and that
113 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
114 lines where \"%n\" will be replaced with the name of the table during
115 insertion of the template. The transformed table will later be inserted
118 The template should also contain a minimal table in a multiline comment.
119 If multiline comments are not possible in the buffer language,
120 you can pack it into a string that will not be used when the code
121 is compiled or executed. Above the table will you need a line with
122 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
123 convert the table into a data structure useful in the
124 language of the buffer. Check the manual for the section on
125 \"Translator functions\", and more generally check out
126 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
128 All occurrences of %n in a template will be replaced with the name of the
129 table, obtained by prompting the user."
132 (list (symbol :tag
"Major mode")
133 (string :tag
"Format"))))
135 (defgroup org-table-settings nil
136 "Settings for tables in Org-mode."
137 :tag
"Org Table Settings"
140 (defcustom org-table-default-size
"5x2"
141 "The default size for newly created tables, Columns x Rows."
142 :group
'org-table-settings
145 (defcustom org-table-number-regexp
146 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
147 "Regular expression for recognizing numbers in table columns.
148 If a table column contains mostly numbers, it will be aligned to the
149 right. If not, it will be aligned to the left.
151 The default value of this option is a regular expression which allows
152 anything which looks remotely like a number as used in scientific
153 context. For example, all of the following will be considered a
155 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
157 Other options offered by the customize interface are more restrictive."
158 :group
'org-table-settings
160 (const :tag
"Positive Integers"
162 (const :tag
"Integers"
164 (const :tag
"Floating Point Numbers"
165 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
166 (const :tag
"Floating Point Number or Integer"
167 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
168 (const :tag
"Exponential, Floating point, Integer"
169 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
170 (const :tag
"Very General Number-Like, including hex and Calc radix"
171 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
172 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
173 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
174 (string :tag
"Regexp:")))
176 (defcustom org-table-number-fraction
0.5
177 "Fraction of numbers in a column required to make the column align right.
178 In a column all non-white fields are considered. If at least
179 this fraction of fields is matched by `org-table-number-regexp',
180 alignment to the right border applies."
181 :group
'org-table-settings
184 (defgroup org-table-editing nil
185 "Behavior of tables during editing in Org-mode."
186 :tag
"Org Table Editing"
189 (defcustom org-table-automatic-realign t
190 "Non-nil means automatically re-align table when pressing TAB or RETURN.
191 When nil, aligning is only done with \\[org-table-align], or after column
193 :group
'org-table-editing
196 (defcustom org-table-auto-blank-field t
197 "Non-nil means automatically blank table field when starting to type into it.
198 This only happens when typing immediately after a field motion
199 command (TAB, S-TAB or RET).
200 Only relevant when `org-enable-table-editor' is equal to `optimized'."
201 :group
'org-table-editing
204 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
205 "Non-nil means automatically exit the follow mode.
206 When nil, the follow mode will stay on and be active in any table
207 the cursor enters. Since the table follow filed mode messes with the
208 window configuration, it is not recommended to set this variable to nil,
209 except maybe locally in a special file that has mostly tables with long
215 (defcustom org-table-fix-formulas-confirm nil
216 "Whether the user should confirm when Org fixes formulas."
217 :group
'org-table-editing
220 (const :tag
"with yes-or-no" yes-or-no-p
)
221 (const :tag
"with y-or-n" y-or-n-p
)
222 (const :tag
"no confirmation" nil
)))
223 (put 'org-table-fix-formulas-confirm
225 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
227 (defcustom org-table-tab-jumps-over-hlines t
228 "Non-nil means tab in the last column of a table with jump over a hline.
229 If a horizontal separator line is following the current line,
230 `org-table-next-field' can either create a new row before that line, or jump
231 over the line. When this option is nil, a new line will be created before
233 :group
'org-table-editing
236 (defgroup org-table-calculation nil
237 "Options concerning tables in Org-mode."
238 :tag
"Org Table Calculation"
241 (defcustom org-table-use-standard-references
'from
242 "Should org-mode work with table references like B3 instead of @3$2?
245 from accept as input, do not present for editing
246 t accept as input and present for editing"
247 :group
'org-table-calculation
249 (const :tag
"Never, don't even check user input for them" nil
)
250 (const :tag
"Always, both as user input, and when editing" t
)
251 (const :tag
"Convert user input, don't offer during editing" from
)))
253 (defcustom org-table-copy-increment t
254 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
255 :group
'org-table-calculation
257 :package-version
'(Org .
"8.3")
259 (const :tag
"Use the difference between the current and the above fields" t
)
260 (integer :tag
"Use a number" 1)
261 (const :tag
"Don't increment the value when copying a field" nil
)))
263 (defcustom org-calc-default-modes
264 '(calc-internal-prec 12
265 calc-float-format
(float 8)
268 calc-symbolic-mode nil
269 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
270 calc-display-working-message t
272 "List with Calc mode settings for use in `calc-eval' for table formulas.
273 The list must contain alternating symbols (Calc modes variables and values).
274 Don't remove any of the default settings, just change the values. Org-mode
275 relies on the variables to be present in the list."
276 :group
'org-table-calculation
279 (defcustom org-table-duration-custom-format
'hours
280 "Format for the output of calc computations like $1+$2;t.
281 The default value is 'hours, and will output the results as a
282 number of hours. Other allowed values are 'seconds, 'minutes and
283 'days, and the output will be a fraction of seconds, minutes or
285 :group
'org-table-calculation
287 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
288 (symbol :tag
"Minutes" 'minutes
)
289 (symbol :tag
"Hours " 'hours
)
290 (symbol :tag
"Days " 'days
)))
292 (defcustom org-table-formula-field-format
"%s"
293 "Format for fields which contain the result of a formula.
294 For example, using \"~%s~\" will display the result within tilde
295 characters. Beware that modifying the display can prevent the
296 field from being used in another formula."
297 :group
'org-table-settings
301 (defcustom org-table-formula-evaluate-inline t
302 "Non-nil means TAB and RET evaluate a formula in current table field.
303 If the current field starts with an equal sign, it is assumed to be a formula
304 which should be evaluated as described in the manual and in the documentation
305 string of the command `org-table-eval-formula'. This feature requires the
307 When this variable is nil, formula calculation is only available through
308 the command \\[org-table-eval-formula]."
309 :group
'org-table-calculation
312 (defcustom org-table-formula-use-constants t
313 "Non-nil means interpret constants in formulas in tables.
314 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
315 by the value given in `org-table-formula-constants', or by a value obtained
316 from the `constants.el' package."
317 :group
'org-table-calculation
320 (defcustom org-table-formula-constants nil
321 "Alist with constant names and values, for use in table formulas.
322 The car of each element is a name of a constant, without the `$' before it.
323 The cdr is the value as a string. For example, if you'd like to use the
324 speed of light in a formula, you would configure
326 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
328 and then use it in an equation like `$1*$c'.
330 Constants can also be defined on a per-file basis using a line like
332 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
333 :group
'org-table-calculation
335 (cons (string :tag
"name")
336 (string :tag
"value"))))
338 (defcustom org-table-allow-automatic-line-recalculation t
339 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
340 Automatically means when TAB or RET or C-c C-c are pressed in the line."
341 :group
'org-table-calculation
344 (defcustom org-table-relative-ref-may-cross-hline t
345 "Non-nil means relative formula references may cross hlines.
346 Here are the allowed values:
348 nil Relative references may not cross hlines. They will reference the
349 field next to the hline instead. Coming from below, the reference
350 will be to the field below the hline. Coming from above, it will be
352 t Relative references may cross hlines.
353 error An attempt to cross a hline will throw an error.
355 It is probably good to never set this variable to nil, for the sake of
356 portability of tables."
357 :group
'org-table-calculation
359 (const :tag
"Allow to cross" t
)
360 (const :tag
"Stick to hline" nil
)
361 (const :tag
"Error on attempt to cross" error
)))
363 (defcustom org-table-formula-create-columns nil
364 "Non-nil means that evaluation of a field formula can add new
365 columns if an out-of-bounds field is being set."
366 :group
'org-table-calculation
368 :package-version
'(Org .
"8.3")
370 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
371 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
372 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
373 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
375 (defgroup org-table-import-export nil
376 "Options concerning table import and export in Org-mode."
377 :tag
"Org Table Import Export"
380 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
381 "Default export parameters for `org-table-export'.
382 These can be overridden for a specific table by setting the
383 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
384 radio tables for the different export transformations and
385 available parameters."
386 :group
'org-table-import-export
389 (defcustom org-table-convert-region-max-lines
999
390 "Max lines that `org-table-convert-region' will attempt to process.
392 The function can be slow on larger regions; this safety feature
393 prevents it from hanging emacs."
394 :group
'org-table-import-export
397 :package-version
'(Org .
"8.3"))
399 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
400 "Detects a table line marked for automatic recalculation.")
401 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
402 "Detects a table line marked for automatic recalculation.")
403 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
404 "Detects a table line marked for automatic recalculation.")
405 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
406 "Searching from within a table (any type) this finds the first line outside the table.")
407 (defvar org-table-last-highlighted-reference nil
)
408 (defvar org-table-formula-history nil
)
410 (defvar org-table-column-names nil
411 "Alist with column names, derived from the `!' line.")
412 (defvar org-table-column-name-regexp nil
413 "Regular expression matching the current column names.")
414 (defvar org-table-local-parameters nil
415 "Alist with parameter names, derived from the `$' line.")
416 (defvar org-table-named-field-locations nil
417 "Alist with locations of named fields.")
419 (defvar org-table-current-line-types nil
420 "Table row types, non-nil only for the duration of a command.")
421 (defvar org-table-current-begin-line nil
422 "Table begin line, non-nil only for the duration of a command.")
423 (defvar org-table-current-begin-pos nil
424 "Table begin position, non-nil only for the duration of a command.")
425 (defvar org-table-current-ncol nil
426 "Number of columns in table, non-nil only for the duration of a command.")
427 (defvar org-table-dlines nil
428 "Vector of data line line numbers in the current table.")
429 (defvar org-table-hlines nil
430 "Vector of hline line numbers in the current table.")
432 (defconst org-table-range-regexp
433 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
435 "Regular expression for matching ranges in formulas.")
437 (defconst org-table-range-regexp2
439 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
441 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
442 "Match a range for reference display.")
444 (defun org-table-colgroup-line-p (line)
445 "Is this a table line colgroup information?"
447 (and (string-match "[<>]\\|&[lg]t;" line
)
448 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
454 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
455 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
457 (defun org-table-cookie-line-p (line)
458 "Is this a table line with only alignment/width cookies?"
460 (and (string-match "[<>]\\|&[lg]t;" line
)
462 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
463 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
464 (not (delq nil
(mapcar
466 (not (or (equal s
"")
468 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
470 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
472 (org-split-string (match-string 1 line
)
473 "[ \t]*|[ \t]*")))))))
475 (defconst org-table-translate-regexp
476 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
477 "Match a reference that needs translation, for reference display.")
480 (defun org-table-create-with-table.el
()
481 "Use the table.el package to insert a new table.
482 If there is already a table at point, convert between Org-mode tables
483 and table.el tables."
488 (if (y-or-n-p "Convert table to Org-mode table? ")
489 (org-table-convert)))
491 (when (y-or-n-p "Convert table to table.el table? ")
493 (org-table-convert)))
494 (t (call-interactively 'table-insert
))))
497 (defun org-table-create-or-convert-from-region (arg)
498 "Convert region to table, or create an empty table.
499 If there is an active region, convert it to a table, using the function
500 `org-table-convert-region'. See the documentation of that function
501 to learn how the prefix argument is interpreted to determine the field
503 If there is no such region, create an empty table with `org-table-create'."
505 (if (org-region-active-p)
506 (org-table-convert-region (region-beginning) (region-end) arg
)
507 (org-table-create arg
)))
510 (defun org-table-create (&optional size
)
511 "Query for a size and insert a table skeleton.
512 SIZE is a string Columns x Rows like for example \"3x2\"."
515 (setq size
(read-string
516 (concat "Table size Columns x Rows [e.g. "
517 org-table-default-size
"]: ")
518 "" nil org-table-default-size
)))
521 (indent (make-string (current-column) ?\
))
522 (split (org-split-string size
" *x *"))
523 (rows (string-to-number (nth 1 split
)))
524 (columns (string-to-number (car split
)))
525 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
527 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
528 (point-at-bol) (point)))
529 (beginning-of-line 1)
531 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
532 (dotimes (i rows
) (insert line
))
535 ;; Insert a hline after the first row.
543 (defun org-table-convert-region (beg0 end0
&optional separator
)
544 "Convert region to a table.
545 The region goes from BEG0 to END0, but these borders will be moved
546 slightly, to make sure a beginning of line in the first line is included.
548 SEPARATOR specifies the field separator in the lines. It can have the
551 '(4) Use the comma as a field separator
552 '(16) Use a TAB as field separator
553 '(64) Prompt for a regular expression as field separator
554 integer When a number, use that many spaces as field separator
555 regexp When a regular expression, use it to match the separator
556 nil When nil, the command tries to be smart and figure out the
557 separator in the following way:
558 - when each line contains a TAB, assume TAB-separated material
559 - when each line contains a comma, assume CSV material
560 - else, assume one or more SPACE characters as separator."
562 (let* ((beg (min beg0 end0
))
563 (end (max beg0 end0
))
565 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
566 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
567 org-table-convert-region-max-lines
)
568 (if (equal separator
'(64))
569 (setq separator
(read-regexp "Regexp for field separator")))
571 (beginning-of-line 1)
572 (setq beg
(point-marker))
574 (if (bolp) (backward-char 1) (end-of-line 1))
575 (setq end
(point-marker))
576 ;; Get the right field separator
581 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
582 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
585 (if (equal separator
'(4))
586 (while (< (point) end
)
587 ;; parse the csv stuff
589 ((looking-at "^") (insert "| "))
590 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
591 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
592 (replace-match "\\1")
593 (if (looking-at "\"") (insert "\"")))
594 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
595 ((looking-at "[ \t]*,") (replace-match " | "))
596 (t (beginning-of-line 2))))
598 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
599 ((equal separator
'(16)) "^\\|\t")
600 ((integerp separator
)
602 (user-error "Number of spaces in separator must be >= 1")
603 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
605 (format "^ *\\|%s" separator
))
606 (t (error "This should not happen"))))
607 (while (re-search-forward re end t
)
608 (replace-match "| " t t
)))
613 (defun org-table-import (file arg
)
614 "Import FILE as a table.
615 The file is assumed to be tab-separated. Such files can be produced by most
616 spreadsheet and database applications. If no tabs (at least one per line)
617 are found, lines will be split on whitespace into fields."
619 (or (bolp) (newline))
622 (insert-file-contents file
)
623 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
627 (defun org-table-export (&optional file format
)
628 "Export table to a file, with configurable format.
629 Such a file can be imported into usual spreadsheet programs.
631 FILE can be the output file name. If not given, it will be taken
632 from a TABLE_EXPORT_FILE property in the current entry or higher
633 up in the hierarchy, or the user will be prompted for a file
634 name. FORMAT can be an export format, of the same kind as it
635 used when `orgtbl-mode' sends a table in a different format.
637 The command suggests a format depending on TABLE_EXPORT_FORMAT,
638 whether it is set locally or up in the hierarchy, then on the
639 extension of the given file name, and finally on the variable
640 `org-table-export-default-format'."
642 (unless (org-at-table-p) (user-error "No table at point"))
643 (org-table-align) ; Make sure we have everything we need.
644 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
646 (setq file
(read-file-name "Export table to: "))
647 (unless (or (not (file-exists-p file
))
648 (y-or-n-p (format "Overwrite file %s? " file
)))
649 (user-error "File not written")))
650 (when (file-directory-p file
)
651 (user-error "This is a directory path, not a file"))
652 (when (and (buffer-file-name (buffer-base-buffer))
655 (file-truename (buffer-file-name (buffer-base-buffer)))))
656 (user-error "Please specify a file name that is different from current"))
657 (let ((fileext (concat (file-name-extension file
) "$"))
658 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
660 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
661 "orgtbl-to-html" "orgtbl-to-generic"
662 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
663 "orgtbl-to-unicode"))
665 (replace-regexp-in-string
667 (replace-regexp-in-string
672 (and (org-string-match-p fileext f
) f
))
674 org-table-export-default-format
)
678 "Format: " formats nil nil deffmt-readable
))))
679 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
680 (let ((transform (intern (match-string 1 format
)))
681 (params (and (match-end 2)
682 (read (concat "(" (match-string 2 format
) ")"))))
683 (table (org-table-to-lisp
684 (buffer-substring-no-properties
685 (org-table-begin) (org-table-end)))))
686 (unless (fboundp transform
)
687 (user-error "No such transformation function %s" transform
))
689 (with-current-buffer (find-file-noselect file
)
690 (setq buf
(current-buffer))
693 (insert (funcall transform table params
) "\n")
696 (message "Export done."))
697 (user-error "TABLE_EXPORT_FORMAT invalid")))))
699 (defvar org-table-aligned-begin-marker
(make-marker)
700 "Marker at the beginning of the table last aligned.
701 Used to check if cursor still is in that table, to minimize realignment.")
702 (defvar org-table-aligned-end-marker
(make-marker)
703 "Marker at the end of the table last aligned.
704 Used to check if cursor still is in that table, to minimize realignment.")
705 (defvar org-table-last-alignment nil
706 "List of flags for flushright alignment, from the last re-alignment.
707 This is being used to correctly align a single field after TAB or RET.")
708 (defvar org-table-last-column-widths nil
709 "List of max width of fields in each column.
710 This is being used to correctly align a single field after TAB or RET.")
711 (defvar org-table-formula-debug nil
712 "Non-nil means debug table formulas.
713 When nil, simply write \"#ERROR\" in corrupted fields.")
714 (make-variable-buffer-local 'org-table-formula-debug
)
715 (defvar org-table-overlay-coordinates nil
716 "Overlay coordinates after each align of a table.")
717 (make-variable-buffer-local 'org-table-overlay-coordinates
)
719 (defvar org-last-recalc-line nil
)
720 (defvar org-table-do-narrow t
) ; for dynamic scoping
721 (defconst org-narrow-column-arrow
"=>"
722 "Used as display property in narrowed table columns.")
725 (defun org-table-align ()
726 "Align the table at point by aligning all vertical bars."
728 (let ((beg (org-table-begin))
729 (end (copy-marker (org-table-end)))
730 (linepos (copy-marker (line-beginning-position)))
731 (colpos (org-table-current-column)))
732 ;; Make sure invisible characters in the table are at the right
733 ;; place since column widths take them into account.
734 (font-lock-fontify-region beg end
)
735 (move-marker org-table-aligned-begin-marker beg
)
736 (move-marker org-table-aligned-end-marker end
)
738 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
739 ;; Table's rows. Separators are replaced by nil. Trailing
740 ;; spaces are also removed.
741 (lines (mapcar (lambda (l)
742 (and (not (org-string-match-p "\\`[ \t]*|-" l
))
743 (let ((l (org-trim l
)))
744 (remove-text-properties
745 0 (length l
) '(display t org-cwidth t
) l
)
747 (org-split-string (buffer-substring beg end
) "\n")))
748 ;; Get the data fields by splitting the lines.
749 (fields (mapcar (lambda (l) (org-split-string l
" *| *"))
751 ;; Compute number of fields in the longest line. If the
752 ;; table contains no field, create a default table.
753 (maxfields (if fields
(apply #'max
(mapcar #'length fields
))
754 (kill-region beg end
)
755 (org-table-create org-table-default-size
)
756 (user-error "Empty table - created default table")))
757 ;; A list of empty strings to fill any short rows on output.
758 (emptycells (make-list maxfields
""))
760 ;; Check for special formatting.
761 (dotimes (i maxfields
)
762 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) fields
))
764 ;; Look for an explicit width or alignment.
765 (when (save-excursion
766 (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t
)
767 (and org-table-do-narrow
769 "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t
))))
771 (dolist (cell column
)
772 (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell
)
773 (when (match-end 1) (setq falign
(match-string 1 cell
)))
774 (when (and org-table-do-narrow
(match-end 2))
775 (setq fmax
(string-to-number (match-string 2 cell
))))
776 (when (or falign fmax
) (throw :exit nil
)))))
777 ;; Find fields that are wider than FMAX, and shorten them.
780 (when (> (org-string-width x
) fmax
)
784 (substitute-command-keys
785 "Clipped table field, use \\[org-table-edit-field] to \
786 edit. Full value is:\n")
787 (substring-no-properties x
)))
790 (or (string-match org-bracket-link-regexp x
)
795 "Cannot narrow field starting with wide link \"%s\""
797 (if (= (org-string-width x
) l
) (setq f2 f1
)
799 (while (< (org-string-width (substring x
0 f2
)) f1
)
801 (add-text-properties f2 l
(list 'org-cwidth t
) x
)
803 (if (>= (string-width (substring x
(1- f2
) f2
)) 2) (1- f2
)
806 (list 'display org-narrow-column-arrow
)
808 ;; Get the maximum width for each column
809 (push (apply #'max
(or fmax
1) 1 (mapcar #'org-string-width column
))
811 ;; Get the fraction of numbers among non-empty cells to
812 ;; decide about alignment of the column.
813 (if falign
(push (equal (downcase falign
) "r") typenums
)
820 (if (org-string-match-p org-table-number-regexp x
)
824 (push (>= frac org-table-number-fraction
) typenums
)))))
825 (setq lengths
(nreverse lengths
))
826 (setq typenums
(nreverse typenums
))
827 ;; Store alignment of this table, for later editing of single
829 (setq org-table-last-alignment typenums
)
830 (setq org-table-last-column-widths lengths
)
831 ;; With invisible characters, `format' does not get the field
832 ;; width right So we need to make these fields wide by hand.
833 ;; Invisible characters may be introduced by fontified links,
834 ;; emphasis, macros or sub/superscripts.
835 (when (or (text-property-any beg end
'invisible
'org-link
)
836 (text-property-any beg end
'invisible t
))
837 (dotimes (i maxfields
)
838 (let ((len (nth i lengths
)))
839 (dotimes (j (length fields
))
840 (let* ((c (nthcdr i
(nth j fields
)))
844 (let ((l (length cell
)))
845 (or (text-property-any 0 l
'invisible
'org-link cell
)
846 (text-property-any beg end
'invisible t
)))
847 (< (org-string-width cell
) len
))
848 (let ((s (make-string (- len
(org-string-width cell
)) ?\s
)))
849 (setcar c
(if (nth i typenums
) (concat s cell
)
850 (concat cell s
))))))))))
852 ;; Compute the formats needed for output of the table.
853 (let ((hfmt (concat indent
"|"))
854 (rfmt (concat indent
"|"))
857 (dolist (l lengths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
858 (let ((ty (if (pop typenums
) "" "-"))) ; Flush numbers right.
859 (setq rfmt
(concat rfmt
(format rfmt1 ty l
)))
860 (setq hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
))))))
861 ;; Replace modified lines only. Check not only contents, but
862 ;; also columns' width.
865 (if l
(apply #'format rfmt
(append (pop fields
) emptycells
))
867 (previous (buffer-substring (point) (line-end-position))))
868 (if (and (equal previous line
)
872 (setq a
(next-single-property-change
873 a
'org-cwidth previous
))
874 (setq b
(next-single-property-change
875 b
'org-cwidth line
)))
880 (delete-region (point) (line-beginning-position 2))))))
881 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
882 (goto-char org-table-aligned-begin-marker
)
883 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
885 (org-table-goto-column colpos
)
887 (set-marker linepos nil
)
888 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
889 (setq org-table-may-need-update nil
))))
892 (defun org-table-begin (&optional table-type
)
893 "Find the beginning of the table and return its position.
894 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
895 (let ((table (org-element-lineage (org-element-at-point) '(table) t
)))
896 (and table
(org-element-property :post-affiliated table
))))
899 (defun org-table-end (&optional table-type
)
900 "Find the end of the table and return its position.
901 With argument TABLE-TYPE, go to the end of a table.el-type table."
902 (let ((table (org-element-lineage (org-element-at-point) '(table) t
)))
904 (let ((type (org-element-property :type table
)))
905 (if (eq type
'org
) (org-element-property :contents-end table
)
907 (goto-char (org-element-property :end table
))
908 (skip-chars-backward " \t\n")
909 (line-beginning-position 2)))))))
912 (defun org-table-justify-field-maybe (&optional new
)
913 "Justify the current field, text to left, number to right.
914 Optional argument NEW may specify text to replace the current field content."
916 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
917 ((org-at-table-hline-p))
919 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
921 (< (point) org-table-aligned-begin-marker
)
922 (>= (point) org-table-aligned-end-marker
)))
923 ;; This is not the same table, force a full re-align
924 (setq org-table-may-need-update t
))
925 (t ;; realign the current field, based on previous full realign
926 (let* ((pos (point)) s
927 (col (org-table-current-column))
928 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
931 (skip-chars-backward "^|\n")
932 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
934 (setq s
(match-string 1)
938 (buffer-substring-no-properties
939 (match-end 0) (match-beginning 0))) 3))
940 e
(not (= (match-beginning 2) (match-end 2))))
941 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
942 l
(if e
"|" (setq org-table-may-need-update t
) ""))
945 (if (<= (org-string-width new
) l
)
946 (setq n
(format f new
))
947 (setq n
(concat new
"|") org-table-may-need-update t
)))
948 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
950 (let (org-table-may-need-update)
951 (replace-match n t t
))))
952 (setq org-table-may-need-update t
))
956 (defun org-table-next-field ()
957 "Go to the next field in the current table, creating new lines as needed.
958 Before doing so, re-align the table if necessary."
960 (org-table-maybe-eval-formula)
961 (org-table-maybe-recalculate-line)
962 (if (and org-table-automatic-realign
963 org-table-may-need-update
)
965 (let ((end (org-table-end)))
966 (if (org-at-table-hline-p)
970 (re-search-forward "|" end
)
971 (if (looking-at "[ \t]*$")
972 (re-search-forward "|" end
))
973 (if (and (looking-at "-")
974 org-table-tab-jumps-over-hlines
975 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
976 (goto-char (match-beginning 1)))
979 (beginning-of-line 0)
980 (org-table-insert-row 'below
))
981 (if (looking-at " ") (forward-char 1))))
983 (org-table-insert-row 'below
)))))
986 (defun org-table-previous-field ()
987 "Go to the previous field in the table.
988 Before doing so, re-align the table if necessary."
990 (org-table-justify-field-maybe)
991 (org-table-maybe-recalculate-line)
992 (if (and org-table-automatic-realign
993 org-table-may-need-update
)
995 (if (org-at-table-hline-p)
999 (re-search-backward "|" (org-table-begin))
1000 (re-search-backward "|" (org-table-begin)))
1001 (error (user-error "Cannot move to previous table field")))
1002 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1003 (re-search-backward "|" (org-table-begin)))
1004 (if (looking-at "| ?")
1005 (goto-char (match-end 0))))
1007 (defun org-table-beginning-of-field (&optional n
)
1008 "Move to the beginning of the current table field.
1009 If already at or before the beginning, move to the beginning of the
1011 With numeric argument N, move N-1 fields backward first."
1013 (let ((pos (point)))
1016 (org-table-previous-field))
1017 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1018 (user-error "No more table fields before the current")
1019 (goto-char (match-end 0))
1020 (and (looking-at " ") (forward-char 1)))
1021 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1023 (defun org-table-end-of-field (&optional n
)
1024 "Move to the end of the current table field.
1025 If already at or after the end, move to the end of the next table field.
1026 With numeric argument N, move N-1 fields forward first."
1028 (let ((pos (point)))
1031 (org-table-next-field))
1032 (when (re-search-forward "|" (point-at-eol 1) t
)
1034 (skip-chars-backward " ")
1035 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1037 (if (<= (point) pos
) (org-table-end-of-field 2))))
1040 (defun org-table-next-row ()
1041 "Go to the next row (same column) in the current table.
1042 Before doing so, re-align the table if necessary."
1044 (org-table-maybe-eval-formula)
1045 (org-table-maybe-recalculate-line)
1046 (if (or (looking-at "[ \t]*$")
1047 (save-excursion (skip-chars-backward " \t") (bolp)))
1049 (if (and org-table-automatic-realign
1050 org-table-may-need-update
)
1052 (let ((col (org-table-current-column)))
1053 (beginning-of-line 2)
1054 (if (or (not (org-at-table-p))
1055 (org-at-table-hline-p))
1057 (beginning-of-line 0)
1058 (org-table-insert-row 'below
)))
1059 (org-table-goto-column col
)
1060 (skip-chars-backward "^|\n\r")
1061 (if (looking-at " ") (forward-char 1)))))
1064 (defun org-table-copy-down (n)
1065 "Copy the value of the current field one row below.
1067 If the field at the cursor is empty, copy the content of the
1068 nearest non-empty field above. With argument N, use the Nth
1071 If the current field is not empty, it is copied down to the next
1072 row, and the cursor is moved with it. Therefore, repeating this
1073 command causes the column to be filled row-by-row.
1075 If the variable `org-table-copy-increment' is non-nil and the
1076 field is an integer or a timestamp, it will be incremented while
1077 copying. By default, increment by the difference between the
1078 value in the current field and the one in the field above. To
1079 increment using a fixed integer, set `org-table-copy-increment'
1080 to a number. In the case of a timestamp, increment by days."
1082 (let* ((colpos (org-table-current-column))
1083 (col (current-column))
1084 (field (save-excursion (org-table-get-field)))
1085 (field-up (or (save-excursion
1086 (org-table-get (1- (org-table-current-line))
1087 (org-table-current-column))) ""))
1088 (non-empty (string-match "[^ \t]" field
))
1089 (non-empty-up (string-match "[^ \t]" field-up
))
1090 (beg (org-table-begin))
1093 (org-table-check-inside-data-field)
1098 (while (progn (beginning-of-line 1)
1099 (re-search-backward org-table-dataline-regexp
1101 (org-table-goto-column colpos t
)
1102 (if (and (looking-at
1103 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1104 (<= (setq n
(1- n
)) 0))
1105 (throw 'exit
(match-string 1))))))
1108 (while (progn (beginning-of-line 1)
1109 (re-search-backward org-table-dataline-regexp
1111 (org-table-goto-column colpos t
)
1112 (if (and (looking-at
1113 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1114 (<= (setq n
(1- n
)) 0))
1115 (throw 'exit
(match-string 1))))))
1116 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1117 ;; Above field was not empty, go down to the next row
1118 (setq txt
(org-trim field
))
1119 (org-table-next-row)
1120 (org-table-blank-field))
1121 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1123 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1124 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1125 (string-match org-ts-regexp3 txt
))
1126 (- (org-time-string-to-absolute txt
)
1127 (org-time-string-to-absolute txt-up
)))
1128 ((string-match org-ts-regexp3 txt
) 1)
1129 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1130 (- (string-to-number txt
)
1131 (string-to-number (match-string 0 txt-up
))))
1135 (user-error "No non-empty field found")
1136 (if (and org-table-copy-increment
1137 (not (equal orig-n
0))
1138 (string-match "^[-+^/*0-9eE.]+$" txt
)
1139 (< (string-to-number txt
) 100000000))
1140 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1142 (org-move-to-column col
)
1143 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1144 (org-timestamp-up-day inc
)
1145 (org-table-maybe-recalculate-line))
1147 (org-move-to-column col
))))
1149 (defun org-table-check-inside-data-field (&optional noerror
)
1150 "Is point inside a table data field?
1151 I.e. not on a hline or before the first or after the last column?
1152 This actually throws an error, so it aborts the current command."
1153 (if (or (not (org-at-table-p))
1154 (= (org-table-current-column) 0)
1155 (org-at-table-hline-p)
1156 (looking-at "[ \t]*$"))
1159 (user-error "Not in table data field"))
1162 (defvar org-table-clip nil
1163 "Clipboard for table regions.")
1165 (defun org-table-get (line column
)
1166 "Get the field in table line LINE, column COLUMN.
1167 If LINE is larger than the number of data lines in the table, the function
1168 returns nil. However, if COLUMN is too large, we will simply return an
1170 If LINE is nil, use the current line.
1171 If COLUMN is nil, use the current column."
1172 (setq column
(or column
(org-table-current-column)))
1174 (and (or (not line
) (org-table-goto-line line
))
1175 (org-trim (org-table-get-field column
)))))
1177 (defun org-table-put (line column value
&optional align
)
1178 "Put VALUE into line LINE, column COLUMN.
1179 When ALIGN is set, also realign the table."
1180 (setq column
(or column
(org-table-current-column)))
1181 (prog1 (save-excursion
1182 (and (or (not line
) (org-table-goto-line line
))
1183 (progn (org-table-goto-column column nil
'force
) t
)
1184 (org-table-get-field column value
)))
1185 (and align
(org-table-align))))
1187 (defun org-table-current-line ()
1188 "Return the index of the current data line."
1189 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1191 (goto-char (org-table-begin))
1192 (while (and (re-search-forward org-table-dataline-regexp end t
)
1194 (< (point-at-eol) pos
))))
1197 (defun org-table-goto-line (N)
1198 "Go to the Nth data line in the current table.
1199 Return t when the line exists, nil if it does not exist."
1200 (goto-char (org-table-begin))
1201 (let ((end (org-table-end)) (cnt 0))
1202 (while (and (re-search-forward org-table-dataline-regexp end t
)
1203 (< (setq cnt
(1+ cnt
)) N
)))
1207 (defun org-table-blank-field ()
1208 "Blank the current table field or active region."
1210 (org-table-check-inside-data-field)
1211 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1212 (let (org-table-clip)
1213 (org-table-cut-region (region-beginning) (region-end)))
1214 (skip-chars-backward "^|")
1216 (if (looking-at "|[^|\n]+")
1217 (let* ((pos (match-beginning 0))
1218 (match (match-string 0))
1219 (len (org-string-width match
)))
1220 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1221 (goto-char (+ 2 pos
))
1222 (substring match
1)))))
1224 (defun org-table-get-field (&optional n replace
)
1225 "Return the value of the field in column N of current row.
1226 N defaults to current field.
1227 If REPLACE is a string, replace field with this value. The return value
1228 is always the old value."
1229 (and n
(org-table-goto-column n
))
1230 (skip-chars-backward "^|\n")
1232 (if (looking-at "|[^|\r\n]*")
1233 (let* ((pos (match-beginning 0))
1234 (val (buffer-substring (1+ pos
) (match-end 0))))
1236 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1238 (goto-char (min (point-at-eol) (+ 2 pos
)))
1240 (forward-char 1) ""))
1243 (defun org-table-field-info (arg)
1244 "Show info about the current field, and highlight any reference at point."
1246 (unless (org-at-table-p) (user-error "Not at a table"))
1247 (org-table-get-specials)
1249 (let* ((pos (point))
1250 (col (org-table-current-column))
1251 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1252 (name (car (rassoc (list (org-current-line) col
)
1253 org-table-named-field-locations
)))
1254 (eql (org-table-expand-lhs-ranges
1257 (cons (org-table-formula-handle-first/last-rc
1259 (org-table-get-stored-formulas))))
1260 (dline (org-table-current-dline))
1261 (ref (format "@%d$%d" dline col
))
1262 (ref1 (org-table-convert-refs-to-an ref
))
1263 (fequation (or (assoc name eql
) (assoc ref eql
)))
1264 (cequation (assoc (int-to-string col
) eql
))
1265 (eqn (or fequation cequation
)))
1266 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1267 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1270 (org-table-show-reference 'local
)
1272 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1274 (if cname
(concat " or $" cname
) "")
1276 (if name
(concat " or $" name
) "")
1277 ;; FIXME: formula info not correct if special table line
1279 (concat ", formula: "
1280 (org-table-formula-to-user
1282 (if (string-match "^[$@]"(car eqn
)) "" "$")
1283 (car eqn
) "=" (cdr eqn
))))
1286 (defun org-table-current-column ()
1287 "Find out which column we are in."
1289 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1291 (let ((cnt 0) (pos (point)))
1292 (beginning-of-line 1)
1293 (while (search-forward "|" pos t
)
1294 (setq cnt
(1+ cnt
)))
1295 (when (org-called-interactively-p 'interactive
)
1296 (message "In table column %d" cnt
))
1300 (defun org-table-current-dline ()
1301 "Find out what table data line we are in.
1302 Only data lines count for this."
1304 (when (org-called-interactively-p 'any
)
1305 (org-table-check-inside-data-field))
1307 (let ((cnt 0) (pos (point)))
1308 (goto-char (org-table-begin))
1309 (while (<= (point) pos
)
1310 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1311 (beginning-of-line 2))
1312 (when (org-called-interactively-p 'any
)
1313 (message "This is table line %d" cnt
))
1317 (defun org-table-goto-column (n &optional on-delim force
)
1318 "Move the cursor to the Nth column in the current table line.
1319 With optional argument ON-DELIM, stop with point before the left delimiter
1321 If there are less than N fields, just go to after the last delimiter.
1322 However, when FORCE is non-nil, create new columns if necessary."
1324 (beginning-of-line 1)
1326 (while (and (> (setq n
(1- n
)) -
1)
1327 (or (search-forward "|" (point-at-eol) t
)
1329 (progn (end-of-line 1)
1330 (skip-chars-backward "^|")
1333 (when (and force
(not (looking-at ".*|")))
1334 (save-excursion (end-of-line 1) (insert " | ")))
1337 (if (looking-at " ") (forward-char 1)))))
1340 (defun org-table-insert-column ()
1341 "Insert a new column into the table."
1343 (if (not (org-at-table-p))
1344 (user-error "Not at a table"))
1345 (org-table-find-dataline)
1346 (let* ((col (max 1 (org-table-current-column)))
1347 (beg (org-table-begin))
1348 (end (copy-marker (org-table-end)))
1349 ;; Current cursor position
1350 (linepos (org-current-line))
1353 (while (< (point) end
)
1354 (if (org-at-table-hline-p)
1356 (org-table-goto-column col t
)
1358 (beginning-of-line 2))
1359 (move-marker end nil
)
1360 (org-goto-line linepos
)
1361 (org-table-goto-column colpos
)
1363 (when (or (not org-table-fix-formulas-confirm
)
1364 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1365 (org-table-fix-formulas "$" nil
(1- col
) 1)
1366 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1368 (defun org-table-find-dataline ()
1369 "Find a data line in the current table, which is needed for column commands."
1370 (if (and (org-at-table-p)
1371 (not (org-at-table-hline-p)))
1373 (let ((col (current-column))
1374 (end (org-table-end)))
1375 (org-move-to-column col
)
1376 (while (and (< (point) end
)
1377 (or (not (= (current-column) col
))
1378 (org-at-table-hline-p)))
1379 (beginning-of-line 2)
1380 (org-move-to-column col
))
1381 (if (and (org-at-table-p)
1382 (not (org-at-table-hline-p)))
1385 "Please position cursor in a data line for column operations")))))
1387 (defun org-table-line-to-dline (line &optional above
)
1388 "Turn a buffer line number into a data line number.
1389 If there is no data line in this line, return nil.
1390 If there is no matching dline (most likely te reference was a hline), the
1391 first dline below it is used. When ABOVE is non-nil, the one above is used."
1393 (let ((ll (length org-table-dlines
))
1399 (if (<= (aref org-table-dlines i
) line
)
1404 (if (>= (aref org-table-dlines i
) line
)
1410 (defun org-table-delete-column ()
1411 "Delete a column from the table."
1413 (if (not (org-at-table-p))
1414 (user-error "Not at a table"))
1415 (org-table-find-dataline)
1416 (org-table-check-inside-data-field)
1417 (let* ((col (org-table-current-column))
1418 (beg (org-table-begin))
1419 (end (copy-marker (org-table-end)))
1420 ;; Current cursor position
1421 (linepos (org-current-line))
1424 (while (< (point) end
)
1425 (if (org-at-table-hline-p)
1427 (org-table-goto-column col t
)
1428 (and (looking-at "|[^|\n]+|")
1429 (replace-match "|")))
1430 (beginning-of-line 2))
1431 (move-marker end nil
)
1432 (org-goto-line linepos
)
1433 (org-table-goto-column colpos
)
1435 (when (or (not org-table-fix-formulas-confirm
)
1436 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1437 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1439 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1443 (defun org-table-move-column-right ()
1444 "Move column to the right."
1446 (org-table-move-column nil
))
1448 (defun org-table-move-column-left ()
1449 "Move column to the left."
1451 (org-table-move-column 'left
))
1454 (defun org-table-move-column (&optional left
)
1455 "Move the current column to the right. With arg LEFT, move to the left."
1457 (if (not (org-at-table-p))
1458 (user-error "Not at a table"))
1459 (org-table-find-dataline)
1460 (org-table-check-inside-data-field)
1461 (let* ((col (org-table-current-column))
1462 (col1 (if left
(1- col
) col
))
1463 (beg (org-table-begin))
1464 (end (copy-marker (org-table-end)))
1465 ;; Current cursor position
1466 (linepos (org-current-line))
1467 (colpos (if left
(1- col
) (1+ col
))))
1468 (if (and left
(= col
1))
1469 (user-error "Cannot move column further left"))
1470 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1471 (user-error "Cannot move column further right"))
1473 (while (< (point) end
)
1474 (if (org-at-table-hline-p)
1476 (org-table-goto-column col1 t
)
1477 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1478 (replace-match "|\\2|\\1|")))
1479 (beginning-of-line 2))
1480 (move-marker end nil
)
1481 (org-goto-line linepos
)
1482 (org-table-goto-column colpos
)
1484 (when (or (not org-table-fix-formulas-confirm
)
1485 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1486 (org-table-fix-formulas
1487 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1488 (cons (number-to-string colpos
) (number-to-string col
))))
1489 (org-table-fix-formulas
1490 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1491 (cons (number-to-string colpos
) (number-to-string col
)))))))
1494 (defun org-table-move-row-down ()
1495 "Move table row down."
1497 (org-table-move-row nil
))
1499 (defun org-table-move-row-up ()
1500 "Move table row up."
1502 (org-table-move-row 'up
))
1505 (defun org-table-move-row (&optional up
)
1506 "Move the current table line down. With arg UP, move it up."
1508 (let* ((col (current-column))
1510 (hline1p (save-excursion (beginning-of-line 1)
1511 (looking-at org-table-hline-regexp
)))
1512 (dline1 (org-table-current-dline))
1513 (dline2 (+ dline1
(if up -
1 1)))
1516 (beginning-of-line tonew
)
1517 (unless (org-at-table-p)
1519 (user-error "Cannot move row further"))
1520 (setq hline2p
(looking-at org-table-hline-regexp
))
1522 (beginning-of-line 1)
1524 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1525 (delete-region (point) (1+ (point-at-eol)))
1526 (beginning-of-line tonew
)
1528 (beginning-of-line 0)
1529 (org-move-to-column col
)
1530 (unless (or hline1p hline2p
1531 (not (or (not org-table-fix-formulas-confirm
)
1532 (funcall org-table-fix-formulas-confirm
1533 "Fix formulas? "))))
1534 (org-table-fix-formulas
1535 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1536 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1539 (defun org-table-insert-row (&optional arg
)
1540 "Insert a new row above the current line into the table.
1541 With prefix ARG, insert below the current line."
1543 (if (not (org-at-table-p))
1544 (user-error "Not at a table"))
1545 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1546 (new (org-table-clean-line line
)))
1547 ;; Fix the first field if necessary
1548 (if (string-match "^[ \t]*| *[#$] *|" line
)
1549 (setq new
(replace-match (match-string 0 line
) t t new
)))
1550 (beginning-of-line (if arg
2 1))
1551 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1552 (beginning-of-line 0)
1553 (re-search-forward "| ?" (point-at-eol) t
)
1554 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1556 (when (or (not org-table-fix-formulas-confirm
)
1557 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1558 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1561 (defun org-table-insert-hline (&optional above
)
1562 "Insert a horizontal-line below the current line into the table.
1563 With prefix ABOVE, insert above the current line."
1565 (if (not (org-at-table-p))
1566 (user-error "Not at a table"))
1567 (when (eobp) (insert "\n") (backward-char 1))
1568 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1570 (let ((line (org-table-clean-line
1571 (buffer-substring (point-at-bol) (point-at-eol))))
1572 (col (current-column)))
1573 (while (string-match "|\\( +\\)|" line
)
1574 (setq line
(replace-match
1575 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1576 ?-
) "|") t t line
)))
1577 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1578 (beginning-of-line (if above
1 2))
1580 (beginning-of-line (if above
1 -
1))
1581 (org-move-to-column col
)
1582 (and org-table-overlay-coordinates
(org-table-align))))
1585 (defun org-table-hline-and-move (&optional same-column
)
1586 "Insert a hline and move to the row below that line."
1588 (let ((col (org-table-current-column)))
1589 (org-table-maybe-eval-formula)
1590 (org-table-maybe-recalculate-line)
1591 (org-table-insert-hline)
1593 (if (looking-at "\n[ \t]*|-")
1594 (progn (insert "\n|") (org-table-align))
1595 (org-table-next-field))
1596 (if same-column
(org-table-goto-column col
))))
1598 (defun org-table-clean-line (s)
1599 "Convert a table line S into a string with only \"|\" and space.
1600 In particular, this does handle wide and invisible characters."
1601 (if (string-match "^[ \t]*|-" s
)
1602 ;; It's a hline, just map the characters
1603 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1604 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1605 (setq s
(replace-match
1606 (concat "|" (make-string (org-string-width (match-string 1 s
))
1612 (defun org-table-kill-row ()
1613 "Delete the current row or horizontal line from the table."
1615 (if (not (org-at-table-p))
1616 (user-error "Not at a table"))
1617 (let ((col (current-column))
1618 (dline (org-table-current-dline)))
1619 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1620 (if (not (org-at-table-p)) (beginning-of-line 0))
1621 (org-move-to-column col
)
1622 (when (or (not org-table-fix-formulas-confirm
)
1623 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1624 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1628 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func
)
1629 "Sort table lines according to the column at point.
1631 The position of point indicates the column to be used for
1632 sorting, and the range of lines is the range between the nearest
1633 horizontal separator lines, or the entire table of no such lines
1634 exist. If point is before the first column, you will be prompted
1635 for the sorting column. If there is an active region, the mark
1636 specifies the first line and the sorting column, while point
1637 should be in the last line to be included into the sorting.
1639 The command then prompts for the sorting type which can be
1640 alphabetically, numerically, or by time (as given in a time stamp
1641 in the field, or as a HH:MM value). Sorting in reverse order is
1644 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1646 If SORTING-TYPE is specified when this function is called from a Lisp
1647 program, no prompting will take place. SORTING-TYPE must be a character,
1648 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1649 sorting should be done in reverse order.
1651 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1652 a function to be called to extract the key. It must return either
1653 a string or a number that should serve as the sorting key for that
1654 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1655 is specified interactively, the comparison will be either a string or
1656 numeric compare based on the type of the first key in the table."
1658 (let* ((thisline (org-current-line))
1659 (thiscol (org-table-current-column))
1660 (otc org-table-overlay-coordinates
)
1661 beg end bcol ecol tend tbeg column lns pos
)
1662 (when (equal thiscol
0)
1663 (if (org-called-interactively-p 'any
)
1666 (read-string "Use column N for sorting: ")))
1668 (org-table-goto-column thiscol
))
1669 (org-table-check-inside-data-field)
1670 (if (org-region-active-p)
1672 (setq beg
(region-beginning) end
(region-end))
1674 (setq column
(org-table-current-column)
1677 (setq end
(point-at-bol 2)))
1678 (setq column
(org-table-current-column)
1680 tbeg
(org-table-begin)
1681 tend
(org-table-end))
1682 (if (re-search-backward org-table-hline-regexp tbeg t
)
1683 (setq beg
(point-at-bol 2))
1685 (setq beg
(point-at-bol 1)))
1687 (if (re-search-forward org-table-hline-regexp tend t
)
1688 (setq end
(point-at-bol 1))
1690 (setq end
(point-at-bol))))
1691 (setq beg
(move-marker (make-marker) beg
)
1692 end
(move-marker (make-marker) end
))
1695 (org-table-goto-column column
)
1696 (skip-chars-backward "^|")
1697 (setq bcol
(current-column))
1698 (org-table-goto-column (1+ column
))
1699 (skip-chars-backward "^|")
1700 (setq ecol
(1- (current-column)))
1701 (org-table-goto-column column
)
1702 (setq lns
(mapcar (lambda(x) (cons
1703 (org-sort-remove-invisible
1705 (org-split-string x
"[ \t]*|[ \t]*")))
1707 (org-split-string (buffer-substring beg end
) "\n")))
1708 (setq lns
(org-table--do-sort
1709 lns
"Table" with-case sorting-type getkey-func compare-func
))
1710 (when org-table-overlay-coordinates
1711 (org-table-toggle-coordinate-overlays))
1712 (delete-region beg end
)
1713 (move-marker beg nil
)
1714 (move-marker end nil
)
1715 (insert (mapconcat 'cdr lns
"\n") "\n")
1716 (org-goto-line thisline
)
1717 (org-table-goto-column thiscol
)
1718 (when otc
(org-table-toggle-coordinate-overlays))
1719 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1721 (defun org-table--do-sort (table what
&optional with-case sorting-type getkey-func compare-func
)
1722 "Sort TABLE of WHAT according to SORTING-TYPE.
1723 The user will be prompted for the SORTING-TYPE if the call to this
1724 function does not specify it.
1725 WHAT is only for the prompt, to indicate what is being sorted.
1726 The sorting key will be extracted from the car of the elements of
1727 the table. If WITH-CASE is non-nil, the sorting will be case-sensitive.
1729 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1730 a function to be called to extract the key. It must return either
1731 a string or a number that should serve as the sorting key for that
1732 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1733 is specified interactively, the comparison will be either a string or
1734 numeric compare based on the type of the first key in the table."
1735 (unless sorting-type
1737 "Sort %s: [a]lphabetic, [n]umeric, [t]ime, [f]unc. A/N/T/F means reversed:"
1739 (setq sorting-type
(read-char-exclusive)))
1740 (let (extractfun comparefun tempfun
)
1741 ;; Define the appropriate functions
1744 (setq extractfun
#'string-to-number
1745 comparefun
(if (= sorting-type ?n
) #'< #'>)))
1747 (setq extractfun
(if with-case
(lambda(x) (org-sort-remove-invisible x
))
1748 (lambda(x) (downcase (org-sort-remove-invisible x
))))
1749 comparefun
(if (= sorting-type ?a
) #'string
< #'org-string
>)))
1753 (cond ((or (string-match org-ts-regexp x
)
1754 (string-match org-ts-regexp-both x
))
1756 (org-time-string-to-time (match-string 0 x
))))
1757 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x
)
1758 (org-hh:mm-string-to-minutes x
))
1760 comparefun
(if (= sorting-type ?t
) #'< #'>)))
1762 (setq tempfun
(or getkey-func
1763 (intern (org-icompleting-read
1764 "Sort using function: "
1765 obarray
#'fboundp t nil nil
))))
1766 (let ((extract-string-p (stringp (funcall tempfun
(caar table
)))))
1767 (setq extractfun
(if (and extract-string-p
(not with-case
))
1768 (lambda (x) (downcase (funcall tempfun x
)))
1770 (setq comparefun
(cond (compare-func
1771 (if (= sorting-type ?f
) compare-func
1772 (lambda (a b
) (funcall compare-func b a
))))
1774 (if (= sorting-type ?f
) #'string
<
1776 (t (if (= sorting-type ?f
) #'< #'>))))))
1777 (t (error "Invalid sorting type `%c'" sorting-type
)))
1779 (sort (mapcar (lambda (x) (cons (funcall extractfun
(car x
)) (cdr x
)))
1781 (lambda (a b
) (funcall comparefun
(car a
) (car b
))))))
1784 (defun org-table-cut-region (beg end
)
1785 "Copy region in table to the clipboard and blank all relevant fields.
1786 If there is no active region, use just the field at point."
1788 (if (org-region-active-p) (region-beginning) (point))
1789 (if (org-region-active-p) (region-end) (point))))
1790 (org-table-copy-region beg end
'cut
))
1793 (defun org-table-copy-region (beg end
&optional cut
)
1794 "Copy rectangular region in table to clipboard.
1795 A special clipboard is used which can only be accessed
1796 with `org-table-paste-rectangle'."
1798 (if (org-region-active-p) (region-beginning) (point))
1799 (if (org-region-active-p) (region-end) (point))
1800 current-prefix-arg
))
1801 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1803 (rpl (if cut
" " nil
)))
1805 (org-table-check-inside-data-field)
1806 (setq l01
(org-current-line)
1807 c01
(org-table-current-column))
1809 (org-table-check-inside-data-field)
1810 (setq l02
(org-current-line)
1811 c02
(org-table-current-column))
1812 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1813 c1
(min c01 c02
) c2
(max c01 c02
))
1817 (if (> l1 l2
) (throw 'exit t
))
1819 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1820 (setq cols nil ic1 c1 ic2 c2
)
1821 (while (< ic1
(1+ ic2
))
1822 (push (org-table-get-field ic1 rpl
) cols
)
1823 (setq ic1
(1+ ic1
)))
1824 (push (nreverse cols
) region
)
1825 (setq l1
(1+ l1
)))))
1826 (setq org-table-clip
(nreverse region
))
1827 (if cut
(org-table-align))
1831 (defun org-table-paste-rectangle ()
1832 "Paste a rectangular region into a table.
1833 The upper right corner ends up in the current field. All involved fields
1834 will be overwritten. If the rectangle does not fit into the present table,
1835 the table is enlarged as needed. The process ignores horizontal separator
1838 (unless (and org-table-clip
(listp org-table-clip
))
1839 (user-error "First cut/copy a region to paste!"))
1840 (org-table-check-inside-data-field)
1841 (let* ((clip org-table-clip
)
1842 (line (org-current-line))
1843 (col (org-table-current-column))
1844 (org-enable-table-editor t
)
1845 (org-table-automatic-realign nil
)
1847 (while (setq cols
(pop clip
))
1848 (while (org-at-table-hline-p) (beginning-of-line 2))
1849 (if (not (org-at-table-p))
1850 (progn (end-of-line 0) (org-table-next-field)))
1852 (while (setq field
(pop cols
))
1853 (org-table-goto-column c nil
'force
)
1854 (org-table-get-field nil field
)
1856 (beginning-of-line 2))
1857 (org-goto-line line
)
1858 (org-table-goto-column col
)
1862 (defun org-table-convert ()
1863 "Convert from `org-mode' table to table.el and back.
1864 Obviously, this only works within limits. When an Org-mode table is
1865 converted to table.el, all horizontal separator lines get lost, because
1866 table.el uses these as cell boundaries and has no notion of horizontal lines.
1867 A table.el table can be converted to an Org-mode table only if it does not
1868 do row or column spanning. Multiline cells will become multiple cells.
1869 Beware, Org-mode does not test if the table can be successfully converted - it
1870 blindly applies a recipe that works for simple tables."
1873 (if (org-at-table.el-p
)
1874 ;; convert to Org-mode table
1875 (let ((beg (copy-marker (org-table-begin t
)))
1876 (end (copy-marker (org-table-end t
))))
1877 (table-unrecognize-region beg end
)
1879 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1882 (if (org-at-table-p)
1883 ;; convert to table.el table
1884 (let ((beg (copy-marker (org-table-begin)))
1885 (end (copy-marker (org-table-end))))
1886 ;; first, get rid of all horizontal lines
1888 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1890 ;; insert a hline before first
1892 (org-table-insert-hline 'above
)
1893 (beginning-of-line -
1)
1894 ;; insert a hline after each line
1895 (while (progn (beginning-of-line 3) (< (point) end
))
1896 (org-table-insert-hline))
1898 (setq end
(move-marker end
(org-table-end)))
1899 ;; replace "+" at beginning and ending of hlines
1900 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1901 (replace-match "\\1+-"))
1903 (while (re-search-forward "-|[ \t]*$" end t
)
1904 (replace-match "-+"))
1907 (defun org-table-transpose-table-at-point ()
1908 "Transpose Org table at point and eliminate hlines.
1916 will be transposed as
1923 Note that horizontal lines disappear."
1925 (let* ((table (delete 'hline
(org-table-to-lisp)))
1926 (dline_old (org-table-current-line))
1927 (col_old (org-table-current-column))
1928 (contents (mapcar (lambda (p)
1934 (setq tp
(cdr tp
))))
1937 (goto-char (org-table-begin))
1938 (re-search-forward "|")
1940 (delete-region (point) (org-table-end))
1943 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1945 (org-table-goto-line col_old
)
1946 (org-table-goto-column dline_old
))
1950 (defun org-table-wrap-region (arg)
1951 "Wrap several fields in a column like a paragraph.
1952 This is useful if you'd like to spread the contents of a field over several
1953 lines, in order to keep the table compact.
1955 If there is an active region, and both point and mark are in the same column,
1956 the text in the column is wrapped to minimum width for the given number of
1957 lines. Generally, this makes the table more compact. A prefix ARG may be
1958 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1959 formats the selected text to two lines. If the region was longer than two
1960 lines, the remaining lines remain empty. A negative prefix argument reduces
1961 the current number of lines by that amount. The wrapped text is pasted back
1962 into the table. If you formatted it to more lines than it was before, fields
1963 further down in the table get overwritten - so you might need to make space in
1966 If there is no region, the current field is split at the cursor position and
1967 the text fragment to the right of the cursor is prepended to the field one
1970 If there is no region, but you specify a prefix ARG, the current field gets
1971 blank, and the content is appended to the field above."
1973 (org-table-check-inside-data-field)
1974 (if (org-region-active-p)
1975 ;; There is a region: fill as a paragraph
1976 (let* ((beg (region-beginning))
1977 (cline (save-excursion (goto-char beg
) (org-current-line)))
1978 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1980 (org-table-cut-region (region-beginning) (region-end))
1981 (if (> (length (car org-table-clip
)) 1)
1982 (user-error "Region must be limited to single column"))
1983 (setq nlines
(if arg
1985 (+ (length org-table-clip
) arg
)
1987 (length org-table-clip
)))
1988 (setq org-table-clip
1989 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1991 (org-goto-line cline
)
1992 (org-table-goto-column ccol
)
1993 (org-table-paste-rectangle))
1994 ;; No region, split the current field at point
1995 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1996 (skip-chars-forward "^\r\n|"))
1998 ;; combine with field above
1999 (let ((s (org-table-blank-field))
2000 (col (org-table-current-column)))
2001 (beginning-of-line 0)
2002 (while (org-at-table-hline-p) (beginning-of-line 0))
2003 (org-table-goto-column col
)
2004 (skip-chars-forward "^|")
2005 (skip-chars-backward " ")
2006 (insert " " (org-trim s
))
2009 (if (looking-at "\\([^|]+\\)+|")
2010 (let ((s (match-string 1)))
2011 (replace-match " |")
2012 (goto-char (match-beginning 0))
2013 (org-table-next-row)
2014 (insert (org-trim s
) " ")
2016 (org-table-next-row)))))
2018 (defvar org-field-marker nil
)
2021 (defun org-table-edit-field (arg)
2022 "Edit table field in a different window.
2023 This is mainly useful for fields that contain hidden parts.
2024 When called with a \\[universal-argument] prefix, just make the full field visible so that
2025 it can be edited in place."
2029 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2031 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2032 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2033 (remove-text-properties b e
'(org-cwidth t invisible t
2034 display t intangible t
))
2035 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2036 (font-lock-fontify-block))))
2038 (let ((pos (point-marker))
2040 (if (eq org-table-use-standard-references t
)
2041 (concat (org-number-to-letters (org-table-current-column))
2042 (int-to-string (org-table-current-dline)))
2043 (concat "@" (int-to-string (org-table-current-dline))
2044 "$" (int-to-string (org-table-current-column)))))
2045 (field (org-table-get-field))
2046 (cw (current-window-configuration))
2049 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2050 (when (and (local-variable-p 'org-field-marker
)
2051 (markerp org-field-marker
))
2052 (move-marker org-field-marker nil
))
2054 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2055 (let ((org-inhibit-startup t
)) (org-mode))
2057 (setq truncate-lines nil
)
2059 (goto-char (setq p
(point-max)))
2060 (insert (org-trim field
))
2061 (remove-text-properties p
(point-max)
2062 '(invisible t org-cwidth t display t
2065 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
2066 (org-set-local 'org-window-configuration cw
)
2067 (org-set-local 'org-field-marker pos
)
2068 (message "Edit and finish with C-c C-c")))))
2070 (defun org-table-finish-edit-field ()
2071 "Finish editing a table data field.
2072 Remove all newline characters, insert the result into the table, realign
2073 the table and kill the editing buffer."
2074 (let ((pos org-field-marker
)
2075 (cw org-window-configuration
)
2076 (cb (current-buffer))
2078 (goto-char (point-min))
2079 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2080 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2081 (replace-match " "))
2082 (setq text
(org-trim (buffer-string)))
2083 (set-window-configuration cw
)
2085 (select-window (get-buffer-window (marker-buffer pos
)))
2087 (move-marker pos nil
)
2088 (org-table-check-inside-data-field)
2089 (org-table-get-field nil text
)
2091 (message "New field value inserted")))
2093 (define-minor-mode org-table-follow-field-mode
2094 "Minor mode to make the table field editor window follow the cursor.
2095 When this mode is active, the field editor window will always show the
2096 current field. The mode exits automatically when the cursor leaves the
2097 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2098 nil
" TblFollow" nil
2099 (if org-table-follow-field-mode
2100 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2102 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2103 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2104 (win (and buf
(get-buffer-window buf
))))
2105 (when win
(delete-window win
))
2107 (with-current-buffer buf
2108 (move-marker org-field-marker nil
))
2109 (kill-buffer buf
)))))
2111 (defun org-table-follow-fields-with-editor ()
2112 (if (and org-table-exit-follow-field-mode-when-leaving-table
2113 (not (org-at-table-p)))
2114 ;; We have left the table, exit the follow mode
2115 (org-table-follow-field-mode -
1)
2116 (when (org-table-check-inside-data-field 'noerror
)
2117 (let ((win (selected-window)))
2118 (org-table-edit-field nil
)
2119 (org-fit-window-to-buffer)
2120 (select-window win
)))))
2122 (defvar org-timecnt
) ; dynamically scoped parameter
2125 (defun org-table-sum (&optional beg end nlast
)
2126 "Sum numbers in region of current table column.
2127 The result will be displayed in the echo area, and will be available
2128 as kill to be inserted with \\[yank].
2130 If there is an active region, it is interpreted as a rectangle and all
2131 numbers in that rectangle will be summed. If there is no active
2132 region and point is located in a table column, sum all numbers in that
2135 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2136 numbers are assumed to be times as well (in decimal hours) and the
2137 numbers are added as such.
2139 If NLAST is a number, only the NLAST fields will actually be summed."
2142 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2144 ((and beg end
)) ; beg and end given explicitly
2145 ((org-region-active-p)
2146 (setq beg
(region-beginning) end
(region-end)))
2148 (setq col
(org-table-current-column))
2149 (goto-char (org-table-begin))
2150 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2151 (user-error "No table data"))
2152 (org-table-goto-column col
)
2154 (goto-char (org-table-end))
2155 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2156 (user-error "No table data"))
2157 (org-table-goto-column col
)
2158 (setq end
(point))))
2159 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2160 (items1 (cond ((not nlast
) items
)
2161 ((>= nlast
(length items
)) items
)
2162 (t (setq items
(reverse items
))
2163 (setcdr (nthcdr (1- nlast
) items
) nil
)
2165 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2167 (res (apply '+ numbers
))
2168 (sres (if (= org-timecnt
0)
2169 (number-to-string res
)
2170 (setq diff
(* 3600 res
)
2171 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2172 m
(floor (/ diff
60)) diff
(mod diff
60)
2174 (format "%.0f:%02.0f:%02.0f" h m s
))))
2176 (if (org-called-interactively-p 'interactive
)
2178 (substitute-command-keys
2179 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2180 (length numbers
) sres
))))
2183 (defun org-table-get-number-for-summing (s)
2185 (if (string-match "^ *|? *" s
)
2186 (setq s
(replace-match "" nil nil s
)))
2187 (if (string-match " *|? *$" s
)
2188 (setq s
(replace-match "" nil nil s
)))
2189 (setq n
(string-to-number s
))
2191 ((and (string-match "0" s
)
2192 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2193 ((string-match "\\`[ \t]+\\'" s
) nil
)
2194 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2195 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2196 (m (string-to-number (or (match-string 2 s
) "0")))
2197 (s (string-to-number (or (match-string 4 s
) "0"))))
2198 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2199 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2203 (defun org-table-current-field-formula (&optional key noerror
)
2204 "Return the formula active for the current field.
2205 Assumes that specials are in place.
2206 If KEY is given, return the key to this formula.
2207 Otherwise return the formula preceded with \"=\" or \":=\"."
2208 (let* ((name (car (rassoc (list (org-current-line)
2209 (org-table-current-column))
2210 org-table-named-field-locations
)))
2211 (col (org-table-current-column))
2212 (scol (int-to-string col
))
2213 (ref (format "@%d$%d" (org-table-current-dline) col
))
2214 (stored-list (org-table-get-stored-formulas noerror
))
2215 (ass (or (assoc name stored-list
)
2216 (assoc ref stored-list
)
2217 (assoc scol stored-list
))))
2220 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2223 (defun org-table-get-formula (&optional equation named
)
2224 "Read a formula from the minibuffer, offer stored formula as default.
2225 When NAMED is non-nil, look for a named equation."
2226 (let* ((stored-list (org-table-get-stored-formulas))
2227 (name (car (rassoc (list (org-current-line)
2228 (org-table-current-column))
2229 org-table-named-field-locations
)))
2230 (ref (format "@%d$%d" (org-table-current-dline)
2231 (org-table-current-column)))
2232 (refass (assoc ref stored-list
))
2233 (nameass (assoc name stored-list
))
2235 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2238 (int-to-string (org-table-current-column))))
2239 (dummy (and (or nameass refass
) (not named
)
2240 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2241 (message "Formula not replaced")))
2242 (name (or name ref
))
2243 (org-table-may-need-update nil
)
2244 (stored (cdr (assoc scol stored-list
)))
2246 ((and stored equation
(string-match "^ *=? *$" equation
))
2250 (t (org-table-formula-from-user
2252 (org-table-formula-to-user
2253 (format "%s formula %s%s="
2254 (if named
"Field" "Column")
2255 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2257 (if stored
(org-table-formula-to-user stored
) "")
2258 'org-table-formula-history
2261 (when (not (string-match "\\S-" eq
))
2263 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2264 (org-table-store-formulas stored-list
)
2265 (user-error "Formula removed"))
2266 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2267 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2268 (if (and name
(not named
))
2269 ;; We set the column equation, delete the named one.
2270 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2273 (setcdr (assoc scol stored-list
) eq
)
2274 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2275 (if (or mustsave
(not (equal stored eq
)))
2276 (org-table-store-formulas stored-list
))
2279 (defun org-table-store-formulas (alist)
2280 "Store the list of formulas below the current table."
2281 (setq alist
(sort alist
'org-table-formula-less-p
))
2282 (let ((case-fold-search t
))
2284 (goto-char (org-table-end))
2285 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2287 ;; don't overwrite TBLFM, we might use text properties to store stuff
2288 (goto-char (match-beginning 3))
2289 (delete-region (match-beginning 3) (match-end 0)))
2291 (insert (or (match-string 2) "#+TBLFM:")))
2293 (mapconcat (lambda (x)
2295 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2296 (car x
) "=" (cdr x
)))
2300 (defsubst org-table-formula-make-cmp-string
(a)
2301 (when (string-match "\\`$[<>]" a
)
2302 (let ((arrow (string-to-char (substring a
1))))
2303 ;; Fake a high number to make sure this is sorted at the end.
2304 (setq a
(org-table-formula-handle-first/last-rc a
))
2305 (setq a
(format "$%d" (+ 10000
2306 (if (= arrow ?
<) -
1000 0)
2307 (string-to-number (substring a
1)))))))
2309 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2313 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2315 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2317 (concat "@@" (match-string 5 a
))))))
2319 (defun org-table-formula-less-p (a b
)
2320 "Compare two formulas for sorting."
2321 (let ((as (org-table-formula-make-cmp-string (car a
)))
2322 (bs (org-table-formula-make-cmp-string (car b
))))
2323 (and as bs
(string< as bs
))))
2326 (defun org-table-get-stored-formulas (&optional noerror
)
2327 "Return an alist with the stored formulas directly after current table."
2328 (interactive) ;; FIXME interactive?
2329 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2331 (goto-char (org-table-end))
2332 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2333 (setq strings
(org-split-string (org-match-string-no-properties 2)
2335 (while (setq string
(pop strings
))
2336 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2337 (setq scol
(if (match-end 2)
2338 (match-string 2 string
)
2339 (match-string 1 string
))
2340 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2341 (concat "$" scol
) scol
)
2342 eq
(match-string 3 string
)
2343 eq-alist
(cons (cons scol eq
) eq-alist
))
2344 (if (member scol seen
)
2347 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2350 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2351 (push scol seen
))))))
2352 (nreverse eq-alist
)))
2354 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2355 "Modify the equations after the table structure has been edited.
2356 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2357 For all numbers larger than LIMIT, shift them by DELTA."
2359 (goto-char (org-table-end))
2360 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2361 (let ((msg "The formulas in #+TBLFM have been updated")
2362 (re (concat key
"\\([0-9]+\\)"))
2365 (if (or (equal key
"$") (equal key
"$LR"))
2366 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2367 (regexp-quote key
) remove
)
2368 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2371 (while (re-search-forward re2
(point-at-eol) t
)
2372 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2373 (if (equal (char-before (match-beginning 0)) ?.
)
2375 "Change makes TBLFM term %s invalid, use undo to recover"
2377 (replace-match "")))))
2378 (while (re-search-forward re
(point-at-eol) t
)
2379 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2380 (setq s
(match-string 1) n
(string-to-number s
))
2382 ((setq a
(assoc s replace
))
2383 (replace-match (concat key
(cdr a
)) t t
)
2385 ((and limit
(> n limit
))
2386 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2390 (defun org-table-get-specials ()
2391 "Get the column names and local parameters for this table."
2393 (let ((beg (org-table-begin)) (end (org-table-end))
2394 names name fields fields1 field cnt
2395 c v l line col types dlines hlines last-dline
)
2396 (setq org-table-column-names nil
2397 org-table-local-parameters nil
2398 org-table-named-field-locations nil
2399 org-table-current-begin-line nil
2400 org-table-current-begin-pos nil
2401 org-table-current-line-types nil
2402 org-table-current-ncol
0)
2404 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2405 (setq names
(org-split-string (match-string 1) " *| *")
2407 (while (setq name
(pop names
))
2409 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2410 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2411 (setq org-table-column-names
(nreverse org-table-column-names
))
2412 (setq org-table-column-name-regexp
2413 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2415 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2416 (setq fields
(org-split-string (match-string 1) " *| *"))
2417 (while (setq field
(pop fields
))
2418 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2419 (push (cons (match-string 1 field
) (match-string 2 field
))
2420 org-table-local-parameters
))))
2422 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2423 (setq c
(match-string 1)
2424 fields
(org-split-string (match-string 2) " *| *"))
2426 (beginning-of-line (if (equal c
"_") 2 0))
2427 (setq line
(org-current-line) col
1)
2428 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2429 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2430 (while (and fields1
(setq field
(pop fields
)))
2431 (setq v
(pop fields1
) col
(1+ col
))
2432 (when (and (stringp field
) (stringp v
)
2433 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2434 (push (cons field v
) org-table-local-parameters
)
2435 (push (list field line col
) org-table-named-field-locations
))))
2436 ;; Analyse the line types
2438 (setq org-table-current-begin-line
(org-current-line)
2439 org-table-current-begin-pos
(point)
2440 l org-table-current-begin-line
)
2441 (while (looking-at "[ \t]*|\\(-\\)?")
2442 (push (if (match-end 1) 'hline
'dline
) types
)
2443 (if (match-end 1) (push l hlines
) (push l dlines
))
2444 (beginning-of-line 2)
2446 (push 'hline types
) ;; add an imaginary extra hline to the end
2447 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2448 last-dline
(car dlines
)
2449 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2450 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2451 (org-goto-line last-dline
)
2452 (let* ((l last-dline
)
2453 (fields (org-split-string
2454 (buffer-substring (point-at-bol) (point-at-eol))
2456 (nfields (length fields
))
2458 (setq org-table-current-ncol nfields
)
2459 (loop for i from
1 to nfields do
2460 (push (list (format "LR%d" i
) l i
) al
)
2461 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2462 (setq org-table-named-field-locations
2463 (append org-table-named-field-locations al
))
2464 (setq org-table-local-parameters
2465 (append org-table-local-parameters al2
))))))
2468 (defun org-table-maybe-eval-formula ()
2469 "Check if the current field starts with \"=\" or \":=\".
2470 If yes, store the formula and apply it."
2471 ;; We already know we are in a table. Get field will only return a formula
2472 ;; when appropriate. It might return a separator line, but no problem.
2473 (when org-table-formula-evaluate-inline
2474 (let* ((field (org-trim (or (org-table-get-field) "")))
2476 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2477 (setq named
(equal (string-to-char field
) ?
:)
2478 eq
(match-string 1 field
))
2479 (if (or (fboundp 'calc-eval
)
2480 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2481 (org-table-eval-formula (if named
'(4) nil
)
2482 (org-table-formula-from-user eq
))
2483 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2485 (defvar org-recalc-commands nil
2486 "List of commands triggering the recalculation of a line.
2487 Will be filled automatically during use.")
2489 (defvar org-recalc-marks
2490 '((" " .
"Unmarked: no special line, no automatic recalculation")
2491 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2492 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2493 ("!" .
"Column name definition line. Reference in formula as $name.")
2494 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2495 ("_" .
"Names for values in row below this one.")
2496 ("^" .
"Names for values in row above this one.")))
2499 (defun org-table-rotate-recalc-marks (&optional newchar
)
2500 "Rotate the recalculation mark in the first column.
2501 If in any row, the first field is not consistent with a mark,
2502 insert a new column for the markers.
2503 When there is an active region, change all the lines in the region,
2504 after prompting for the marking character.
2505 After each change, a message will be displayed indicating the meaning
2508 (unless (org-at-table-p) (user-error "Not at a table"))
2509 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2510 (beg (org-table-begin))
2511 (end (org-table-end))
2512 (l (org-current-line))
2513 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2514 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2518 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2519 (col (org-table-current-column))
2520 (forcenew (car (assoc newchar org-recalc-marks
)))
2523 (message "Change region to what mark? Type # * ! $ or SPC: ")
2524 (setq newchar
(char-to-string (read-char-exclusive))
2525 forcenew
(car (assoc newchar org-recalc-marks
))))
2526 (if (and newchar
(not forcenew
))
2527 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2529 (if l1
(org-goto-line l1
))
2531 (beginning-of-line 1)
2532 (unless (looking-at org-table-dataline-regexp
)
2533 (user-error "Not at a table data line")))
2535 (org-table-goto-column 1)
2536 (org-table-insert-column)
2537 (org-table-goto-column (1+ col
)))
2538 (setq epos
(point-at-eol))
2540 (beginning-of-line 1)
2541 (org-table-get-field
2542 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2544 (setq new
(or forcenew
2545 (cadr (member (match-string 1) marks
))))
2551 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2552 (and (looking-at org-table-dataline-regexp
)
2553 (org-table-get-field 1 (concat " " new
" "))))
2554 (org-goto-line l1
)))
2555 (if (not (= epos
(point-at-eol))) (org-table-align))
2557 (and (org-called-interactively-p 'interactive
)
2558 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2561 (defun org-table-maybe-recalculate-line ()
2562 "Recompute the current line if marked for it, and if we haven't just done it."
2564 (and org-table-allow-automatic-line-recalculation
2565 (not (and (memq last-command org-recalc-commands
)
2566 (equal org-last-recalc-line
(org-current-line))))
2567 (save-excursion (beginning-of-line 1)
2568 (looking-at org-table-auto-recalculate-regexp
))
2569 (org-table-recalculate) t
))
2571 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2572 (defsubst org-set-calc-mode
(var &optional value
)
2574 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2575 ("R" calc-angle-mode rad
)
2576 ("F" calc-prefer-frac t
)
2577 ("S" calc-symbolic-mode t
)))
2578 value
(nth 2 var
) var
(nth 1 var
)))
2579 (if (memq var org-tbl-calc-modes
)
2580 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2581 (cons var
(cons value org-tbl-calc-modes
)))
2585 (defun org-table-eval-formula (&optional arg equation
2586 suppress-align suppress-const
2587 suppress-store suppress-analysis
)
2588 "Replace the table field value at the cursor by the result of a calculation.
2590 This function makes use of Dave Gillespie's Calc package, in my view the
2591 most exciting program ever written for GNU Emacs. So you need to have Calc
2592 installed in order to use this function.
2594 In a table, this command replaces the value in the current field with the
2595 result of a formula. It also installs the formula as the \"current\" column
2596 formula, by storing it in a special line below the table. When called
2597 with a `C-u' prefix, the current field must be a named field, and the
2598 formula is installed as valid in only this specific field.
2600 When called with two `C-u' prefixes, insert the active equation
2601 for the field back into the current field, so that it can be
2602 edited there. This is useful in order to use \\[org-table-show-reference]
2603 to check the referenced fields.
2605 When called, the command first prompts for a formula, which is read in
2606 the minibuffer. Previously entered formulas are available through the
2607 history list, and the last used formula is offered as a default.
2608 These stored formulas are adapted correctly when moving, inserting, or
2609 deleting columns with the corresponding commands.
2611 The formula can be any algebraic expression understood by the Calc package.
2612 For details, see the Org-mode manual.
2614 This function can also be called from Lisp programs and offers
2615 additional arguments: EQUATION can be the formula to apply. If this
2616 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2617 used to speed-up recursive calls by by-passing unnecessary aligns.
2618 SUPPRESS-CONST suppresses the interpretation of constants in the
2619 formula, assuming that this has been done already outside the function.
2620 SUPPRESS-STORE means the formula should not be stored, either because
2621 it is already stored, or because it is a modified equation that should
2622 not overwrite the stored one."
2624 (org-table-check-inside-data-field)
2625 (or suppress-analysis
(org-table-get-specials))
2626 (if (equal arg
'(16))
2627 (let ((eq (org-table-current-field-formula)))
2628 (or eq
(user-error "No equation active for current field"))
2629 (org-table-get-field nil eq
)
2631 (setq org-table-may-need-update t
))
2633 (ndown (if (integerp arg
) arg
1))
2634 (org-table-automatic-realign nil
)
2635 (case-fold-search nil
)
2637 (formula (if (and equation suppress-store
)
2639 (org-table-get-formula equation
(equal arg
'(4)))))
2640 (n0 (org-table-current-column))
2641 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2642 (numbers nil
) ; was a variable, now fixed default
2644 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2645 duration duration-output-format
)
2646 ;; Parse the format string. Since we have a lot of modes, this is
2647 ;; a lot of work. However, I think calc still uses most of the time.
2648 (if (string-match ";" formula
)
2649 (let ((tmp (org-split-string formula
";")))
2650 (setq formula
(car tmp
)
2651 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2653 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2654 (setq c
(string-to-char (match-string 1 fmt
))
2655 n
(string-to-number (match-string 2 fmt
)))
2657 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2658 (setq org-tbl-calc-modes
2661 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2662 (?s . sci
) (?e . eng
))))
2664 (setq fmt
(replace-match "" t t fmt
)))
2665 (if (string-match "T" fmt
)
2666 (setq duration t numbers t
2667 duration-output-format nil
2668 fmt
(replace-match "" t t fmt
)))
2669 (if (string-match "t" fmt
)
2671 duration-output-format org-table-duration-custom-format
2673 fmt
(replace-match "" t t fmt
)))
2674 (if (string-match "N" fmt
)
2676 fmt
(replace-match "" t t fmt
)))
2677 (if (string-match "L" fmt
)
2679 fmt
(replace-match "" t t fmt
)))
2680 (if (string-match "E" fmt
)
2682 fmt
(replace-match "" t t fmt
)))
2683 (while (string-match "[DRFS]" fmt
)
2684 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2685 (setq fmt
(replace-match "" t t fmt
)))
2686 (unless (string-match "\\S-" fmt
)
2688 (if (and (not suppress-const
) org-table-formula-use-constants
)
2689 (setq formula
(org-table-formula-substitute-names formula
)))
2690 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2692 (setq fields
(org-split-string
2693 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2695 ;; replace fields with duration values if relevant
2698 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2701 (setq fields
(mapcar
2703 (if (string-match "\\S-" x
)
2704 (number-to-string (string-to-number x
))
2707 (setq ndown
(1- ndown
))
2708 (setq form
(copy-sequence formula
)
2709 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2710 (if (and lispp literal
) (setq lispp
'literal
))
2712 ;; Insert row and column number of formula result field
2713 (while (string-match "[@$]#" form
)
2718 (if (equal (substring form
(match-beginning 0)
2719 (1+ (match-beginning 0)))
2721 (org-table-current-dline)
2722 (org-table-current-column))))
2725 ;; Check for old vertical references
2726 (org-table--error-on-old-row-references form
)
2727 ;; Insert remote references
2728 (setq form
(org-table-remote-reference-indirection form
))
2729 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2733 (org-table-make-reference
2734 (let ((rmtrng (org-table-get-remote-range
2735 (match-string 1 form
) (match-string 2 form
))))
2738 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2739 (org-table-time-string-to-seconds rmtrng
))
2741 keep-empty numbers lispp
))
2743 ;; Insert complex ranges
2744 (while (and (string-match org-table-range-regexp form
)
2745 (> (length (match-string 0 form
)) 1))
2746 (setq formrg
(save-match-data
2747 (org-table-get-range (match-string 0 form
) nil n0
)))
2750 (org-table-make-reference
2751 ;; possibly handle durations
2754 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2755 (org-table-time-string-to-seconds formrg
))
2757 keep-empty numbers lispp
)))
2758 (if (not (save-match-data
2759 (string-match (regexp-quote form
) formrpl
)))
2760 (setq form
(replace-match formrpl t t form
))
2761 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2762 ;; Insert simple ranges, i.e. included in the current row.
2763 (while (string-match
2764 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2769 (org-table-make-reference
2771 (+ (if (match-end 2) n0
0)
2772 (string-to-number (match-string 1 form
)))
2773 (+ (if (match-end 4) n0
0)
2774 (string-to-number (match-string 3 form
))))
2775 keep-empty numbers lispp
))
2778 ;; Insert the references to fields in same row
2779 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2780 (setq n
(+ (string-to-number (match-string 1 form
))
2781 (if (match-end 2) n0
0))
2782 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2783 formrpl
(save-match-data
2784 (org-table-make-reference
2785 x keep-empty numbers lispp
)))
2788 (string-match (regexp-quote formula
) formrpl
)))
2789 (user-error "Invalid field specifier \"%s\""
2790 (match-string 0 form
)))
2791 (setq form
(replace-match formrpl t t form
)))
2794 (setq ev
(condition-case nil
2795 (eval (eval (read form
)))
2797 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2798 ev
(if duration
(org-table-time-seconds-to-string
2799 (string-to-number ev
)
2800 duration-output-format
) ev
))
2801 (or (fboundp 'calc-eval
)
2802 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2803 ;; Use <...> time-stamps so that Calc can handle them
2804 (while (string-match (concat "\\[" org-ts-regexp1
"\\]") form
)
2805 (setq form
(replace-match "<\\1>" nil nil form
)))
2806 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2807 (when (string-match org-ts-regexp2 form
)
2808 (let* ((ts (match-string 0 form
))
2809 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2810 (system-time-locale "C")
2811 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2812 (cdr org-time-stamp-formats
))
2813 (car org-time-stamp-formats
))))
2814 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2816 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2818 (calc-eval (cons form org-tbl-calc-modes
)
2819 (when (and (not keep-empty
) numbers
) 'num
)))
2820 ev
(if duration
(org-table-time-seconds-to-string
2821 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2822 (string-to-number (org-table-time-string-to-seconds ev
))
2823 (string-to-number ev
))
2824 duration-output-format
)
2827 (when org-table-formula-debug
2828 (with-output-to-temp-buffer "*Substitution History*"
2829 (princ (format "Substitution history of formula
2833 $1-> %s\n" orig formula form0 form
))
2835 (princ (format " %s^\nError: %s"
2836 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2837 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2839 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2840 (setq bw
(get-buffer-window "*Substitution History*"))
2841 (org-fit-window-to-buffer bw
)
2842 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2843 (unless (let (inhibit-redisplay)
2844 (y-or-n-p "Debugging Formula. Continue to next? "))
2846 (user-error "Abort"))
2849 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2850 (org-table-justify-field-maybe
2851 (format org-table-formula-field-format
2852 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2853 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2854 (call-interactively 'org-return
)
2856 (and down
(org-table-maybe-recalculate-line))
2857 (or suppress-align
(and org-table-may-need-update
2858 (org-table-align))))))
2860 (defun org-table-put-field-property (prop value
)
2862 (put-text-property (progn (skip-chars-backward "^|") (point))
2863 (progn (skip-chars-forward "^|") (point))
2866 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2867 "Get a calc vector from a column, according to descriptor DESC.
2868 Optional arguments TBEG and COL can give the beginning of the table and
2869 the current column, to avoid unnecessary parsing.
2871 HIGHLIGHT means just highlight the range.
2873 When CORNERS-ONLY is set, only return the corners of the range as
2874 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2875 in the buffer and column1 and column2 are table column numbers."
2876 (if (not (equal (string-to-char desc
) ?
@))
2877 (setq desc
(concat "@" desc
)))
2879 (or tbeg
(setq tbeg
(org-table-begin)))
2880 (or col
(setq col
(org-table-current-column)))
2881 (let ((thisline (org-current-line))
2882 beg end c1 c2 r1 r2 rangep tmp
)
2883 (unless (string-match org-table-range-regexp desc
)
2884 (user-error "Invalid table range specifier `%s'" desc
))
2885 (setq rangep
(match-end 3)
2886 r1
(and (match-end 1) (match-string 1 desc
))
2887 r2
(and (match-end 4) (match-string 4 desc
))
2888 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2889 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2891 (and c1
(setq c1
(+ (string-to-number c1
)
2892 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2893 (and c2
(setq c2
(+ (string-to-number c2
)
2894 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2895 (if (equal r1
"") (setq r1 nil
))
2896 (if (equal r2
"") (setq r2 nil
))
2897 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2898 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2899 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2900 (if (not r1
) (setq r1 thisline
))
2901 (if (not r2
) (setq r2 thisline
))
2902 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2903 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2904 (if (and (not corners-only
)
2905 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2909 (while (not (looking-at org-table-dataline-regexp
))
2910 (beginning-of-line 2))
2911 (prog1 (org-trim (org-table-get-field c1
))
2912 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2913 ;; A range, return a vector
2914 ;; First sort the numbers to get a regular rectangle
2915 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2916 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2918 ;; Only return the corners of the range
2920 ;; Copy the range values into a list
2922 (while (not (looking-at org-table-dataline-regexp
))
2923 (beginning-of-line 2))
2924 (org-table-goto-column c1
)
2927 (while (not (looking-at org-table-dataline-regexp
))
2928 (beginning-of-line 0))
2929 (org-table-goto-column c2
)
2932 (org-table-highlight-rectangle
2933 beg
(progn (skip-chars-forward "^|\n") (point))))
2934 ;; return string representation of calc vector
2936 (apply 'append
(org-table-copy-region beg end
))))))))
2938 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2939 "Analyze descriptor DESC and retrieve the corresponding line number.
2940 The cursor is currently in line CLINE, the table begins in line BLINE,
2941 and TABLE is a vector with line types."
2942 (if (string-match "^[0-9]+$" desc
)
2943 (aref org-table-dlines
(string-to-number desc
))
2944 (setq cline
(or cline
(org-current-line))
2945 bline
(or bline org-table-current-begin-line
)
2946 table
(or table org-table-current-line-types
))
2948 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2950 (and (not (match-end 3)) (not (match-end 6)))
2951 (and (match-end 3) (match-end 6) (not (match-end 5))))
2952 (user-error "Invalid row descriptor `%s'" desc
))
2953 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2954 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2955 (odir (and (match-end 5) (match-string 5 desc
)))
2956 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2958 (rel (and (match-end 6)
2959 (or (and (match-end 1) (not (match-end 3)))
2961 (if (and hn
(not hdir
))
2964 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2965 (if (and (not hn
) on
(not odir
))
2966 (user-error "Should never happen");;(aref org-table-dlines on)
2967 (if (and hn
(> hn
0))
2968 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2969 nil hn cline desc
)))
2971 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2972 rel on cline desc
)))
2975 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2976 "FIXME: Needs more documentation."
2977 (let ((l (length table
)))
2979 (while (and (setq i
(+ i
(if backwards -
1 1)))
2981 (not (eq (aref table i
) type
))
2982 (if (and relative
(eq (aref table i
) 'hline
))
2984 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2985 ((eq org-table-relative-ref-may-cross-hline
'error
)
2986 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2987 (t (setq i
(- i
(if backwards -
1 1))
2992 (cond ((or (< i
0) (>= i l
))
2993 (user-error "Row descriptor %s used in line %d leads outside table"
2995 ;; The last hline doesn't exist. Instead, point to last row
2997 ((= i
(1- l
)) (1- i
))
3000 (defun org-table--error-on-old-row-references (s)
3001 (when (string-match "&[-+0-9I]" s
)
3002 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3004 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3005 "Convert list ELEMENTS to something appropriate to insert into formula.
3006 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3007 NUMBERS indicates that everything should be converted to numbers.
3008 LISPP non-nil means to return something appropriate for a Lisp
3009 list, 'literal is for the format specifier L."
3010 ;; Calc nan (not a number) is used for the conversion of the empty
3011 ;; field to a reference for several reasons: (i) It is accepted in a
3012 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3013 ;; (ii) In a single field (not in range) it can be distinguished
3014 ;; from "(nan)" which is the reference made from a single field
3015 ;; containing "nan".
3016 (if (stringp elements
)
3019 (if (eq lispp
'literal
)
3021 (if (and (eq elements
"") (not keep-empty
))
3024 (if numbers
(string-to-number elements
) elements
))))
3025 (if (string-match "\\S-" elements
)
3027 (when numbers
(setq elements
(number-to-string
3028 (string-to-number elements
))))
3029 (concat "(" elements
")"))
3030 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3035 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3037 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3041 (if (eq lispp
'literal
)
3043 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3045 (concat "[" (mapconcat
3047 (if (string-match "\\S-" x
)
3049 (number-to-string (string-to-number x
))
3051 (if (or (not keep-empty
) numbers
) "0" "nan")))
3055 (defun org-table-message-once-per-second (t1 &rest args
)
3056 "If there has been more than one second since T1, display message.
3057 ARGS are passed as arguments to the `message' function. Returns
3058 current time if a message is printed, otherwise returns T1. If
3059 T1 is nil, always messages."
3060 (let ((curtime (current-time)))
3061 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3062 (progn (apply 'message args
)
3067 (defun org-table-recalculate (&optional all noalign
)
3068 "Recalculate the current table line by applying all stored formulas.
3069 With prefix arg ALL, do this for all lines in the table.
3070 With the prefix argument ALL is `(16)' \
3071 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3072 it is the symbol `iterate', recompute the table until it no longer changes.
3073 If NOALIGN is not nil, do not re-align the table after the computations
3074 are done. This is typically used internally to save time, if it is
3075 known that the table will be realigned a little later anyway."
3077 (or (memq this-command org-recalc-commands
)
3078 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
3079 (unless (org-at-table-p) (user-error "Not at a table"))
3080 (if (or (eq all
'iterate
) (equal all
'(16)))
3082 (org-table-get-specials)
3083 (let* ((eqlist (sort (org-table-get-stored-formulas)
3084 (lambda (a b
) (string< (car a
) (car b
)))))
3085 (eqlist1 (copy-sequence eqlist
))
3086 (inhibit-redisplay (not debug-on-error
))
3087 (line-re org-table-dataline-regexp
)
3088 (thisline (org-current-line))
3089 (thiscol (org-table-current-column))
3090 (log-first-time (current-time))
3091 (log-last-time log-first-time
)
3093 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3094 ;; Insert constants in all formulas
3099 (if (string-match "^@-?I+" (car x
))
3100 (user-error "Can't assign to hline relative reference"))
3101 (when (string-match "\\`$[<>]" (car x
))
3103 (setq x
(cons (substring
3104 (org-table-formula-handle-first/last-rc
3107 (if (assoc (car x
) eqlist1
)
3108 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3111 (org-table-formula-handle-first/last-rc
(car x
))
3112 (org-table-formula-substitute-names
3113 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3115 ;; Split the equation list
3116 (while (setq eq
(pop eqlist
))
3117 (if (<= (string-to-char (car eq
)) ?
9)
3120 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3121 ;; Expand ranges in lhs of formulas
3122 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3124 ;; Get the correct line range to process
3127 (setq end
(copy-marker (1+ (org-table-end))))
3128 (goto-char (setq beg
(org-table-begin)))
3129 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3130 ;; This is a table with marked lines, compute selected lines
3131 (setq line-re org-table-recalculate-regexp
)
3132 ;; Move forward to the first non-header line
3133 (if (and (re-search-forward org-table-dataline-regexp end t
)
3134 (re-search-forward org-table-hline-regexp end t
)
3135 (re-search-forward org-table-dataline-regexp end t
))
3136 (setq beg
(match-beginning 0))
3137 nil
))) ;; just leave beg where it is
3138 (setq beg
(point-at-bol)
3139 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3142 ;; First find the named fields, and mark them untouchable.
3143 ;; Also check if several field/range formulas try to set the same field.
3144 (remove-text-properties beg end
'(org-untouchable t
))
3145 (while (setq eq
(pop eqlname
))
3147 a
(assoc name org-table-named-field-locations
))
3149 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3151 (when (member name1 seen-fields
)
3152 (user-error "Several field/range formulas try to set %s" name1
))
3153 (push name1 seen-fields
)
3156 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3159 (aref org-table-dlines
3160 (string-to-number (match-string 1 name
)))
3161 (error (user-error "Invalid row number in %s"
3163 (string-to-number (match-string 2 name
)))))
3164 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3166 (org-table-message-once-per-second
3167 (and all log-last-time
)
3168 "Re-applying formula to field: %s" name
))
3169 (org-goto-line (nth 1 a
))
3170 (org-table-goto-column (nth 2 a
))
3171 (push (append a
(list (cdr eq
))) eqlname1
)
3172 (org-table-put-field-property :org-untouchable t
)))
3173 (setq eqlname1
(nreverse eqlname1
))
3175 ;; Now evaluate the column formulas, but skip fields covered
3176 ;; by field formulas
3178 (while (re-search-forward line-re end t
)
3179 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3180 ;; Unprotected line, recalculate
3182 (and all
(setq log-last-time
3183 (org-table-message-once-per-second
3185 "Re-applying formulas to full table...(line %d)" cnt
)))
3186 (setq org-last-recalc-line
(org-current-line))
3188 (while (setq entry
(pop eql
))
3189 (org-goto-line org-last-recalc-line
)
3190 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3191 (unless (get-text-property (point) :org-untouchable
)
3192 (org-table-eval-formula
3194 'noalign
'nocst
'nostore
'noanalysis
)))))
3196 ;; Now evaluate the field formulas
3197 (while (setq eq
(pop eqlname1
))
3199 (org-table-message-once-per-second
3200 (and all log-last-time
)
3201 "Re-applying formula to field: %s" (car eq
)))
3202 (org-goto-line (nth 1 eq
))
3203 (let ((column-target (nth 2 eq
)))
3204 (when (> column-target
1000)
3205 (user-error "Formula column target too large"))
3206 (let* ((column-count (progn (end-of-line)
3207 (1- (org-table-current-column))))
3209 (and (> column-target column-count
)
3210 (or (eq org-table-formula-create-columns t
)
3212 (eq org-table-formula-create-columns
'warn
)
3214 (org-display-warning
3215 "Out-of-bounds formula added columns")
3218 (eq org-table-formula-create-columns
'prompt
)
3220 "Out-of-bounds formula. Add columns?"))))))
3221 (org-table-goto-column column-target nil create-new-column
))
3223 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3224 'nostore
'noanalysis
)))
3226 (org-goto-line thisline
)
3227 (org-table-goto-column thiscol
)
3228 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3229 (or noalign
(and org-table-may-need-update
(org-table-align))
3230 (and all
(org-table-message-once-per-second
3232 "Re-applying formulas to %d lines...done" cnt
)))
3235 ;; back to initial position
3236 (org-table-message-once-per-second
3237 (and all log-first-time
)
3238 "Re-applying formulas...done")
3240 (org-goto-line thisline
)
3241 (org-table-goto-column thiscol
)
3242 (or noalign
(and org-table-may-need-update
(org-table-align)))))))
3245 (defun org-table-iterate (&optional arg
)
3246 "Recalculate the table until it does not change anymore.
3247 The maximum number of iterations is 10, but you can choose a different value
3248 with the prefix ARG."
3250 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3252 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3257 (org-table-recalculate 'all
)
3258 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3259 (if (not (string= lasttbl thistbl
))
3260 (setq lasttbl thistbl
)
3262 (message "Convergence after %d iterations" i
)
3263 (message "Table was already stable"))
3265 (user-error "No convergence after %d iterations" i
))))
3268 (defun org-table-recalculate-buffer-tables ()
3269 "Recalculate all tables in the current buffer."
3274 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3277 (defun org-table-iterate-buffer-tables ()
3278 "Iterate all tables in the buffer, to converge inter-table dependencies."
3282 (checksum (md5 (buffer-string)))
3290 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3291 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3293 (message "Convergence after %d iterations" (- imax i
))
3295 (setq checksum c1
)))
3296 (user-error "No convergence after %d iterations" imax
))))))
3298 (defun org-table-calc-current-TBLFM (&optional arg
)
3299 "Apply the #+TBLFM in the line at point to the table."
3301 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3302 (let ((formula (buffer-substring
3303 (line-beginning-position)
3304 (line-end-position))))
3306 ;; Insert a temporary formula at right after the table
3307 (goto-char (org-table-TBLFM-begin))
3308 (let ((s (point-marker)))
3309 (insert formula
"\n")
3310 (let ((e (point-marker)))
3311 ;; Recalculate the table.
3312 (beginning-of-line 0) ; move to the inserted line
3313 (skip-chars-backward " \r\n\t")
3315 (org-call-with-arg #'org-table-recalculate
(or arg t
))
3316 ;; Delete the formula inserted temporarily.
3319 (set-marker e nil
)))))))
3321 (defun org-table-TBLFM-begin ()
3322 "Find the beginning of the TBLFM lines and return its position.
3323 Return nil when the beginning of TBLFM line was not found."
3325 (when (progn (forward-line 1)
3326 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3327 (line-beginning-position 2))))
3329 (defun org-table-expand-lhs-ranges (equations)
3330 "Expand list of formulas.
3331 If some of the RHS in the formulas are ranges or a row reference, expand
3332 them to individual field equations for each field."
3333 (let (e res lhs rhs range r1 r2 c1 c2
)
3334 (while (setq e
(pop equations
))
3335 (setq lhs
(car e
) rhs
(cdr e
))
3337 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3338 ;; This just refers to one fixed field
3340 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3341 ;; This just refers to one fixed named field
3343 ((string-match "^@[0-9]+$" lhs
)
3344 (loop for ic from
1 to org-table-current-ncol do
3345 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3346 (put-text-property 0 (length (caar res
))
3347 :orig-eqn e
(caar res
))))
3349 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3351 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3352 r2
(nth 2 range
) c2
(nth 3 range
))
3353 (setq r1
(org-table-line-to-dline r1
))
3354 (setq r2
(org-table-line-to-dline r2
'above
))
3355 (loop for ir from r1 to r2 do
3356 (loop for ic from c1 to c2 do
3357 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3358 (put-text-property 0 (length (caar res
))
3359 :orig-eqn e
(caar res
)))))))
3362 (defun org-table-formula-handle-first/last-rc
(s)
3363 "Replace @<, @>, $<, $> with first/last row/column of the table.
3364 So @< and $< will always be replaced with @1 and $1, respectively.
3365 The advantage of these special markers are that structure editing of
3366 the table will not change them, while @1 and $1 will be modified
3367 when a line/row is swapped out of that privileged position. So for
3368 formulas that use a range of rows or columns, it may often be better
3369 to anchor the formula with \"I\" row markers, or to offset from the
3370 borders of the table using the @< @> $< $> makers."
3371 (let (n nmax len char
(start 0))
3372 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3375 (setq start
(match-end 3))
3376 (setq nmax
(if (equal (match-string 1 s
) "@")
3377 (1- (length org-table-dlines
))
3378 org-table-current-ncol
)
3379 len
(- (match-end 2) (match-beginning 2))
3380 char
(string-to-char (match-string 2 s
))
3384 (if (or (< n
1) (> n nmax
))
3385 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3386 (match-string 0 s
) s
))
3387 (setq start
(match-beginning 0))
3388 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3391 (defun org-table-formula-substitute-names (f)
3392 "Replace $const with values in string F."
3394 (pp (/= (string-to-char f
) ?
'))
3395 (duration (org-string-match-p ";.*[Tt].*\\'" f
))
3396 (new (replace-regexp-in-string ; Check for column names.
3397 org-table-column-name-regexp
3399 (concat "$" (cdr (assoc (match-string 1 m
)
3400 org-table-column-names
))))
3402 ;; Parameters and constants.
3405 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3407 (if (match-end 2) (setq start
(match-end 2))
3409 ;; When a duration is expected, convert value on the fly.
3412 (let ((v (org-table-get-constant (match-string 1 new
))))
3413 (if (and (org-string-nw-p v
) duration
)
3414 (org-table-time-string-to-seconds v
)
3417 (setq new
(replace-match
3418 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3419 (if org-table-formula-debug
(org-propertize new
:orig-formula f
)) new
))
3421 (defun org-table-get-constant (const)
3422 "Find the value for a parameter or constant in a formula.
3423 Parameters get priority."
3424 (or (cdr (assoc const org-table-local-parameters
))
3425 (cdr (assoc const org-table-formula-constants-local
))
3426 (cdr (assoc const org-table-formula-constants
))
3427 (and (fboundp 'constants-get
) (constants-get const
))
3428 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3429 (org-entry-get nil
(substring const
5) 'inherit
))
3432 (defvar org-table-fedit-map
3433 (let ((map (make-sparse-keymap)))
3434 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3435 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3436 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3437 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3438 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3439 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3440 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3441 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3442 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3443 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3444 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3445 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3446 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3447 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3448 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3449 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3450 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3451 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3452 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3453 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3456 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3458 ["Finish and Install" org-table-fedit-finish t
]
3459 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3460 ["Abort" org-table-fedit-abort t
]
3462 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3463 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3465 "Shift Reference at Point"
3466 ["Up" org-table-fedit-ref-up t
]
3467 ["Down" org-table-fedit-ref-down t
]
3468 ["Left" org-table-fedit-ref-left t
]
3469 ["Right" org-table-fedit-ref-right t
]
3471 "Change Test Row for Column Formulas"
3472 ["Up" org-table-fedit-line-up t
]
3473 ["Down" org-table-fedit-line-down t
]
3475 ["Scroll Table Window" org-table-fedit-scroll t
]
3476 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3477 ["Show Table Grid" org-table-fedit-toggle-coordinates
3478 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3479 org-table-overlay-coordinates
)]
3481 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3482 :style toggle
:selected org-table-buffer-is-an
]))
3487 (defun org-table-edit-formulas ()
3488 "Edit the formulas of the current table in a separate buffer."
3490 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3491 (beginning-of-line 0))
3492 (unless (org-at-table-p) (user-error "Not at a table"))
3493 (org-table-get-specials)
3494 (let ((key (org-table-current-field-formula 'key
'noerror
))
3495 (eql (sort (org-table-get-stored-formulas 'noerror
)
3496 'org-table-formula-less-p
))
3497 (pos (point-marker))
3499 (wc (current-window-configuration))
3500 (sel-win (selected-window))
3501 (titles '((column .
"# Column Formulas\n")
3502 (field .
"# Field and Range Formulas\n")
3503 (named .
"# Named Field Formulas\n")))
3505 (org-switch-to-buffer-other-window "*Edit Formulas*")
3507 ;; Keep global-font-lock-mode from turning on font-lock-mode
3508 (let ((font-lock-global-modes '(not fundamental-mode
)))
3510 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3511 (org-set-local 'org-pos pos
)
3512 (org-set-local 'org-window-configuration wc
)
3513 (org-set-local 'org-selected-window sel-win
)
3514 (use-local-map org-table-fedit-map
)
3515 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3516 (easy-menu-add org-table-fedit-menu
)
3517 (setq startline
(org-current-line))
3518 (while (setq entry
(pop eql
))
3520 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3521 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3522 ((string-match "^[0-9]" (car entry
)) 'column
)
3524 (when (setq title
(assq type titles
))
3525 (or (bobp) (insert "\n"))
3526 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3527 (setq titles
(remove title titles
)))
3528 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3529 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3530 (car entry
) " = " (cdr entry
) "\n"))
3531 (remove-text-properties 0 (length s
) '(face nil
) s
)
3533 (if (eq org-table-use-standard-references t
)
3534 (org-table-fedit-toggle-ref-type))
3535 (org-goto-line startline
)
3536 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3538 (defun org-table-fedit-post-command ()
3539 (when (not (memq this-command
'(lisp-complete-symbol)))
3540 (let ((win (selected-window)))
3543 (org-table-show-reference)
3545 (select-window win
)))))
3547 (defun org-table-formula-to-user (s)
3548 "Convert a formula from internal to user representation."
3549 (if (eq org-table-use-standard-references t
)
3550 (org-table-convert-refs-to-an s
)
3553 (defun org-table-formula-from-user (s)
3554 "Convert a formula from user to internal representation."
3555 (if org-table-use-standard-references
3556 (org-table-convert-refs-to-rc s
)
3559 (defun org-table-convert-refs-to-rc (s)
3560 "Convert spreadsheet references from A7 to @7$28.
3561 Works for single references, but also for entire formulas and even the
3564 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3567 ;; format match, just advance
3568 (setq start
(match-end 0)))
3569 ((and (> (match-beginning 0) 0)
3570 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3571 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3572 ;; 3.e5 or something like this.
3573 (setq start
(match-end 0)))
3574 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3575 ;; (member (match-string 1 s)
3576 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3578 ;; function name, just advance
3579 (setq start
(match-end 0)))
3581 (setq start
(match-beginning 0)
3583 (if (equal (match-string 2 s
) "&")
3584 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3586 (string-to-number (match-string 2 s
))
3587 (org-letters-to-number (match-string 1 s
))))
3591 (defun org-table-convert-refs-to-an (s)
3592 "Convert spreadsheet references from to @7$28 to AB7.
3593 Works for single references, but also for entire formulas and even the
3595 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3596 (setq s
(replace-match
3598 (org-number-to-letters
3599 (string-to-number (match-string 2 s
)))
3600 (string-to-number (match-string 1 s
)))
3602 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3603 (setq s
(replace-match (concat "\\1"
3604 (org-number-to-letters
3605 (string-to-number (match-string 2 s
))) "&")
3609 (defun org-letters-to-number (s)
3610 "Convert a base 26 number represented by letters into an integer.
3611 For example: AB -> 28."
3614 (while (> (length s
) 0)
3615 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3619 (defun org-number-to-letters (n)
3620 "Convert an integer into a base 26 number represented by letters.
3621 For example: 28 -> AB."
3624 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3628 (defun org-table-time-string-to-seconds (s)
3629 "Convert a time string into numerical duration in seconds.
3630 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3631 If S is a string representing a number, keep this number."
3634 (let (hour minus min sec res
)
3636 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3637 (setq minus
(< 0 (length (match-string 1 s
)))
3638 hour
(string-to-number (match-string 2 s
))
3639 min
(string-to-number (match-string 3 s
))
3640 sec
(string-to-number (match-string 4 s
)))
3642 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3643 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3644 ((and (not (string-match org-ts-regexp-both s
))
3645 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3646 (setq minus
(< 0 (length (match-string 1 s
)))
3647 hour
(string-to-number (match-string 2 s
))
3648 min
(string-to-number (match-string 3 s
)))
3650 (setq res
(- (+ (* hour
3600) (* min
60))))
3651 (setq res
(+ (* hour
3600) (* min
60)))))
3652 (t (setq res
(string-to-number s
))))
3653 (number-to-string res
))))
3655 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3656 "Convert a number of seconds to a time string.
3657 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3658 minutes or seconds."
3659 (let* ((secs0 (abs secs
))
3661 (cond ((eq output-format
'days
)
3662 (format "%.3f" (/ (float secs0
) 86400)))
3663 ((eq output-format
'hours
)
3664 (format "%.2f" (/ (float secs0
) 3600)))
3665 ((eq output-format
'minutes
)
3666 (format "%.1f" (/ (float secs0
) 60)))
3667 ((eq output-format
'seconds
)
3668 (format "%d" secs0
))
3669 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3670 (if (< secs
0) (concat "-" res
) res
)))
3672 (defun org-table-fedit-convert-buffer (function)
3673 "Convert all references in this buffer, using FUNCTION."
3674 (let ((line (org-current-line)))
3675 (goto-char (point-min))
3677 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3678 (delete-region (point) (point-at-eol))
3679 (or (eobp) (forward-char 1)))
3680 (org-goto-line line
)))
3682 (defun org-table-fedit-toggle-ref-type ()
3683 "Convert all references in the buffer from B3 to @3$2 and back."
3685 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3686 (org-table-fedit-convert-buffer
3687 (if org-table-buffer-is-an
3688 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3689 (message "Reference type switched to %s"
3690 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3692 (defun org-table-fedit-ref-up ()
3693 "Shift the reference at point one row/hline up."
3695 (org-table-fedit-shift-reference 'up
))
3696 (defun org-table-fedit-ref-down ()
3697 "Shift the reference at point one row/hline down."
3699 (org-table-fedit-shift-reference 'down
))
3700 (defun org-table-fedit-ref-left ()
3701 "Shift the reference at point one field to the left."
3703 (org-table-fedit-shift-reference 'left
))
3704 (defun org-table-fedit-ref-right ()
3705 "Shift the reference at point one field to the right."
3707 (org-table-fedit-shift-reference 'right
))
3709 (defun org-table-fedit-shift-reference (dir)
3711 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3712 (if (memq dir
'(left right
))
3713 (org-rematch-and-replace 1 (eq dir
'left
))
3714 (user-error "Cannot shift reference in this direction")))
3715 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3716 ;; A B3-like reference
3717 (if (memq dir
'(up down
))
3718 (org-rematch-and-replace 2 (eq dir
'up
))
3719 (org-rematch-and-replace 1 (eq dir
'left
))))
3721 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3722 ;; An internal reference
3723 (if (memq dir
'(up down
))
3724 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3725 (org-rematch-and-replace 5 (eq dir
'left
))))))
3727 (defun org-rematch-and-replace (n &optional decr hline
)
3728 "Re-match the group N, and replace it with the shifted reference."
3729 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3730 (goto-char (match-beginning n
))
3731 (and (looking-at (regexp-quote (match-string n
)))
3732 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3735 (defun org-table-shift-refpart (ref &optional decr hline
)
3736 "Shift a reference part REF.
3737 If DECR is set, decrease the references row/column, else increase.
3738 If HLINE is set, this may be a hline reference, it certainly is not
3739 a translation reference."
3741 (let* ((sign (string-match "^[-+]" ref
)) n
)
3743 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3745 ((and hline
(string-match "^I+" ref
))
3746 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3747 (setq n
(+ n
(if decr -
1 1)))
3748 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3750 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3752 (concat sign
(make-string n ?I
)))
3754 ((string-match "^[0-9]+" ref
)
3755 (setq n
(string-to-number (concat sign ref
)))
3756 (setq n
(+ n
(if decr -
1 1)))
3758 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3759 (number-to-string (max 1 n
))))
3761 ((string-match "^[a-zA-Z]+" ref
)
3762 (org-number-to-letters
3763 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3765 (t (user-error "Cannot shift reference"))))))
3767 (defun org-table-fedit-toggle-coordinates ()
3768 "Toggle the display of coordinates in the referenced table."
3770 (let ((pos (marker-position org-pos
)))
3771 (with-current-buffer (marker-buffer org-pos
)
3774 (org-table-toggle-coordinate-overlays)))))
3776 (defun org-table-fedit-finish (&optional arg
)
3777 "Parse the buffer for formula definitions and install them.
3778 With prefix ARG, apply the new formulas to the table."
3780 (org-table-remove-rectangle-highlight)
3781 (if org-table-use-standard-references
3783 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3784 (setq org-table-buffer-is-an nil
)))
3785 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3786 (goto-char (point-min))
3787 (while (re-search-forward
3788 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3790 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3791 form
(match-string 3))
3792 (setq form
(org-trim form
))
3793 (when (not (equal form
""))
3794 (while (string-match "[ \t]*\n[ \t]*" form
)
3795 (setq form
(replace-match " " t t form
)))
3796 (when (assoc var eql
)
3797 (user-error "Double formulas for %s" var
))
3798 (push (cons var form
) eql
)))
3800 (set-window-configuration org-window-configuration
)
3801 (select-window sel-win
)
3803 (unless (org-at-table-p)
3804 (user-error "Lost table position - cannot install formulas"))
3805 (org-table-store-formulas eql
)
3806 (move-marker pos nil
)
3807 (kill-buffer "*Edit Formulas*")
3809 (org-table-recalculate 'all
)
3810 (message "New formulas installed - press C-u C-c C-c to apply."))))
3812 (defun org-table-fedit-abort ()
3813 "Abort editing formulas, without installing the changes."
3815 (org-table-remove-rectangle-highlight)
3816 (let ((pos org-pos
) (sel-win org-selected-window
))
3817 (set-window-configuration org-window-configuration
)
3818 (select-window sel-win
)
3820 (move-marker pos nil
)
3821 (message "Formula editing aborted without installing changes")))
3823 (defun org-table-fedit-lisp-indent ()
3824 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3826 (let ((pos (point)) beg end ind
)
3827 (beginning-of-line 1)
3829 ((looking-at "[ \t]")
3831 (call-interactively 'lisp-indent-line
))
3832 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3833 ((not (fboundp 'pp-buffer
))
3834 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3835 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3836 (goto-char (- (match-end 0) 2))
3838 (setq ind
(make-string (current-column) ?\
))
3839 (condition-case nil
(forward-sexp 1)
3841 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3844 (narrow-to-region beg end
)
3845 (if (eq last-command this-command
)
3847 (goto-char (point-min))
3848 (setq this-command nil
)
3849 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3850 (replace-match " ")))
3852 (untabify (point-min) (point-max))
3853 (goto-char (1+ (point-min)))
3854 (while (re-search-forward "^." nil t
)
3855 (beginning-of-line 1)
3857 (goto-char (point-max))
3858 (org-delete-backward-char 1)))
3862 (defvar org-show-positions nil
)
3864 (defun org-table-show-reference (&optional local
)
3865 "Show the location/value of the $ expression at point."
3867 (org-table-remove-rectangle-highlight)
3869 (let ((pos (if local
(point) org-pos
))
3871 (org-inhibit-highlight-removal t
)
3872 (win (selected-window))
3873 (org-show-positions nil
)
3874 var name e what match dest
)
3875 (if local
(org-table-get-specials))
3877 ((org-in-regexp "^@[0-9]+[ \t=]")
3878 (setq match
(concat (substring (match-string 0) 0 -
1)
3880 (substring (match-string 0) 0 -
1)
3883 ((or (org-in-regexp org-table-range-regexp2
)
3884 (org-in-regexp org-table-translate-regexp
)
3885 (org-in-regexp org-table-range-regexp
))
3888 (org-table-convert-refs-to-rc (match-string 0))))
3890 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3891 ((org-in-regexp "\\$[0-9]+") 'column
)
3893 (t (user-error "No reference at point")))
3894 match
(and what
(or match
(match-string 0))))
3895 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3896 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3897 'secondary-selection
))
3898 (org-add-hook 'before-change-functions
3899 'org-table-remove-rectangle-highlight
)
3900 (if (eq what
'name
) (setq var
(substring match
1)))
3901 (when (eq what
'range
)
3902 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3903 (setq match
(org-table-formula-substitute-names match
)))
3907 (re-search-backward "^\\S-" nil t
)
3908 (beginning-of-line 1)
3909 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3912 (org-table-convert-refs-to-rc (match-string 1))))
3913 (org-table-add-rectangle-overlay
3914 (match-beginning 1) (match-end 1) face2
))))
3915 (if (and (markerp pos
) (marker-buffer pos
))
3916 (if (get-buffer-window (marker-buffer pos
))
3917 (select-window (get-buffer-window (marker-buffer pos
)))
3918 (org-switch-to-buffer-other-window (get-buffer-window
3919 (marker-buffer pos
)))))
3921 (org-table-force-dataline)
3923 (setq name
(substring dest
1))
3925 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3926 (setq e
(assoc name org-table-named-field-locations
))
3927 (org-goto-line (nth 1 e
))
3928 (org-table-goto-column (nth 2 e
)))
3929 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3930 (let ((l (string-to-number (match-string 1 dest
)))
3931 (c (string-to-number (match-string 2 dest
))))
3932 (org-goto-line (aref org-table-dlines l
))
3933 (org-table-goto-column c
)))
3934 (t (org-table-goto-column (string-to-number name
))))
3935 (move-marker pos
(point))
3936 (org-table-highlight-rectangle nil nil face2
))
3938 ((equal dest match
))
3943 (org-table-get-range match nil nil
'highlight
))
3945 ((setq e
(assoc var org-table-named-field-locations
))
3946 (org-goto-line (nth 1 e
))
3947 (org-table-goto-column (nth 2 e
))
3948 (org-table-highlight-rectangle (point) (point))
3949 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3950 ((setq e
(assoc var org-table-column-names
))
3951 (org-table-goto-column (string-to-number (cdr e
)))
3952 (org-table-highlight-rectangle (point) (point))
3953 (goto-char (org-table-begin))
3954 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3957 (goto-char (match-beginning 1))
3958 (org-table-highlight-rectangle)
3959 (message "Named column (column %s)" (cdr e
)))
3960 (user-error "Column name not found")))
3963 (org-table-goto-column (string-to-number (substring match
1)))
3964 (org-table-highlight-rectangle (point) (point))
3965 (message "Column %s" (substring match
1)))
3966 ((setq e
(assoc var org-table-local-parameters
))
3967 (goto-char (org-table-begin))
3968 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3970 (goto-char (match-beginning 1))
3971 (org-table-highlight-rectangle)
3972 (message "Local parameter."))
3973 (user-error "Parameter not found")))
3976 ((not var
) (user-error "No reference at point"))
3977 ((setq e
(assoc var org-table-formula-constants-local
))
3978 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3980 ((setq e
(assoc var org-table-formula-constants
))
3981 (message "Constant: $%s=%s in `org-table-formula-constants'."
3983 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3984 (message "Constant: $%s=%s, from `constants.el'%s."
3985 var e
(format " (%s units)" constants-unit-system
)))
3986 (t (user-error "Undefined name $%s" var
)))))
3988 (when (and org-show-positions
3989 (not (memq this-command
'(org-table-fedit-scroll
3990 org-table-fedit-scroll-down
))))
3991 (push pos org-show-positions
)
3992 (push org-table-current-begin-pos org-show-positions
)
3993 (let ((min (apply 'min org-show-positions
))
3994 (max (apply 'max org-show-positions
)))
3995 (set-window-start (selected-window) min
)
3997 (or (pos-visible-in-window-p max
)
3998 (set-window-start (selected-window) max
))))
3999 (select-window win
))))
4001 (defun org-table-force-dataline ()
4002 "Make sure the cursor is in a dataline in a table."
4003 (unless (save-excursion
4004 (beginning-of-line 1)
4005 (looking-at org-table-dataline-regexp
))
4006 (let* ((re org-table-dataline-regexp
)
4007 (p1 (save-excursion (re-search-forward re nil
'move
)))
4008 (p2 (save-excursion (re-search-backward re nil
'move
))))
4010 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4012 ((or p1 p2
) (goto-char (or p1 p2
)))
4013 (t (user-error "No table dataline around here"))))))
4015 (defun org-table-fedit-line-up ()
4016 "Move cursor one line up in the window showing the table."
4018 (org-table-fedit-move 'previous-line
))
4020 (defun org-table-fedit-line-down ()
4021 "Move cursor one line down in the window showing the table."
4023 (org-table-fedit-move 'next-line
))
4025 (defun org-table-fedit-move (command)
4026 "Move the cursor in the window showing the table.
4027 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4028 (let ((org-table-allow-automatic-line-recalculation nil
)
4029 (pos org-pos
) (win (selected-window)) p
)
4030 (select-window (get-buffer-window (marker-buffer org-pos
)))
4032 (call-interactively command
)
4033 (while (and (org-at-table-p)
4034 (org-at-table-hline-p))
4035 (call-interactively command
))
4036 (or (org-at-table-p) (goto-char p
))
4037 (move-marker pos
(point))
4038 (select-window win
)))
4040 (defun org-table-fedit-scroll (N)
4042 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4043 (scroll-other-window N
)))
4045 (defun org-table-fedit-scroll-down (N)
4047 (org-table-fedit-scroll (- N
)))
4049 (defvar org-table-rectangle-overlays nil
)
4051 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4052 "Add a new overlay."
4053 (let ((ov (make-overlay beg end
)))
4054 (overlay-put ov
'face
(or face
'secondary-selection
))
4055 (push ov org-table-rectangle-overlays
)))
4057 (defun org-table-highlight-rectangle (&optional beg end face
)
4058 "Highlight rectangular region in a table."
4059 (setq beg
(or beg
(point)) end
(or end
(point)))
4060 (let ((b (min beg end
))
4063 (and (boundp 'org-show-positions
)
4064 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4065 (goto-char (min beg end
))
4066 (setq l1
(org-current-line)
4067 c1
(org-table-current-column))
4068 (goto-char (max beg end
))
4069 (setq l2
(org-current-line)
4070 c2
(org-table-current-column))
4071 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
4073 (beginning-of-line 1)
4074 (loop for line from l1 to l2 do
4075 (when (looking-at org-table-dataline-regexp
)
4076 (org-table-goto-column c1
)
4077 (skip-chars-backward "^|\n") (setq beg
(point))
4078 (org-table-goto-column c2
)
4079 (skip-chars-forward "^|\n") (setq end
(point))
4080 (org-table-add-rectangle-overlay beg end face
))
4081 (beginning-of-line 2))
4083 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
4085 (defun org-table-remove-rectangle-highlight (&rest ignore
)
4086 "Remove the rectangle overlays."
4087 (unless org-inhibit-highlight-removal
4088 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4089 (mapc 'delete-overlay org-table-rectangle-overlays
)
4090 (setq org-table-rectangle-overlays nil
)))
4092 (defvar org-table-coordinate-overlays nil
4093 "Collects the coordinate grid overlays, so that they can be removed.")
4094 (make-variable-buffer-local 'org-table-coordinate-overlays
)
4096 (defun org-table-overlay-coordinates ()
4097 "Add overlays to the table at point, to show row/column coordinates."
4099 (mapc 'delete-overlay org-table-coordinate-overlays
)
4100 (setq org-table-coordinate-overlays nil
)
4102 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4103 (goto-char (org-table-begin))
4104 (while (org-at-table-p)
4105 (setq eol
(point-at-eol))
4106 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4107 (push ov org-table-coordinate-overlays
)
4108 (setq hline
(looking-at org-table-hline-regexp
))
4109 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4110 (format "%4d" (setq id
(1+ id
)))))
4111 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4114 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4115 (setq beg
(1+ (match-beginning 0))
4117 s1
(concat "$" (int-to-string ic
))
4118 s2
(org-number-to-letters ic
)
4119 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4120 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4121 (push ov org-table-coordinate-overlays
)
4122 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4123 (beginning-of-line 2)))))
4126 (defun org-table-toggle-coordinate-overlays ()
4127 "Toggle the display of Row/Column numbers in tables."
4129 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4130 (message "Tables Row/Column numbers display turned %s"
4131 (if org-table-overlay-coordinates
"on" "off"))
4132 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4134 (unless org-table-overlay-coordinates
4135 (mapc 'delete-overlay org-table-coordinate-overlays
)
4136 (setq org-table-coordinate-overlays nil
)))
4139 (defun org-table-toggle-formula-debugger ()
4140 "Toggle the formula debugger in tables."
4142 (setq org-table-formula-debug
(not org-table-formula-debug
))
4143 (message "Formula debugging has been turned %s"
4144 (if org-table-formula-debug
"on" "off")))
4146 ;;; The orgtbl minor mode
4148 ;; Define a minor mode which can be used in other modes in order to
4149 ;; integrate the org-mode table editor.
4151 ;; This is really a hack, because the org-mode table editor uses several
4152 ;; keys which normally belong to the major mode, for example the TAB and
4153 ;; RET keys. Here is how it works: The minor mode defines all the keys
4154 ;; necessary to operate the table editor, but wraps the commands into a
4155 ;; function which tests if the cursor is currently inside a table. If that
4156 ;; is the case, the table editor command is executed. However, when any of
4157 ;; those keys is used outside a table, the function uses `key-binding' to
4158 ;; look up if the key has an associated command in another currently active
4159 ;; keymap (minor modes, major mode, global), and executes that command.
4160 ;; There might be problems if any of the keys used by the table editor is
4161 ;; otherwise used as a prefix key.
4163 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4164 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4165 ;; addresses this by checking explicitly for both bindings.
4167 ;; The optimized version (see variable `orgtbl-optimized') takes over
4168 ;; all keys which are bound to `self-insert-command' in the *global map*.
4169 ;; Some modes bind other commands to simple characters, for example
4170 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4171 ;; active, this binding is ignored inside tables and replaced with a
4172 ;; modified self-insert.
4175 (defvar orgtbl-mode-map
(make-keymap)
4176 "Keymap for `orgtbl-mode'.")
4178 (defvar org-old-auto-fill-inhibit-regexp nil
4179 "Local variable used by `orgtbl-mode'.")
4181 (defconst orgtbl-line-start-regexp
4182 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4183 "Matches a line belonging to an orgtbl.")
4185 (defconst orgtbl-extra-font-lock-keywords
4186 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4187 0 (quote 'org-table
) 'prepend
))
4188 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4190 ;; Install it as a minor mode.
4191 (put 'orgtbl-mode
:included t
)
4192 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4195 (define-minor-mode orgtbl-mode
4196 "The `org-mode' table editor as a minor mode for use in other modes."
4197 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4198 (org-load-modules-maybe)
4200 ((derived-mode-p 'org-mode
)
4201 ;; Exit without error, in case some hook functions calls this
4202 ;; by accident in org-mode.
4203 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4205 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4206 ;; Make sure we are first in minor-mode-map-alist
4207 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4208 ;; FIXME: maybe it should use emulation-mode-map-alists?
4209 (and c
(setq minor-mode-map-alist
4210 (cons c
(delq c minor-mode-map-alist
)))))
4211 (org-set-local (quote org-table-may-need-update
) t
)
4212 (org-add-hook 'before-change-functions
'org-before-change-function
4214 (org-set-local 'org-old-auto-fill-inhibit-regexp
4215 auto-fill-inhibit-regexp
)
4216 (org-set-local 'auto-fill-inhibit-regexp
4217 (if auto-fill-inhibit-regexp
4218 (concat orgtbl-line-start-regexp
"\\|"
4219 auto-fill-inhibit-regexp
)
4220 orgtbl-line-start-regexp
))
4221 (add-to-invisibility-spec '(org-cwidth))
4222 (when (fboundp 'font-lock-add-keywords
)
4223 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4224 (org-restart-font-lock))
4225 (easy-menu-add orgtbl-mode-menu
))
4227 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4228 (org-table-cleanup-narrow-column-properties)
4229 (org-remove-from-invisibility-spec '(org-cwidth))
4230 (remove-hook 'before-change-functions
'org-before-change-function t
)
4231 (when (fboundp 'font-lock-remove-keywords
)
4232 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4233 (org-restart-font-lock))
4234 (easy-menu-remove orgtbl-mode-menu
)
4235 (force-mode-line-update 'all
))))
4237 (defun org-table-cleanup-narrow-column-properties ()
4238 "Remove all properties related to narrow-column invisibility."
4239 (let ((s (point-min)))
4240 (while (setq s
(text-property-any s
(point-max)
4241 'display org-narrow-column-arrow
))
4242 (remove-text-properties s
(1+ s
) '(display t
)))
4243 (setq s
(point-min))
4244 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4245 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4246 (setq s
(point-min))
4247 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4248 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4250 (defun orgtbl-make-binding (fun n
&rest keys
)
4251 "Create a function for binding in the table minor mode.
4252 FUN is the command to call inside a table. N is used to create a unique
4253 command name. KEYS are keys that should be checked in for a command
4254 to execute outside of tables."
4257 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4259 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4260 "Outside of tables, run the binding of `"
4261 (mapconcat #'key-description keys
"' or `")
4266 (list 'call-interactively
(list 'quote fun
))
4267 (list 'let
'(orgtbl-mode)
4268 (list 'call-interactively
4271 (list 'key-binding k
))
4273 '('orgtbl-error
))))))))
4275 (defun orgtbl-error ()
4276 "Error when there is no default binding for a table key."
4278 (user-error "This key has no function outside tables"))
4280 (defun orgtbl-setup ()
4281 "Setup orgtbl keymaps."
4284 '(([(meta shift left
)] org-table-delete-column
)
4285 ([(meta left
)] org-table-move-column-left
)
4286 ([(meta right
)] org-table-move-column-right
)
4287 ([(meta shift right
)] org-table-insert-column
)
4288 ([(meta shift up
)] org-table-kill-row
)
4289 ([(meta shift down
)] org-table-insert-row
)
4290 ([(meta up
)] org-table-move-row-up
)
4291 ([(meta down
)] org-table-move-row-down
)
4292 ("\C-c\C-w" org-table-cut-region
)
4293 ("\C-c\M-w" org-table-copy-region
)
4294 ("\C-c\C-y" org-table-paste-rectangle
)
4295 ("\C-c\C-w" org-table-wrap-region
)
4296 ("\C-c-" org-table-insert-hline
)
4297 ("\C-c}" org-table-toggle-coordinate-overlays
)
4298 ("\C-c{" org-table-toggle-formula-debugger
)
4299 ("\C-m" org-table-next-row
)
4300 ([(shift return
)] org-table-copy-down
)
4301 ("\C-c?" org-table-field-info
)
4302 ("\C-c " org-table-blank-field
)
4303 ("\C-c+" org-table-sum
)
4304 ("\C-c=" org-table-eval-formula
)
4305 ("\C-c'" org-table-edit-formulas
)
4306 ("\C-c`" org-table-edit-field
)
4307 ("\C-c*" org-table-recalculate
)
4308 ("\C-c^" org-table-sort-lines
)
4309 ("\M-a" org-table-beginning-of-field
)
4310 ("\M-e" org-table-end-of-field
)
4311 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4313 (while (setq elt
(pop bindings
))
4314 (setq nfunc
(1+ nfunc
))
4315 (setq key
(org-key (car elt
))
4317 cmd
(orgtbl-make-binding fun nfunc key
))
4318 (org-defkey orgtbl-mode-map key cmd
))
4320 ;; Special treatment needed for TAB and RET
4321 (org-defkey orgtbl-mode-map
[(return)]
4322 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4323 (org-defkey orgtbl-mode-map
"\C-m"
4324 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4326 (org-defkey orgtbl-mode-map
[(tab)]
4327 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4328 (org-defkey orgtbl-mode-map
"\C-i"
4329 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4331 (org-defkey orgtbl-mode-map
[(shift tab
)]
4332 (orgtbl-make-binding 'org-table-previous-field
104
4333 [(shift tab
)] [(tab)] "\C-i"))
4336 (unless (featurep 'xemacs
)
4337 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4338 (orgtbl-make-binding 'org-table-previous-field
107
4339 [S-iso-lefttab
] [backtab] [(shift tab)]
4342 (org-defkey orgtbl-mode-map [backtab]
4343 (orgtbl-make-binding 'org-table-previous-field
108
4344 [backtab] [S-iso-lefttab] [(shift tab)]
4347 (org-defkey orgtbl-mode-map "\M-\C-m"
4348 (orgtbl-make-binding 'org-table-wrap-region 105
4349 "\M-\C-m" [(meta return)]))
4350 (org-defkey orgtbl-mode-map [(meta return)]
4351 (orgtbl-make-binding 'org-table-wrap-region 106
4352 [(meta return)] "\M-\C-m"))
4354 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4355 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4357 (when orgtbl-optimized
4358 ;; If the user wants maximum table support, we need to hijack
4359 ;; some standard editing functions
4360 (org-remap orgtbl-mode-map
4361 'self-insert-command 'orgtbl-self-insert-command
4362 'delete-char 'org-delete-char
4363 'delete-backward-char 'org-delete-backward-char)
4364 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4365 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4367 ["Create or convert" org-table-create-or-convert-from-region
4368 :active (not (org-at-table-p)) :keys "C-c |" ]
4370 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4371 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4372 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4373 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4375 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4376 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4377 ["Copy Field from Above"
4378 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4381 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4382 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4383 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4384 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4386 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4387 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4388 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4389 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4390 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4392 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4394 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4395 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4396 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4397 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4400 ["Insert table template" orgtbl-insert-radio-table
4401 (assq major-mode orgtbl-radio-table-templates)]
4402 ["Comment/uncomment table" orgtbl-toggle-comment t])
4404 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4405 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4406 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4407 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4408 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4409 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4410 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4411 ["Sum Column/Rectangle" org-table-sum
4412 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4413 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4415 org-table-toggle-formula-debugger :active (org-at-table-p)
4417 :style toggle :selected org-table-formula-debug]
4418 ["Show Col/Row Numbers"
4419 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4421 :style toggle :selected org-table-overlay-coordinates]
4424 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4425 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4428 (defun orgtbl-ctrl-c-ctrl-c (arg)
4429 "If the cursor is inside a table, realign the table.
4430 If it is a table to be sent away to a receiver, do it.
4431 With prefix arg, also recompute table."
4433 (let ((case-fold-search t) (pos (point)) action)
4435 (beginning-of-line 1)
4437 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4438 ((looking-at "[ \t]*|") pos)
4439 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4443 (org-table-maybe-eval-formula)
4445 (call-interactively 'org-table-recalculate)
4446 (org-table-maybe-recalculate-line))
4447 (call-interactively 'org-table-align)
4448 (when (orgtbl-send-table 'maybe)
4449 (run-hooks 'orgtbl-after-send-table-hook)))
4450 ((eq action 'recalc)
4452 (beginning-of-line 1)
4453 (skip-chars-backward " \r\n\t")
4454 (if (org-at-table-p)
4455 (org-call-with-arg 'org-table-recalculate t))))
4456 (t (let (orgtbl-mode)
4457 (call-interactively (key-binding "\C-c\C-c")))))))
4459 (defun orgtbl-create-or-convert-from-region (arg)
4460 "Create table or convert region to table, if no conflicting binding.
4461 This installs the table binding `C-c |', but only if there is no
4462 conflicting binding to this key outside orgtbl-mode."
4464 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4466 (call-interactively cmd)
4467 (call-interactively 'org-table-create-or-convert-from-region))))
4469 (defun orgtbl-tab (arg)
4470 "Justification and field motion for `orgtbl-mode'."
4472 (if arg (org-table-edit-field t)
4473 (org-table-justify-field-maybe)
4474 (org-table-next-field)))
4476 (defun orgtbl-ret ()
4477 "Justification and field motion for `orgtbl-mode'."
4481 (org-table-justify-field-maybe)
4482 (org-table-next-row)))
4484 (defun orgtbl-self-insert-command (N)
4485 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4486 If the cursor is in a table looking at whitespace, the whitespace is
4487 overwritten, and the table is not marked as requiring realignment."
4489 (if (and (org-at-table-p)
4491 (and org-table-auto-blank-field
4492 (member last-command
4493 '(orgtbl-hijacker-command-100
4494 orgtbl-hijacker-command-101
4495 orgtbl-hijacker-command-102
4496 orgtbl-hijacker-command-103
4497 orgtbl-hijacker-command-104
4498 orgtbl-hijacker-command-105
4500 (org-table-blank-field))
4503 (looking-at "[^|\n]* +|"))
4504 (let (org-table-may-need-update)
4505 (goto-char (1- (match-end 0)))
4506 (org-delete-backward-char 1)
4507 (goto-char (match-beginning 0))
4508 (self-insert-command N))
4509 (setq org-table-may-need-update t)
4512 (cmd (or (key-binding
4513 (or (and (listp function-key-map)
4514 (setq a (assoc last-input-event function-key-map))
4516 (vector last-input-event)))
4517 'self-insert-command)))
4518 (call-interactively cmd)
4519 (if (and org-self-insert-cluster-for-undo
4520 (eq cmd 'self-insert-command))
4521 (if (not (eq last-command 'orgtbl-self-insert-command))
4522 (setq org-self-insert-command-undo-counter 1)
4523 (if (>= org-self-insert-command-undo-counter 20)
4524 (setq org-self-insert-command-undo-counter 1)
4525 (and (> org-self-insert-command-undo-counter 0)
4527 (not (cadr buffer-undo-list)) ; remove nil entry
4528 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4529 (setq org-self-insert-command-undo-counter
4530 (1+ org-self-insert-command-undo-counter))))))))
4533 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4534 "Regular expression matching exponentials as produced by calc.")
4536 (defun orgtbl-gather-send-defs ()
4537 "Gather a plist of :name, :transform, :params for each destination before
4540 (goto-char (org-table-begin))
4542 (beginning-of-line 0)
4543 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4544 (let ((name (org-no-properties (match-string 1)))
4545 (transform (intern (match-string 2)))
4546 (params (if (match-end 3)
4547 (read (concat "(" (match-string 3) ")")))))
4548 (push (list :name name :transform transform :params params)
4550 (beginning-of-line 0)))
4553 (defun orgtbl-send-replace-tbl (name txt)
4554 "Find and replace table NAME with TXT."
4556 (goto-char (point-min))
4557 (unless (re-search-forward
4558 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4559 (user-error "Don't know where to insert translated table"))
4560 (let ((beg (line-beginning-position 2)))
4561 (unless (re-search-forward
4562 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4563 (user-error "Cannot find end of insertion region"))
4565 (delete-region beg (point)))
4569 (defun org-table-to-lisp (&optional txt)
4570 "Convert the table at point to a Lisp structure.
4571 The structure will be a list. Each item is either the symbol `hline'
4572 for a horizontal separator line, or a list of field values as strings.
4573 The table is taken from the parameter TXT, or from the buffer at point."
4574 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4576 (buffer-substring-no-properties (org-table-begin)
4579 (if (string-match org-table-hline-regexp x) 'hline
4580 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4581 (org-split-string txt "[ \t]*\n[ \t]*"))))
4583 (defun orgtbl-send-table (&optional maybe)
4584 "Send a transformed version of table at point to the receiver position.
4585 With argument MAYBE, fail quietly if no transformation is defined
4589 (unless (org-at-table-p) (user-error "Not at a table"))
4590 ;; when non-interactive, we assume align has just happened.
4591 (when (org-called-interactively-p 'any) (org-table-align))
4592 (let ((dests (orgtbl-gather-send-defs))
4593 (table (org-table-to-lisp
4594 (buffer-substring-no-properties (org-table-begin)
4598 (if maybe (throw 'exit nil)
4599 (user-error "Don't know how to transform this table")))
4600 (dolist (dest dests)
4601 (let ((name (plist-get dest :name))
4602 (transform (plist-get dest :transform))
4603 (params (plist-get dest :params)))
4604 (unless (fboundp transform)
4605 (user-error "No such transformation function %s" transform))
4606 (orgtbl-send-replace-tbl name (funcall transform table params)))
4608 (message "Table converted and installed at %d receiver location%s"
4609 ntbl (if (> ntbl 1) "s" ""))
4610 (and (> ntbl 0) ntbl))))
4612 (defun org-remove-by-index (list indices &optional i0)
4613 "Remove the elements in LIST with indices in INDICES.
4614 First element has index 0, or I0 if given."
4617 (if (integerp indices) (setq indices (list indices)))
4618 (setq i0 (1- (or i0 0)))
4619 (delq :rm (mapcar (lambda (x)
4621 (if (memq i0 indices) :rm x))
4624 (defun orgtbl-toggle-comment ()
4625 "Comment or uncomment the orgtbl at point."
4627 (let* ((case-fold-search t)
4628 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4629 (re2 (concat "^" orgtbl-line-start-regexp))
4630 (commented (save-excursion (beginning-of-line 1)
4631 (cond ((looking-at re1) t)
4632 ((looking-at re2) nil)
4633 (t (user-error "Not at an org table")))))
4634 (re (if commented re1 re2))
4637 (beginning-of-line 1)
4638 (while (looking-at re) (beginning-of-line 0))
4639 (beginning-of-line 2)
4641 (while (looking-at re) (beginning-of-line 2))
4643 (comment-region beg end (if commented '(4) nil))))
4645 (defun orgtbl-insert-radio-table ()
4646 "Insert a radio table template appropriate for this major mode."
4648 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4651 (unless e (user-error "No radio table setup defined for %s" major-mode))
4652 (setq name (read-string "Table name: "))
4653 (while (string-match "%n" txt)
4654 (setq txt (replace-match name t t txt)))
4655 (or (bolp) (insert "\n"))
4661 (defun orgtbl-to-generic (table params)
4662 "Convert the orgtbl-mode TABLE to some other format.
4664 This generic routine can be used for many standard cases.
4666 TABLE is a list, each entry either the symbol `hline' for
4667 a horizontal separator line, or a list of fields for that
4668 line. PARAMS is a property list of parameters that can
4669 influence the conversion.
4671 Valid parameters are:
4675 Export back-end used as a basis to transcode elements of the
4676 table, when no specific parameter applies to it. It is also
4677 used to translate cells contents. You can prevent this by
4678 setting :raw property to a non-nil value.
4682 When non-nil, only convert rows, not the table itself. This is
4683 equivalent to setting to the empty string both :tstart
4684 and :tend, which see.
4688 When set to an integer N, skip the first N lines of the table.
4689 Horizontal separation lines do count for this parameter!
4693 List of columns that should be skipped. If the table has
4694 a column with calculation marks, that column is automatically
4695 discarded beforehand.
4699 String to be inserted on horizontal separation lines. May be
4700 nil to ignore these lines altogether.
4704 Separator between two fields, as a string.
4706 Each in the following group may be either a string or a function
4707 of no arguments returning a string:
4711 Strings to start and end the table. Ignored when :splice is t.
4715 Strings to start and end a new table line.
4719 Strings to start and end the last table line. Default,
4720 respectively, to :lstart and :lend.
4722 Each in the following group may be a string or a function of one
4723 argument (either the cells in the current row, as a list of
4724 strings, or the current cell) returning a string:
4728 Format string for an entire row, with enough %s to capture all
4729 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4733 Format for the entire last line, defaults to :lfmt.
4737 A format to be used to wrap the field, should contain %s for
4738 the original field value. For example, to wrap everything in
4739 dollars, you could use :fmt \"$%s$\". This may also be
4740 a property list with column numbers and format strings, or
4743 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4745 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4747 Same as above, specific for the header lines in the table.
4748 All lines before the first hline are treated as header. If
4749 any of these is not present, the data line value is used.
4751 This may be either a string or a function of two arguments:
4755 Use this format to print numbers with exponential. The format
4756 should have %s twice for inserting mantissa and exponent, for
4757 example \"%s\\\\times10^{%s}\". This may also be a property
4758 list with column numbers and format strings or functions.
4759 :fmt will still be applied after :efmt."
4760 (let ((backend (plist-get params :backend))
4761 ;; Disable user-defined export filters and hooks.
4762 (org-export-filters-alist nil)
4763 (org-export-before-parsing-hook nil)
4764 (org-export-before-processing-hook nil))
4765 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4766 (user-error "Unknown :backend value"))
4767 (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
4769 (org-export-string-as
4770 ;; Return TABLE as Org syntax. Tolerate non-string cells.
4771 (with-output-to-string
4773 (cond ((eq e 'hline) (princ "|--\n"))
4775 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4777 ;; Build a custom back-end according to PARAMS. Before defining
4778 ;; a translator, check if there is anything to do. When there
4779 ;; isn't, let BACKEND handle the element.
4780 (org-export-create-backend
4781 :parent (or backend 'org)
4783 '((:filter-parse-tree
4784 ;; Handle :skip parameter.
4785 (lambda (tree backend info)
4786 (let ((skip (plist-get info :skip)))
4788 (unless (wholenump skip) (user-error "Wrong :skip value"))
4790 (org-element-map tree 'table-row
4793 (org-element-extract-element row)
4798 ;; Handle :skipcols parameter.
4799 (lambda (tree backend info)
4800 (let ((skipcols (plist-get info :skipcols)))
4802 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4803 (org-element-map tree 'table
4806 (org-export-table-has-special-column-p table)))
4807 (dolist (row (org-element-contents table))
4808 (when (eq (org-element-property :type row) 'standard)
4810 (dolist (cell (nthcdr (if specialp 1 0)
4811 (org-element-contents row)))
4812 (when (memq c skipcols)
4813 (org-element-extract-element cell))
4818 `((table . ,(org-table--to-generic-table params))
4819 (table-row . ,(org-table--to-generic-row params))
4820 (table-cell . ,(org-table--to-generic-cell params))
4821 ;; Section. Return contents to avoid garbage around table.
4822 (section . (lambda (s c i) c))))
4823 'body-only (org-combine-plists params '(:with-tables t))))))
4825 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4826 (cond ((null value) nil)
4827 ((functionp value) `(funcall ',value ,@args))
4829 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4830 (args `(format ,value ,@args))
4832 ((and with-cons (consp value))
4833 `(let ((val (cadr (memq column ',value))))
4834 (cond ((null val) contents)
4835 ((stringp val) (format val ,@args))
4836 ((functionp val) (funcall val ,@args))
4837 (t (user-error "Wrong %s value" ,name)))))
4838 (t (user-error "Wrong %s value" name))))
4840 (defun org-table--to-generic-table (params)
4841 "Return custom table transcoder according to PARAMS.
4842 PARAMS is a plist. See `orgtbl-to-generic' for more
4844 (let ((backend (plist-get params :backend))
4845 (splice (plist-get params :splice))
4846 (tstart (plist-get params :tstart))
4847 (tend (plist-get params :tend)))
4848 `(lambda (table contents info)
4850 ,(and tstart (not splice)
4851 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4852 ,(if (or (not backend) tstart tend splice) 'contents
4853 `(org-export-with-backend ',backend table contents info))
4854 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4856 (defun org-table--to-generic-row (params)
4857 "Return custom table row transcoder according to PARAMS.
4858 PARAMS is a plist. See `orgtbl-to-generic' for more
4860 (let* ((backend (plist-get params :backend))
4861 (lstart (plist-get params :lstart))
4862 (llstart (plist-get params :llstart))
4863 (hlstart (plist-get params :hlstart))
4864 (hllstart (plist-get params :hllstart))
4865 (lend (plist-get params :lend))
4866 (llend (plist-get params :llend))
4867 (hlend (plist-get params :hlend))
4868 (hllend (plist-get params :hllend))
4869 (lfmt (plist-get params :lfmt))
4870 (llfmt (plist-get params :llfmt))
4871 (hlfmt (plist-get params :hlfmt))
4872 (hllfmt (plist-get params :hllfmt)))
4873 `(lambda (row contents info)
4874 (if (eq (org-element-property :type row) 'rule)
4876 ((plist-member params :hline)
4877 (org-table--generic-apply (plist-get params :hline) ":hline"))
4878 (backend `(org-export-with-backend ',backend row nil info)))
4879 (let ((headerp (org-export-table-row-in-header-p row info))
4880 (lastp (not (org-export-get-next-element row info)))
4881 (last-header-p (org-export-table-row-ends-header-p row info)))
4883 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4884 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4885 ;; `:lstart', `:lend' and their relatives.
4887 '(org-element-map row 'table-cell
4889 ;; Export all cells, without separators.
4891 ;; Use `org-export-data-with-backend'
4892 ;; instead of `org-export-data' to eschew
4893 ;; cached values, which
4894 ;; ignore :orgtbl-ignore-sep parameter.
4895 (org-export-data-with-backend
4897 (plist-get info :back-end)
4898 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4902 `(last-header-p ,(org-table--generic-apply
4903 hllfmt ":hllfmt" nil cells)))
4905 `(headerp ,(org-table--generic-apply
4906 hlfmt ":hlfmt" nil cells)))
4908 `(lastp ,(org-table--generic-apply
4909 llfmt ":llfmt" nil cells)))
4911 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4915 (or hllstart hllend)
4918 ,(org-table--generic-apply hllstart ":hllstart")
4920 ,(org-table--generic-apply hllend ":hllend"))))
4925 ,(org-table--generic-apply hlstart ":hlstart")
4927 ,(org-table--generic-apply hlend ":hlend"))))
4932 ,(org-table--generic-apply llstart ":llstart")
4934 ,(org-table--generic-apply llend ":llend"))))
4939 ,(org-table--generic-apply lstart ":lstart")
4941 ,(org-table--generic-apply lend ":lend")))
4943 `(org-export-with-backend
4944 ',backend row contents info))
4945 (t 'contents)))))))))))))))
4947 (defun org-table--to-generic-cell (params)
4948 "Return custom table cell transcoder according to PARAMS.
4949 PARAMS is a plist. See `orgtbl-to-generic' for more
4951 (let* ((backend (plist-get params :backend))
4952 (efmt (plist-get params :efmt))
4953 (fmt (plist-get params :fmt))
4954 (hfmt (plist-get params :hfmt))
4955 (sep (plist-get params :sep))
4956 (hsep (plist-get params :hsep)))
4957 `(lambda (cell contents info)
4958 (let ((headerp (org-export-table-row-in-header-p
4959 (org-export-get-parent-element cell) info))
4960 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4961 ;; Make sure that contents are exported as Org data when :raw
4962 ;; parameter is non-nil.
4963 ,(when (and backend (plist-get params :raw))
4965 ;; Since we don't know what are the pseudo object
4966 ;; types defined in backend, we cannot pass them to
4967 ;; `org-element-interpret-data'. As a consequence,
4968 ;; they will be treated as pseudo elements, and
4969 ;; will have newlines appended instead of spaces.
4970 ;; Therefore, we must make sure :post-blank value
4971 ;; is really turned into spaces.
4972 (replace-regexp-in-string
4975 (org-element-interpret-data
4976 (org-element-contents cell))))))
4978 ;; Check if we can apply `:efmt' on CONTENTS.
4980 `(when (string-match orgtbl-exp-regexp contents)
4981 (let ((mantissa (match-string 1 contents))
4982 (exponent (match-string 2 contents)))
4983 (setq contents ,(org-table--generic-apply
4984 efmt ":efmt" t 'mantissa 'exponent)))))
4985 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
4987 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
4988 hfmt ":hfmt" t 'contents))))
4989 ,(and fmt `(t (setq contents ,(org-table--generic-apply
4990 fmt ":fmt" t 'contents))))))
4991 ;; If a separator is provided, use it instead of BACKEND's.
4992 ;; Separators are ignored when LFMT (or equivalent) is
4996 `(if (or ,(and (not sep) '(not headerp))
4997 (plist-get info :orgtbl-ignore-sep)
4998 (not (org-export-get-next-element cell info)))
4999 ,(if (not backend) 'contents
5000 `(org-export-with-backend ',backend cell contents info))
5002 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5004 (backend `(org-export-with-backend ',backend cell contents info))
5008 (defun orgtbl-to-tsv (table params)
5009 "Convert the orgtbl-mode table to TAB separated material."
5010 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5013 (defun orgtbl-to-csv (table params)
5014 "Convert the orgtbl-mode table to CSV material.
5015 This does take care of the proper quoting of fields with comma or quotes."
5016 (orgtbl-to-generic table
5017 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5021 (defun orgtbl-to-latex (table params)
5022 "Convert the orgtbl-mode TABLE to LaTeX.
5024 TABLE is a list, each entry either the symbol `hline' for
5025 a horizontal separator line, or a list of fields for that line.
5026 PARAMS is a property list of parameters that can influence the
5027 conversion. All parameters from `orgtbl-to-generic' are
5028 supported. It is also possible to use the following ones:
5032 When non-nil, use formal \"booktabs\" style.
5036 Specify environment to use, as a string. If you use
5037 \"longtable\", you may also want to specify :language property,
5038 as a string, to get proper continuation strings."
5043 ;; Provide sane default values.
5044 (list :backend 'latex
5045 :latex-default-table-mode 'table
5046 :latex-tables-centered nil
5047 :latex-tables-booktabs (plist-get params :booktabs)
5048 :latex-table-scientific-notation nil
5049 :latex-default-table-environment
5050 (or (plist-get params :environment) "tabular"))
5054 (defun orgtbl-to-html (table params)
5055 "Convert the orgtbl-mode TABLE to HTML.
5057 TABLE is a list, each entry either the symbol `hline' for
5058 a horizontal separator line, or a list of fields for that line.
5059 PARAMS is a property list of parameters that can influence the
5060 conversion. All parameters from `orgtbl-to-generic' are
5061 supported. It is also possible to use the following one:
5065 Attributes and values, as a plist, which will be used in
5071 ;; Provide sane default values.
5072 (list :backend 'html
5073 :html-table-data-tags '("<td%s>" . "</td>")
5074 :html-table-use-header-tags-for-first-column nil
5075 :html-table-align-individual-fields t
5076 :html-table-row-tags '("<tr>" . "</tr>")
5077 :html-table-attributes
5078 (if (plist-member params :attributes)
5079 (plist-get params :attributes)
5080 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5085 (defun orgtbl-to-texinfo (table params)
5086 "Convert the orgtbl-mode TABLE to Texinfo.
5088 TABLE is a list, each entry either the symbol `hline' for
5089 a horizontal separator line, or a list of fields for that line.
5090 PARAMS is a property list of parameters that can influence the
5091 conversion. All parameters from `orgtbl-to-generic' are
5092 supported. It is also possible to use the following one:
5096 Column widths, as a string. When providing column fractions,
5097 \"@columnfractions\" command can be omitted."
5098 (require 'ox-texinfo)
5103 (list :backend 'texinfo
5104 :texinfo-tables-verbatim nil
5105 :texinfo-table-scientific-notation nil)
5107 (columns (let ((w (plist-get params :columns)))
5109 ((org-string-match-p "{\\|@columnfractions " w) w)
5110 (t (concat "@columnfractions " w))))))
5111 (if (not columns) output
5112 (replace-regexp-in-string
5113 "@multitable \\(.*\\)" columns output t nil 1))))
5116 (defun orgtbl-to-orgtbl (table params)
5117 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5119 TABLE is a list, each entry either the symbol `hline' for
5120 a horizontal separator line, or a list of fields for that line.
5121 PARAMS is a property list of parameters that can influence the
5122 conversion. All parameters from `orgtbl-to-generic' are
5125 Useful when slicing one table into many. The :hline, :sep,
5126 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5127 be set to provide ORGTBL directives for the generated table."
5129 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5131 (defun orgtbl-to-table.el (table params)
5132 "Convert the orgtbl-mode TABLE into a table.el table.
5133 TABLE is a list, each entry either the symbol `hline' for
5134 a horizontal separator line, or a list of fields for that line.
5135 PARAMS is a property list of parameters that can influence the
5136 conversion. All parameters from `orgtbl-to-generic' are
5139 (insert (orgtbl-to-orgtbl table params))
5141 (replace-regexp-in-string
5143 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5145 (defun orgtbl-to-unicode (table params)
5146 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5148 TABLE is a list, each entry either the symbol `hline' for
5149 a horizontal separator line, or a list of fields for that line.
5150 PARAMS is a property list of parameters that can influence the
5151 conversion. All parameters from `orgtbl-to-generic' are
5152 supported. It is also possible to use the following ones:
5156 When non-nil, use \"ascii-art-to-unicode\" package to translate
5157 the table. You can download it here:
5158 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5162 When non-nil, narrow columns width than provided width cookie,
5163 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5168 (list :backend 'ascii
5169 :ascii-charset 'utf-8
5170 :ascii-table-widen-columns (not (plist-get params :narrow))
5171 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5174 ;; Put the cursor in a column containing numerical values
5175 ;; of an Org-Mode table,
5177 ;; A new column is added with a bar plot.
5178 ;; When the table is refreshed (C-u C-c *),
5179 ;; the plot is updated to reflect the new values.
5181 (defun orgtbl-ascii-draw (value min max &optional width characters)
5182 "Draw an ascii bar in a table.
5183 VALUE is a the value to plot, the width of the bar to draw. A
5184 value equal to MIN will be displayed as empty (zero width bar).
5185 A value equal to MAX will draw a bar filling all the WIDTH.
5186 WIDTH is the expected width in characters of the column.
5187 CHARACTERS is a string that will compose the bar, with shades of
5188 grey from pure white to pure black. It defaults to a 10
5189 characters string of regular ascii characters."
5190 (let* ((characters (or characters " .:;c!lhVHW"))
5191 (width (or width 12))
5192 (value (if (numberp value) value (string-to-number value)))
5193 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5195 ((< value 0) "too small")
5196 ((> value width) "too large")
5198 (let ((len (1- (length characters))))
5200 (make-string (floor value) (elt characters len))
5201 (string (elt characters
5202 (floor (* (- value (floor value)) len))))))))))
5205 (defun orgtbl-ascii-plot (&optional ask)
5206 "Draw an ascii bar plot in a column.
5207 With cursor in a column containing numerical values, this
5208 function will draw a plot in a new column.
5209 ASK, if given, is a numeric prefix to override the default 12
5210 characters width of the plot. ASK may also be the
5211 \\[universal-argument] prefix, which will prompt for the width."
5213 (let ((col (org-table-current-column))
5214 (min 1e999) ; 1e999 will be converted to infinity
5215 (max -1e999) ; which is the desired result
5216 (table (org-table-to-lisp))
5219 (read-number "Length of column " 12))
5222 ;; Skip any hline a the top of table.
5223 (while (eq (car table) 'hline) (setq table (cdr table)))
5224 ;; Skip table header if any.
5225 (dolist (x (or (cdr (memq 'hline table)) table))
5227 (setq x (nth (1- col) x))
5229 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5231 (setq x (string-to-number x))
5232 (when (> min x) (setq min x))
5233 (when (< max x) (setq max x)))))
5234 (org-table-insert-column)
5235 (org-table-move-column-right)
5236 (org-table-store-formulas
5239 (number-to-string (1+ col))
5240 (format "'(%s $%s %s %s %s)"
5241 "orgtbl-ascii-draw" col min max length))
5242 (org-table-get-stored-formulas)))
5243 (org-table-recalculate t)))
5245 ;; Example of extension: unicode characters
5246 ;; Here are two examples of different styles.
5248 ;; Unicode block characters are used to give a smooth effect.
5249 ;; See http://en.wikipedia.org/wiki/Block_Elements
5250 ;; Use one of those drawing functions
5251 ;; - orgtbl-ascii-draw (the default ascii)
5252 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5253 ;; - orgtbl-uc-draw-cont (smooth unicode)
5255 ;; This is best viewed with the "DejaVu Sans Mono" font
5256 ;; (use M-x set-default-font).
5258 (defun orgtbl-uc-draw-grid (value min max &optional width)
5259 "Draw a bar in a table using block unicode characters.
5260 It is a variant of orgtbl-ascii-draw with Unicode block
5261 characters, for a smooth display. Bars appear as grids (to the
5262 extent the font allows)."
5263 ;; http://en.wikipedia.org/wiki/Block_Elements
5264 ;; best viewed with the "DejaVu Sans Mono" font.
5265 (orgtbl-ascii-draw value min max width
5266 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5268 (defun orgtbl-uc-draw-cont (value min max &optional width)
5269 "Draw a bar in a table using block unicode characters.
5270 It is a variant of orgtbl-ascii-draw with Unicode block
5271 characters, for a smooth display. Bars are solid (to the extent
5273 (orgtbl-ascii-draw value min max width
5274 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5276 (defun org-table-get-remote-range (name-or-id form)
5277 "Get a field value or a list of values in a range from table at ID.
5279 NAME-OR-ID may be the name of a table in the current file as set
5280 by a \"#+NAME:\" directive. The first table following this line
5281 will then be used. Alternatively, it may be an ID referring to
5282 any entry, also in a different file. In this case, the first
5283 table in that entry will be referenced.
5284 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5285 \"@I$2..@II$2\". All the references must be absolute, not relative.
5287 The return value is either a single string for a single field, or a
5288 list of the fields in the rectangle."
5290 (let ((case-fold-search t) (id-loc nil)
5291 ;; Protect a bunch of variables from being overwritten
5292 ;; by the context of the remote table
5293 org-table-column-names org-table-column-name-regexp
5294 org-table-local-parameters org-table-named-field-locations
5295 org-table-current-line-types org-table-current-begin-line
5296 org-table-current-begin-pos org-table-dlines
5297 org-table-current-ncol
5298 org-table-hlines org-table-last-alignment
5299 org-table-last-column-widths org-table-last-alignment
5300 org-table-last-column-widths tbeg
5302 (setq form (org-table-convert-refs-to-rc form))
5307 (goto-char (point-min))
5308 (if (re-search-forward
5309 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5310 (regexp-quote name-or-id) "[ \t]*$")
5312 (setq buffer (current-buffer) loc (match-beginning 0))
5313 (setq id-loc (org-id-find name-or-id 'marker))
5314 (unless (and id-loc (markerp id-loc))
5315 (user-error "Can't find remote table \"%s\"" name-or-id))
5316 (setq buffer (marker-buffer id-loc)
5317 loc (marker-position id-loc))
5318 (move-marker id-loc nil)))
5319 (with-current-buffer buffer
5325 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5326 (not (match-beginning 1)))
5327 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5328 (setq tbeg (point-at-bol))
5329 (org-table-get-specials)
5330 (setq form (org-table-formula-substitute-names
5331 (org-table-formula-handle-first/last-rc form)))
5332 (if (and (string-match org-table-range-regexp form)
5333 (> (length (match-string 0 form)) 1))
5335 (org-table-get-range (match-string 0 form) tbeg 1))
5338 (defun org-table-remote-reference-indirection (form)
5339 "Return formula with table remote references substituted by indirection.
5340 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5341 This indirection works only with the format @ROW$COLUMN. The
5342 format \"B3\" is not supported because it can not be
5343 distinguished from a plain table name or ID."
5345 (while (string-match (concat
5346 ;; Same as in `org-table-eval-formula'.
5347 "\\<remote([ \t]*\\("
5348 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5350 ;; Same as in `org-table-eval-formula'.
5351 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5354 ;; The position of the character as far as possible to the right
5355 ;; that will not be replaced and particularly not be shifted by
5357 (setq start (match-beginning 1))
5358 ;; Substitute the remote reference with the value found in the
5363 (org-table-get-range (org-table-formula-handle-first/last-rc
5364 (match-string 1 form))))
5368 (defmacro org-define-lookup-function (mode)
5369 (let ((mode-str (symbol-name mode))
5370 (first-p (equal mode 'first))
5371 (all-p (equal mode 'all)))
5372 (let ((plural-str (if all-p "s" "")))
5373 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5374 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5375 If R-LIST is nil, return matching element%s of S-LIST.
5376 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5377 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5378 This function is generated by a call to the macro `org-define-lookup-function'."
5379 mode-str plural-str plural-str plural-str)
5380 (let ,(let ((lvars '((p (or predicate 'equal))
5382 (rl (or r-list s-list))
5384 (if first-p (add-to-list 'lvars '(match-p nil)))
5386 (while ,(if first-p '(and (not match-p) sl) 'sl)
5388 (if (funcall p val (car sl))
5390 ,(if first-p '(setq match-p t))
5391 (let ((rval (car rl)))
5392 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5393 (setq sl (cdr sl) rl (cdr rl))))
5396 (org-define-lookup-function first)
5397 (org-define-lookup-function last)
5398 (org-define-lookup-function all)
5400 (provide 'org-table)
5403 ;; generated-autoload-file: "org-loaddefs.el"
5406 ;;; org-table.el ends here