1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org-mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org-mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
41 (declare-function org-export-string-as
"ox"
42 (string backend
&optional body-only ext-plist
))
43 (declare-function aa2u
"ext:ascii-art-to-unicode" ())
44 (defvar orgtbl-mode
) ; defined below
45 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
46 (defvar constants-unit-system
)
47 (defvar org-table-follow-field-mode
)
49 (defvar orgtbl-after-send-table-hook nil
50 "Hook for functions attaching to `C-c C-c', if the table is sent.
51 This can be used to add additional functionality after the table is sent
52 to the receiver position, otherwise, if table is not sent, the functions
55 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
56 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
57 In the optimized version, the table editor takes over all simple keys that
58 normally just insert a character. In tables, the characters are inserted
59 in a way to minimize disturbing the table structure (i.e. in overwrite mode
60 for empty fields). Outside tables, the correct binding of the keys is
63 The default for this option is t if the optimized version is also used in
64 Org-mode. See the variable `org-enable-table-editor' for details. Changing
65 this variable requires a restart of Emacs to become effective."
69 (defcustom orgtbl-radio-table-templates
70 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
71 % END RECEIVE ORGTBL %n
73 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
76 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
77 @c END RECEIVE ORGTBL %n
79 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
83 <!-- END RECEIVE ORGTBL %n -->
85 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
88 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
89 #+ END RECEIVE ORGTBL %n
91 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
94 "Templates for radio tables in different major modes.
95 All occurrences of %n in a template will be replaced with the name of the
96 table, obtained by prompting the user."
99 (list (symbol :tag
"Major mode")
100 (string :tag
"Format"))))
102 (defgroup org-table-settings nil
103 "Settings for tables in Org-mode."
104 :tag
"Org Table Settings"
107 (defcustom org-table-default-size
"5x2"
108 "The default size for newly created tables, Columns x Rows."
109 :group
'org-table-settings
112 (defcustom org-table-number-regexp
113 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
114 "Regular expression for recognizing numbers in table columns.
115 If a table column contains mostly numbers, it will be aligned to the
116 right. If not, it will be aligned to the left.
118 The default value of this option is a regular expression which allows
119 anything which looks remotely like a number as used in scientific
120 context. For example, all of the following will be considered a
122 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
124 Other options offered by the customize interface are more restrictive."
125 :group
'org-table-settings
127 (const :tag
"Positive Integers"
129 (const :tag
"Integers"
131 (const :tag
"Floating Point Numbers"
132 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
133 (const :tag
"Floating Point Number or Integer"
134 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
135 (const :tag
"Exponential, Floating point, Integer"
136 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
137 (const :tag
"Very General Number-Like, including hex and Calc radix"
138 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
139 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
140 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
141 (string :tag
"Regexp:")))
143 (defcustom org-table-number-fraction
0.5
144 "Fraction of numbers in a column required to make the column align right.
145 In a column all non-white fields are considered. If at least
146 this fraction of fields is matched by `org-table-number-regexp',
147 alignment to the right border applies."
148 :group
'org-table-settings
151 (defgroup org-table-editing nil
152 "Behavior of tables during editing in Org-mode."
153 :tag
"Org Table Editing"
156 (defcustom org-table-automatic-realign t
157 "Non-nil means automatically re-align table when pressing TAB or RETURN.
158 When nil, aligning is only done with \\[org-table-align], or after column
160 :group
'org-table-editing
163 (defcustom org-table-auto-blank-field t
164 "Non-nil means automatically blank table field when starting to type into it.
165 This only happens when typing immediately after a field motion
166 command (TAB, S-TAB or RET).
167 Only relevant when `org-enable-table-editor' is equal to `optimized'."
168 :group
'org-table-editing
171 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
172 "Non-nil means automatically exit the follow mode.
173 When nil, the follow mode will stay on and be active in any table
174 the cursor enters. Since the table follow filed mode messes with the
175 window configuration, it is not recommended to set this variable to nil,
176 except maybe locally in a special file that has mostly tables with long
182 (defcustom org-table-fix-formulas-confirm nil
183 "Whether the user should confirm when Org fixes formulas."
184 :group
'org-table-editing
187 (const :tag
"with yes-or-no" yes-or-no-p
)
188 (const :tag
"with y-or-n" y-or-n-p
)
189 (const :tag
"no confirmation" nil
)))
190 (put 'org-table-fix-formulas-confirm
192 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
194 (defcustom org-table-tab-jumps-over-hlines t
195 "Non-nil means tab in the last column of a table with jump over a hline.
196 If a horizontal separator line is following the current line,
197 `org-table-next-field' can either create a new row before that line, or jump
198 over the line. When this option is nil, a new line will be created before
200 :group
'org-table-editing
203 (defgroup org-table-calculation nil
204 "Options concerning tables in Org-mode."
205 :tag
"Org Table Calculation"
208 (defcustom org-table-use-standard-references
'from
209 "Should org-mode work with table references like B3 instead of @3$2?
212 from accept as input, do not present for editing
213 t accept as input and present for editing"
214 :group
'org-table-calculation
216 (const :tag
"Never, don't even check user input for them" nil
)
217 (const :tag
"Always, both as user input, and when editing" t
)
218 (const :tag
"Convert user input, don't offer during editing" from
)))
220 (defcustom org-table-copy-increment t
221 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
222 :group
'org-table-calculation
225 (defcustom org-calc-default-modes
226 '(calc-internal-prec 12
227 calc-float-format
(float 8)
230 calc-symbolic-mode nil
231 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
232 calc-display-working-message t
234 "List with Calc mode settings for use in `calc-eval' for table formulas.
235 The list must contain alternating symbols (Calc modes variables and values).
236 Don't remove any of the default settings, just change the values. Org-mode
237 relies on the variables to be present in the list."
238 :group
'org-table-calculation
241 (defcustom org-table-duration-custom-format
'hours
242 "Format for the output of calc computations like $1+$2;t.
243 The default value is 'hours, and will output the results as a
244 number of hours. Other allowed values are 'seconds, 'minutes and
245 'days, and the output will be a fraction of seconds, minutes or
247 :group
'org-table-calculation
249 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
250 (symbol :tag
"Minutes" 'minutes
)
251 (symbol :tag
"Hours " 'hours
)
252 (symbol :tag
"Days " 'days
)))
254 (defcustom org-table-formula-field-format
"%s"
255 "Format for fields which contain the result of a formula.
256 For example, using \"~%s~\" will display the result within tilde
257 characters. Beware that modifying the display can prevent the
258 field from being used in another formula."
259 :group
'org-table-settings
263 (defcustom org-table-formula-evaluate-inline t
264 "Non-nil means TAB and RET evaluate a formula in current table field.
265 If the current field starts with an equal sign, it is assumed to be a formula
266 which should be evaluated as described in the manual and in the documentation
267 string of the command `org-table-eval-formula'. This feature requires the
269 When this variable is nil, formula calculation is only available through
270 the command \\[org-table-eval-formula]."
271 :group
'org-table-calculation
274 (defcustom org-table-formula-use-constants t
275 "Non-nil means interpret constants in formulas in tables.
276 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
277 by the value given in `org-table-formula-constants', or by a value obtained
278 from the `constants.el' package."
279 :group
'org-table-calculation
282 (defcustom org-table-formula-constants nil
283 "Alist with constant names and values, for use in table formulas.
284 The car of each element is a name of a constant, without the `$' before it.
285 The cdr is the value as a string. For example, if you'd like to use the
286 speed of light in a formula, you would configure
288 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
290 and then use it in an equation like `$1*$c'.
292 Constants can also be defined on a per-file basis using a line like
294 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
295 :group
'org-table-calculation
297 (cons (string :tag
"name")
298 (string :tag
"value"))))
300 (defcustom org-table-allow-automatic-line-recalculation t
301 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
302 Automatically means when TAB or RET or C-c C-c are pressed in the line."
303 :group
'org-table-calculation
306 (defcustom org-table-error-on-row-ref-crossing-hline t
307 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
311 (defcustom org-table-relative-ref-may-cross-hline t
312 "Non-nil means relative formula references may cross hlines.
313 Here are the allowed values:
315 nil Relative references may not cross hlines. They will reference the
316 field next to the hline instead. Coming from below, the reference
317 will be to the field below the hline. Coming from above, it will be
319 t Relative references may cross hlines.
320 error An attempt to cross a hline will throw an error.
322 It is probably good to never set this variable to nil, for the sake of
323 portability of tables."
324 :group
'org-table-calculation
326 (const :tag
"Allow to cross" t
)
327 (const :tag
"Stick to hline" nil
)
328 (const :tag
"Error on attempt to cross" error
)))
330 (defgroup org-table-import-export nil
331 "Options concerning table import and export in Org-mode."
332 :tag
"Org Table Import Export"
335 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
336 "Default export parameters for `org-table-export'.
337 These can be overridden for a specific table by setting the
338 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
339 radio tables for the different export transformations and
340 available parameters."
341 :group
'org-table-import-export
344 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
345 "Detects a table line marked for automatic recalculation.")
346 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
347 "Detects a table line marked for automatic recalculation.")
348 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
349 "Detects a table line marked for automatic recalculation.")
350 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
351 "Searching from within a table (any type) this finds the first line outside the table.")
352 (defvar org-table-last-highlighted-reference nil
)
353 (defvar org-table-formula-history nil
)
355 (defvar org-table-column-names nil
356 "Alist with column names, derived from the `!' line.")
357 (defvar org-table-column-name-regexp nil
358 "Regular expression matching the current column names.")
359 (defvar org-table-local-parameters nil
360 "Alist with parameter names, derived from the `$' line.")
361 (defvar org-table-named-field-locations nil
362 "Alist with locations of named fields.")
364 (defvar org-table-current-line-types nil
365 "Table row types, non-nil only for the duration of a command.")
366 (defvar org-table-current-begin-line nil
367 "Table begin line, non-nil only for the duration of a command.")
368 (defvar org-table-current-begin-pos nil
369 "Table begin position, non-nil only for the duration of a command.")
370 (defvar org-table-current-ncol nil
371 "Number of columns in table, non-nil only for the duration of a command.")
372 (defvar org-table-dlines nil
373 "Vector of data line line numbers in the current table.")
374 (defvar org-table-hlines nil
375 "Vector of hline line numbers in the current table.")
377 (defconst org-table-range-regexp
378 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
380 "Regular expression for matching ranges in formulas.")
382 (defconst org-table-range-regexp2
384 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
386 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
387 "Match a range for reference display.")
389 (defun org-table-colgroup-line-p (line)
390 "Is this a table line colgroup information?"
392 (and (string-match "[<>]\\|&[lg]t;" line
)
393 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
399 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
400 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
402 (defun org-table-cookie-line-p (line)
403 "Is this a table line with only alignment/width cookies?"
405 (and (string-match "[<>]\\|&[lg]t;" line
)
407 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
408 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
409 (not (delq nil
(mapcar
411 (not (or (equal s
"")
413 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
415 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
417 (org-split-string (match-string 1 line
)
418 "[ \t]*|[ \t]*")))))))
420 (defvar org-table-colgroup-info nil
) ; Dynamically scoped.
421 (defun org-table-clean-before-export (lines &optional maybe-quoted
)
422 "Check if the table has a marking column.
423 If yes remove the column and the special lines."
424 (setq org-table-colgroup-info nil
)
427 (lambda (x) (or (string-match "^[ \t]*|-" x
)
430 "^[ \t]*| *\\\\?\\([\#!$*_^ /]\\) *|"
431 "^[ \t]*| *\\([\#!$*_^ /]\\) *|")
434 ;; No special marking column
436 (setq org-table-clean-did-remove-column nil
)
441 ((org-table-colgroup-line-p x
)
442 ;; This line contains colgroup info, extract it
443 ;; and then discard the line
444 (setq org-table-colgroup-info
446 (cond ((member x
'("<" "<")) :start
)
447 ((member x
'(">" ">")) :end
)
448 ((member x
'("<>" "<>")) :startend
)))
449 (org-split-string x
"[ \t]*|[ \t]*")))
451 ((org-table-cookie-line-p x
)
452 ;; This line contains formatting cookies, discard it
456 ;; there is a special marking column
457 (setq org-table-clean-did-remove-column t
)
462 ((org-table-colgroup-line-p x
)
463 ;; This line contains colgroup info, extract it
464 ;; and then discard the line
465 (setq org-table-colgroup-info
467 (cond ((member x
'("<" "<")) :start
)
468 ((member x
'(">" ">")) :end
)
469 ((member x
'("<>" "<>")) :startend
)))
470 (cdr (org-split-string x
"[ \t]*|[ \t]*"))))
472 ((org-table-cookie-line-p x
)
473 ;; This line contains formatting cookies, discard it
475 ((string-match "^[ \t]*| *\\([!_^/$]\\|\\\\\\$\\) *|" x
)
478 ((or (string-match "^\\([ \t]*\\)|-+\\+" x
)
479 (string-match "^\\([ \t]*\\)|[^|]*|" x
))
480 ;; remove the first column
481 (replace-match "\\1|" t nil x
))))
484 (defconst org-table-translate-regexp
485 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
486 "Match a reference that needs translation, for reference display.")
489 (defun org-table-create-with-table.el
()
490 "Use the table.el package to insert a new table.
491 If there is already a table at point, convert between Org-mode tables
492 and table.el tables."
497 (if (y-or-n-p "Convert table to Org-mode table? ")
498 (org-table-convert)))
500 (when (y-or-n-p "Convert table to table.el table? ")
502 (org-table-convert)))
503 (t (call-interactively 'table-insert
))))
506 (defun org-table-create-or-convert-from-region (arg)
507 "Convert region to table, or create an empty table.
508 If there is an active region, convert it to a table, using the function
509 `org-table-convert-region'. See the documentation of that function
510 to learn how the prefix argument is interpreted to determine the field
512 If there is no such region, create an empty table with `org-table-create'."
514 (if (org-region-active-p)
515 (org-table-convert-region (region-beginning) (region-end) arg
)
516 (org-table-create arg
)))
519 (defun org-table-create (&optional size
)
520 "Query for a size and insert a table skeleton.
521 SIZE is a string Columns x Rows like for example \"3x2\"."
524 (setq size
(read-string
525 (concat "Table size Columns x Rows [e.g. "
526 org-table-default-size
"]: ")
527 "" nil org-table-default-size
)))
530 (indent (make-string (current-column) ?\
))
531 (split (org-split-string size
" *x *"))
532 (rows (string-to-number (nth 1 split
)))
533 (columns (string-to-number (car split
)))
534 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
536 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
537 (point-at-bol) (point)))
538 (beginning-of-line 1)
540 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
541 (dotimes (i rows
) (insert line
))
544 ;; Insert a hline after the first row.
552 (defun org-table-convert-region (beg0 end0
&optional separator
)
553 "Convert region to a table.
554 The region goes from BEG0 to END0, but these borders will be moved
555 slightly, to make sure a beginning of line in the first line is included.
557 SEPARATOR specifies the field separator in the lines. It can have the
560 '(4) Use the comma as a field separator
561 '(16) Use a TAB as field separator
562 integer When a number, use that many spaces as field separator
563 nil When nil, the command tries to be smart and figure out the
564 separator in the following way:
565 - when each line contains a TAB, assume TAB-separated material
566 - when each line contains a comma, assume CSV material
567 - else, assume one or more SPACE characters as separator."
569 (let* ((beg (min beg0 end0
))
570 (end (max beg0 end0
))
573 (beginning-of-line 1)
574 (setq beg
(point-marker))
576 (if (bolp) (backward-char 1) (end-of-line 1))
577 (setq end
(point-marker))
578 ;; Get the right field separator
583 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
584 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
587 (if (equal separator
'(4))
588 (while (< (point) end
)
589 ;; parse the csv stuff
591 ((looking-at "^") (insert "| "))
592 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
593 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
594 (replace-match "\\1")
595 (if (looking-at "\"") (insert "\"")))
596 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
597 ((looking-at "[ \t]*,") (replace-match " | "))
598 (t (beginning-of-line 2))))
600 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
601 ((equal separator
'(16)) "^\\|\t")
602 ((integerp separator
)
604 (user-error "Number of spaces in separator must be >= 1")
605 (format "^ *\\| *\t *\\| \\{%d,\\}" 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
)))
626 (defvar org-table-last-alignment
)
627 (defvar org-table-last-column-widths
)
629 (defun org-table-export (&optional file format
)
630 "Export table to a file, with configurable format.
631 Such a file can be imported into usual spreadsheet programs.
633 FILE can be the output file name. If not given, it will be taken
634 from a TABLE_EXPORT_FILE property in the current entry or higher
635 up in the hierarchy, or the user will be prompted for a file
636 name. FORMAT can be an export format, of the same kind as it
637 used when `orgtbl-mode' sends a table in a different format.
639 The command suggests a format depending on TABLE_EXPORT_FORMAT,
640 whether it is set locally or up in the hierarchy, then on the
641 extension of the given file name, and finally on the variable
642 `org-table-export-default-format'."
644 (unless (org-at-table-p) (user-error "No table at point"))
645 (org-table-align) ;; make sure we have everything we need
646 (let* ((beg (org-table-begin))
647 (end (org-table-end))
648 (txt (buffer-substring-no-properties beg end
))
649 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
650 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
651 "orgtbl-to-latex" "orgtbl-to-html"
652 "orgtbl-to-generic" "orgtbl-to-texinfo"
655 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
656 buf deffmt-readable fileext
)
658 (setq file
(read-file-name "Export table to: "))
659 (unless (or (not (file-exists-p file
))
660 (y-or-n-p (format "Overwrite file %s? " file
)))
661 (user-error "File not written")))
662 (if (file-directory-p file
)
663 (user-error "This is a directory path, not a file"))
664 (if (and (buffer-file-name)
665 (equal (file-truename file
)
666 (file-truename (buffer-file-name))))
667 (user-error "Please specify a file name that is different from current"))
668 (setq fileext
(concat (file-name-extension file
) "$"))
670 (setq deffmt-readable
671 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
672 org-table-export-default-format
))
673 (while (string-match "\t" deffmt-readable
)
674 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
675 (while (string-match "\n" deffmt-readable
)
676 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
677 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
678 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
679 (let* ((transform (intern (match-string 1 format
)))
680 (params (if (match-end 2)
681 (read (concat "(" (match-string 2 format
) ")"))))
682 (skip (plist-get params
:skip
))
683 (skipcols (plist-get params
:skipcols
))
684 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
685 (lines (org-table-clean-before-export lines
))
686 (i0 (if org-table-clean-did-remove-column
2 1))
689 (if (string-match org-table-hline-regexp x
)
692 (org-split-string (org-trim x
) "\\s-*|\\s-*")
695 (fun (if (= i0
2) 'cdr
'identity
))
696 (org-table-last-alignment
697 (org-remove-by-index (funcall fun org-table-last-alignment
)
699 (org-table-last-column-widths
700 (org-remove-by-index (funcall fun org-table-last-column-widths
)
703 (unless (fboundp transform
)
704 (user-error "No such transformation function %s" transform
))
705 (setq txt
(funcall transform table params
))
707 (with-current-buffer (find-file-noselect file
)
708 (setq buf
(current-buffer))
714 (message "Export done."))
715 (user-error "TABLE_EXPORT_FORMAT invalid"))))
717 (defvar org-table-aligned-begin-marker
(make-marker)
718 "Marker at the beginning of the table last aligned.
719 Used to check if cursor still is in that table, to minimize realignment.")
720 (defvar org-table-aligned-end-marker
(make-marker)
721 "Marker at the end of the table last aligned.
722 Used to check if cursor still is in that table, to minimize realignment.")
723 (defvar org-table-last-alignment nil
724 "List of flags for flushright alignment, from the last re-alignment.
725 This is being used to correctly align a single field after TAB or RET.")
726 (defvar org-table-last-column-widths nil
727 "List of max width of fields in each column.
728 This is being used to correctly align a single field after TAB or RET.")
729 (defvar org-table-formula-debug nil
730 "Non-nil means debug table formulas.
731 When nil, simply write \"#ERROR\" in corrupted fields.")
732 (make-variable-buffer-local 'org-table-formula-debug
)
733 (defvar org-table-overlay-coordinates nil
734 "Overlay coordinates after each align of a table.")
735 (make-variable-buffer-local 'org-table-overlay-coordinates
)
737 (defvar org-last-recalc-line nil
)
738 (defvar org-table-do-narrow t
) ; for dynamic scoping
739 (defconst org-narrow-column-arrow
"=>"
740 "Used as display property in narrowed table columns.")
743 (defun org-table-align ()
744 "Align the table at point by aligning all vertical bars."
748 (beg (org-table-begin))
749 (end (org-table-end))
750 ;; Current cursor position
751 (linepos (org-current-line))
752 (colpos (org-table-current-column))
753 (winstart (window-start))
754 (winstartline (org-current-line (min winstart
(1- (point-max)))))
755 lines
(new "") lengths l typenums ty fields maxfields i
763 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
765 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
766 emptystrings links dates emph raise narrow
767 falign falign1 fmax f1 len c e space
)
769 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
770 ;; Check if we have links or dates
772 (setq links
(re-search-forward org-bracket-link-regexp end t
))
774 (setq emph
(and org-hide-emphasis-markers
775 (re-search-forward org-emph-re end t
)))
777 (setq raise
(and org-use-sub-superscripts
778 (re-search-forward org-match-substring-regexp end t
)))
780 (setq dates
(and org-display-custom-times
781 (re-search-forward org-ts-regexp-both end t
)))
782 ;; Make sure the link properties are right
783 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
784 ;; Make sure the date properties are right
785 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
786 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
787 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
789 ;; Check if we are narrowing any columns
791 (setq narrow
(and org-table-do-narrow
792 org-format-transports-properties-p
793 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
795 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
798 (setq lines
(org-split-string
799 (buffer-substring beg end
) "\n"))
800 ;; Store the indentation of the first line
801 (if (string-match "^ *" (car lines
))
802 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
803 ;; Mark the hlines by setting the corresponding element to nil
804 ;; At the same time, we remove trailing space.
805 (setq lines
(mapcar (lambda (l)
806 (if (string-match "^ *|-" l
)
808 (if (string-match "[ \t]+$" l
)
809 (substring l
0 (match-beginning 0))
812 ;; Get the data fields by splitting the lines.
815 (org-split-string l
" *| *"))
816 (delq nil
(copy-sequence lines
))))
817 ;; How many fields in the longest line?
819 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
821 (kill-region beg end
)
822 (org-table-create org-table-default-size
)
823 (user-error "Empty table - created default table")))
824 ;; A list of empty strings to fill any short rows on output
825 (setq emptystrings
(make-list maxfields
""))
826 ;; Check for special formatting.
828 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
829 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
830 ;; Check if there is an explicit width specified
832 (when (or narrow falign
)
833 (setq c column fmax nil falign1 nil
)
836 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
837 (if (match-end 1) (setq falign1
(match-string 1 e
)))
838 (if (and org-table-do-narrow
(match-end 2))
839 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
840 ;; Find fields that are wider than fmax, and shorten them
842 (loop for xx in column do
843 (when (and (stringp xx
)
844 (> (org-string-width xx
) fmax
))
845 (org-add-props xx nil
847 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
848 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
850 (user-error "Cannot narrow field starting with wide link \"%s\""
851 (match-string 0 xx
)))
852 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
853 (add-text-properties (- f1
2) f1
854 (list 'display org-narrow-column-arrow
)
856 ;; Get the maximum width for each column
857 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
859 ;; Get the fraction of numbers, to decide about alignment of the column
861 (push (equal (downcase falign1
) "r") typenums
)
862 (setq cnt
0 frac
0.0)
863 (loop for x in column do
866 (setq frac
( / (+ (* frac cnt
)
867 (if (string-match org-table-number-regexp x
) 1 0))
868 (setq cnt
(1+ cnt
))))))
869 (push (>= frac org-table-number-fraction
) typenums
)))
870 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
872 ;; Store the alignment of this table, for later editing of single fields
873 (setq org-table-last-alignment typenums
874 org-table-last-column-widths lengths
)
876 ;; With invisible characters, `format' does not get the field width right
877 ;; So we need to make these fields wide by hand.
878 (when (or links emph raise
)
879 (loop for i from
0 upto
(1- maxfields
) do
880 (setq len
(nth i lengths
))
881 (loop for j from
0 upto
(1- (length fields
)) do
882 (setq c
(nthcdr i
(car (nthcdr j fields
))))
883 (if (and (stringp (car c
))
884 (or (text-property-any 0 (length (car c
))
885 'invisible
'org-link
(car c
))
886 (text-property-any 0 (length (car c
))
887 'org-dwidth t
(car c
)))
888 (< (org-string-width (car c
)) len
))
890 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
891 (setcar c
(if (nth i typenums
)
892 (concat space
(car c
))
893 (concat (car c
) space
))))))))
895 ;; Compute the formats needed for output of the table
896 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
897 (while (setq l
(pop lengths
))
898 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
899 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
900 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
901 (setq rfmt
(concat rfmt
"\n")
902 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
906 (if l
(apply 'format rfmt
907 (append (pop fields
) emptystrings
))
910 (move-marker org-table-aligned-begin-marker
(point))
912 ;; Replace the old one
913 (delete-region (point) end
)
914 (move-marker end nil
)
915 (move-marker org-table-aligned-end-marker
(point))
916 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
917 (goto-char org-table-aligned-begin-marker
)
918 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
919 ;; Try to move to the old location
920 (org-goto-line winstartline
)
921 (setq winstart
(point-at-bol))
922 (org-goto-line linepos
)
923 (when (eq (window-buffer (selected-window)) (current-buffer))
924 (set-window-start (selected-window) winstart
'noforce
))
925 (org-table-goto-column colpos
)
926 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
927 (setq org-table-may-need-update nil
)
930 (defun org-table-begin (&optional table-type
)
931 "Find the beginning of the table and return its position.
932 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
934 (if (not (re-search-backward
935 (if table-type org-table-any-border-regexp
936 org-table-border-regexp
)
938 (progn (goto-char (point-min)) (point))
939 (goto-char (match-beginning 0))
940 (beginning-of-line 2)
943 (defun org-table-end (&optional table-type
)
944 "Find the end of the table and return its position.
945 With argument TABLE-TYPE, go to the end of a table.el-type table."
947 (if (not (re-search-forward
948 (if table-type org-table-any-border-regexp
949 org-table-border-regexp
)
951 (goto-char (point-max))
952 (goto-char (match-beginning 0)))
956 (defun org-table-justify-field-maybe (&optional new
)
957 "Justify the current field, text to left, number to right.
958 Optional argument NEW may specify text to replace the current field content."
960 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
961 ((org-at-table-hline-p))
963 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
965 (< (point) org-table-aligned-begin-marker
)
966 (>= (point) org-table-aligned-end-marker
)))
967 ;; This is not the same table, force a full re-align
968 (setq org-table-may-need-update t
))
969 (t ;; realign the current field, based on previous full realign
970 (let* ((pos (point)) s
971 (col (org-table-current-column))
972 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
975 (skip-chars-backward "^|\n")
976 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
978 (setq s
(match-string 1)
980 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
981 e
(not (= (match-beginning 2) (match-end 2))))
982 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
983 l
(if e
"|" (setq org-table-may-need-update t
) ""))
986 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
987 (setq n
(format f new
))
988 (setq n
(concat new
"|") org-table-may-need-update t
)))
989 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
991 (let (org-table-may-need-update)
992 (replace-match n t t
))))
993 (setq org-table-may-need-update t
))
997 (defun org-table-next-field ()
998 "Go to the next field in the current table, creating new lines as needed.
999 Before doing so, re-align the table if necessary."
1001 (org-table-maybe-eval-formula)
1002 (org-table-maybe-recalculate-line)
1003 (if (and org-table-automatic-realign
1004 org-table-may-need-update
)
1006 (let ((end (org-table-end)))
1007 (if (org-at-table-hline-p)
1011 (re-search-forward "|" end
)
1012 (if (looking-at "[ \t]*$")
1013 (re-search-forward "|" end
))
1014 (if (and (looking-at "-")
1015 org-table-tab-jumps-over-hlines
1016 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1017 (goto-char (match-beginning 1)))
1018 (if (looking-at "-")
1020 (beginning-of-line 0)
1021 (org-table-insert-row 'below
))
1022 (if (looking-at " ") (forward-char 1))))
1024 (org-table-insert-row 'below
)))))
1027 (defun org-table-previous-field ()
1028 "Go to the previous field in the table.
1029 Before doing so, re-align the table if necessary."
1031 (org-table-justify-field-maybe)
1032 (org-table-maybe-recalculate-line)
1033 (if (and org-table-automatic-realign
1034 org-table-may-need-update
)
1036 (if (org-at-table-hline-p)
1040 (re-search-backward "|" (org-table-begin))
1041 (re-search-backward "|" (org-table-begin)))
1042 (error (user-error "Cannot move to previous table field")))
1043 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1044 (re-search-backward "|" (org-table-begin)))
1045 (if (looking-at "| ?")
1046 (goto-char (match-end 0))))
1048 (defun org-table-beginning-of-field (&optional n
)
1049 "Move to the end of the current table field.
1050 If already at or after the end, move to the end of the next table field.
1051 With numeric argument N, move N-1 fields forward first."
1053 (let ((pos (point)))
1056 (org-table-previous-field))
1057 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1058 (user-error "No more table fields before the current")
1059 (goto-char (match-end 0))
1060 (and (looking-at " ") (forward-char 1)))
1061 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1063 (defun org-table-end-of-field (&optional n
)
1064 "Move to the beginning of the current table field.
1065 If already at or before the beginning, move to the beginning of the
1067 With numeric argument N, move N-1 fields backward first."
1069 (let ((pos (point)))
1072 (org-table-next-field))
1073 (when (re-search-forward "|" (point-at-eol 1) t
)
1075 (skip-chars-backward " ")
1076 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1078 (if (<= (point) pos
) (org-table-end-of-field 2))))
1081 (defun org-table-next-row ()
1082 "Go to the next row (same column) in the current table.
1083 Before doing so, re-align the table if necessary."
1085 (org-table-maybe-eval-formula)
1086 (org-table-maybe-recalculate-line)
1087 (if (or (looking-at "[ \t]*$")
1088 (save-excursion (skip-chars-backward " \t") (bolp)))
1090 (if (and org-table-automatic-realign
1091 org-table-may-need-update
)
1093 (let ((col (org-table-current-column)))
1094 (beginning-of-line 2)
1095 (if (or (not (org-at-table-p))
1096 (org-at-table-hline-p))
1098 (beginning-of-line 0)
1099 (org-table-insert-row 'below
)))
1100 (org-table-goto-column col
)
1101 (skip-chars-backward "^|\n\r")
1102 (if (looking-at " ") (forward-char 1)))))
1105 (defun org-table-copy-down (n)
1106 "Copy a field down in the current column.
1107 If the field at the cursor is empty, copy into it the content of
1108 the nearest non-empty field above. With argument N, use the Nth
1109 non-empty field. If the current field is not empty, it is copied
1110 down to the next row, and the cursor is moved with it.
1111 Therefore, repeating this command causes the column to be filled
1113 If the variable `org-table-copy-increment' is non-nil and the
1114 field is an integer or a timestamp, it will be incremented while
1115 copying. In the case of a timestamp, increment by one day."
1117 (let* ((colpos (org-table-current-column))
1118 (col (current-column))
1119 (field (org-table-get-field))
1120 (non-empty (string-match "[^ \t]" field
))
1121 (beg (org-table-begin))
1124 (org-table-check-inside-data-field)
1127 (setq txt
(org-trim field
))
1128 (org-table-next-row)
1129 (org-table-blank-field))
1133 (while (progn (beginning-of-line 1)
1134 (re-search-backward org-table-dataline-regexp
1136 (org-table-goto-column colpos t
)
1137 (if (and (looking-at
1138 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1139 (<= (setq n
(1- n
)) 0))
1140 (throw 'exit
(match-string 1))))))))
1143 (if (and org-table-copy-increment
1144 (not (equal orig-n
0))
1145 (string-match "^[0-9]+$" txt
)
1146 (< (string-to-number txt
) 100000000))
1147 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1149 (org-move-to-column col
)
1150 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1151 (org-timestamp-up-day)
1152 (org-table-maybe-recalculate-line))
1154 (org-move-to-column col
))
1155 (user-error "No non-empty field found"))))
1157 (defun org-table-check-inside-data-field (&optional noerror
)
1158 "Is point inside a table data field?
1159 I.e. not on a hline or before the first or after the last column?
1160 This actually throws an error, so it aborts the current command."
1161 (if (or (not (org-at-table-p))
1162 (= (org-table-current-column) 0)
1163 (org-at-table-hline-p)
1164 (looking-at "[ \t]*$"))
1167 (user-error "Not in table data field"))
1170 (defvar org-table-clip nil
1171 "Clipboard for table regions.")
1173 (defun org-table-get (line column
)
1174 "Get the field in table line LINE, column COLUMN.
1175 If LINE is larger than the number of data lines in the table, the function
1176 returns nil. However, if COLUMN is too large, we will simply return an
1178 If LINE is nil, use the current line.
1179 If column is nil, use the current column."
1180 (setq column
(or column
(org-table-current-column)))
1182 (and (or (not line
) (org-table-goto-line line
))
1183 (org-trim (org-table-get-field column
)))))
1185 (defun org-table-put (line column value
&optional align
)
1186 "Put VALUE into line LINE, column COLUMN.
1187 When ALIGN is set, also realign the table."
1188 (setq column
(or column
(org-table-current-column)))
1189 (prog1 (save-excursion
1190 (and (or (not line
) (org-table-goto-line line
))
1191 (progn (org-table-goto-column column nil
'force
) t
)
1192 (org-table-get-field column value
)))
1193 (and align
(org-table-align))))
1195 (defun org-table-current-line ()
1196 "Return the index of the current data line."
1197 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1199 (goto-char (org-table-begin))
1200 (while (and (re-search-forward org-table-dataline-regexp end t
)
1202 (< (point-at-eol) pos
))))
1205 (defun org-table-goto-line (N)
1206 "Go to the Nth data line in the current table.
1207 Return t when the line exists, nil if it does not exist."
1208 (goto-char (org-table-begin))
1209 (let ((end (org-table-end)) (cnt 0))
1210 (while (and (re-search-forward org-table-dataline-regexp end t
)
1211 (< (setq cnt
(1+ cnt
)) N
)))
1214 (defun org-table-blank-field ()
1215 "Blank the current table field or active region."
1217 (org-table-check-inside-data-field)
1218 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1219 (let (org-table-clip)
1220 (org-table-cut-region (region-beginning) (region-end)))
1221 (skip-chars-backward "^|")
1223 (if (looking-at "|[^|\n]+")
1224 (let* ((pos (match-beginning 0))
1225 (match (match-string 0))
1226 (len (org-string-width match
)))
1227 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1228 (goto-char (+ 2 pos
))
1229 (substring match
1)))))
1231 (defun org-table-get-field (&optional n replace
)
1232 "Return the value of the field in column N of current row.
1233 N defaults to current field.
1234 If REPLACE is a string, replace field with this value. The return value
1235 is always the old value."
1236 (and n
(org-table-goto-column n
))
1237 (skip-chars-backward "^|\n")
1239 (if (looking-at "|[^|\r\n]*")
1240 (let* ((pos (match-beginning 0))
1241 (val (buffer-substring (1+ pos
) (match-end 0))))
1243 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1245 (goto-char (min (point-at-eol) (+ 2 pos
)))
1247 (forward-char 1) ""))
1250 (defun org-table-field-info (arg)
1251 "Show info about the current field, and highlight any reference at point."
1253 (org-table-get-specials)
1255 (let* ((pos (point))
1256 (col (org-table-current-column))
1257 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1258 (name (car (rassoc (list (org-current-line) col
)
1259 org-table-named-field-locations
)))
1260 (eql (org-table-expand-lhs-ranges
1263 (cons (org-table-formula-handle-first/last-rc
1265 (org-table-get-stored-formulas))))
1266 (dline (org-table-current-dline))
1267 (ref (format "@%d$%d" dline col
))
1268 (ref1 (org-table-convert-refs-to-an ref
))
1269 (fequation (or (assoc name eql
) (assoc ref eql
)))
1270 (cequation (assoc (int-to-string col
) eql
))
1271 (eqn (or fequation cequation
)))
1272 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1273 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1276 (org-table-show-reference 'local
)
1278 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1280 (if cname
(concat " or $" cname
) "")
1282 (if name
(concat " or $" name
) "")
1283 ;; FIXME: formula info not correct if special table line
1285 (concat ", formula: "
1286 (org-table-formula-to-user
1288 (if (string-match "^[$@]"(car eqn
)) "" "$")
1289 (car eqn
) "=" (cdr eqn
))))
1292 (defun org-table-current-column ()
1293 "Find out which column we are in."
1295 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1297 (let ((cnt 0) (pos (point)))
1298 (beginning-of-line 1)
1299 (while (search-forward "|" pos t
)
1300 (setq cnt
(1+ cnt
)))
1301 (when (org-called-interactively-p 'interactive
)
1302 (message "In table column %d" cnt
))
1306 (defun org-table-current-dline ()
1307 "Find out what table data line we are in.
1308 Only data lines count for this."
1310 (when (org-called-interactively-p 'any
)
1311 (org-table-check-inside-data-field))
1313 (let ((cnt 0) (pos (point)))
1314 (goto-char (org-table-begin))
1315 (while (<= (point) pos
)
1316 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1317 (beginning-of-line 2))
1318 (when (org-called-interactively-p 'any
)
1319 (message "This is table line %d" cnt
))
1323 (defun org-table-goto-column (n &optional on-delim force
)
1324 "Move the cursor to the Nth column in the current table line.
1325 With optional argument ON-DELIM, stop with point before the left delimiter
1327 If there are less than N fields, just go to after the last delimiter.
1328 However, when FORCE is non-nil, create new columns if necessary."
1330 (beginning-of-line 1)
1332 (while (and (> (setq n
(1- n
)) -
1)
1333 (or (search-forward "|" (point-at-eol) t
)
1335 (progn (end-of-line 1)
1336 (skip-chars-backward "^|")
1339 (when (and force
(not (looking-at ".*|")))
1340 (save-excursion (end-of-line 1) (insert " | ")))
1343 (if (looking-at " ") (forward-char 1)))))
1346 (defun org-table-insert-column ()
1347 "Insert a new column into the table."
1349 (if (not (org-at-table-p))
1350 (user-error "Not at a table"))
1351 (org-table-find-dataline)
1352 (let* ((col (max 1 (org-table-current-column)))
1353 (beg (org-table-begin))
1354 (end (org-table-end))
1355 ;; Current cursor position
1356 (linepos (org-current-line))
1359 (while (< (point) end
)
1360 (if (org-at-table-hline-p)
1362 (org-table-goto-column col t
)
1364 (beginning-of-line 2))
1365 (move-marker end nil
)
1366 (org-goto-line linepos
)
1367 (org-table-goto-column colpos
)
1369 (when (or (not org-table-fix-formulas-confirm
)
1370 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1371 (org-table-fix-formulas "$" nil
(1- col
) 1)
1372 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1374 (defun org-table-find-dataline ()
1375 "Find a data line in the current table, which is needed for column commands."
1376 (if (and (org-at-table-p)
1377 (not (org-at-table-hline-p)))
1379 (let ((col (current-column))
1380 (end (org-table-end)))
1381 (org-move-to-column col
)
1382 (while (and (< (point) end
)
1383 (or (not (= (current-column) col
))
1384 (org-at-table-hline-p)))
1385 (beginning-of-line 2)
1386 (org-move-to-column col
))
1387 (if (and (org-at-table-p)
1388 (not (org-at-table-hline-p)))
1391 "Please position cursor in a data line for column operations")))))
1393 (defun org-table-line-to-dline (line &optional above
)
1394 "Turn a buffer line number into a data line number.
1395 If there is no data line in this line, return nil.
1396 If there is no matching dline (most likely te reference was a hline), the
1397 first dline below it is used. When ABOVE is non-nil, the one above is used."
1399 (let ((ll (length org-table-dlines
))
1405 (if (<= (aref org-table-dlines i
) line
)
1410 (if (>= (aref org-table-dlines i
) line
)
1416 (defun org-table-delete-column ()
1417 "Delete a column from the table."
1419 (if (not (org-at-table-p))
1420 (user-error "Not at a table"))
1421 (org-table-find-dataline)
1422 (org-table-check-inside-data-field)
1423 (let* ((col (org-table-current-column))
1424 (beg (org-table-begin))
1425 (end (org-table-end))
1426 ;; Current cursor position
1427 (linepos (org-current-line))
1430 (while (< (point) end
)
1431 (if (org-at-table-hline-p)
1433 (org-table-goto-column col t
)
1434 (and (looking-at "|[^|\n]+|")
1435 (replace-match "|")))
1436 (beginning-of-line 2))
1437 (move-marker end nil
)
1438 (org-goto-line linepos
)
1439 (org-table-goto-column colpos
)
1441 (when (or (not org-table-fix-formulas-confirm
)
1442 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1443 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1445 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1449 (defun org-table-move-column-right ()
1450 "Move column to the right."
1452 (org-table-move-column nil
))
1454 (defun org-table-move-column-left ()
1455 "Move column to the left."
1457 (org-table-move-column 'left
))
1460 (defun org-table-move-column (&optional left
)
1461 "Move the current column to the right. With arg LEFT, move to the left."
1463 (if (not (org-at-table-p))
1464 (user-error "Not at a table"))
1465 (org-table-find-dataline)
1466 (org-table-check-inside-data-field)
1467 (let* ((col (org-table-current-column))
1468 (col1 (if left
(1- col
) col
))
1469 (beg (org-table-begin))
1470 (end (org-table-end))
1471 ;; Current cursor position
1472 (linepos (org-current-line))
1473 (colpos (if left
(1- col
) (1+ col
))))
1474 (if (and left
(= col
1))
1475 (user-error "Cannot move column further left"))
1476 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1477 (user-error "Cannot move column further right"))
1479 (while (< (point) end
)
1480 (if (org-at-table-hline-p)
1482 (org-table-goto-column col1 t
)
1483 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1484 (replace-match "|\\2|\\1|")))
1485 (beginning-of-line 2))
1486 (move-marker end nil
)
1487 (org-goto-line linepos
)
1488 (org-table-goto-column colpos
)
1490 (when (or (not org-table-fix-formulas-confirm
)
1491 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1492 (org-table-fix-formulas
1493 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1494 (cons (number-to-string colpos
) (number-to-string col
))))
1495 (org-table-fix-formulas
1496 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1497 (cons (number-to-string colpos
) (number-to-string col
)))))))
1500 (defun org-table-move-row-down ()
1501 "Move table row down."
1503 (org-table-move-row nil
))
1505 (defun org-table-move-row-up ()
1506 "Move table row up."
1508 (org-table-move-row 'up
))
1511 (defun org-table-move-row (&optional up
)
1512 "Move the current table line down. With arg UP, move it up."
1514 (let* ((col (current-column))
1516 (hline1p (save-excursion (beginning-of-line 1)
1517 (looking-at org-table-hline-regexp
)))
1518 (dline1 (org-table-current-dline))
1519 (dline2 (+ dline1
(if up -
1 1)))
1522 (beginning-of-line tonew
)
1523 (unless (org-at-table-p)
1525 (user-error "Cannot move row further"))
1526 (setq hline2p
(looking-at org-table-hline-regexp
))
1528 (beginning-of-line 1)
1530 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1531 (delete-region (point) (1+ (point-at-eol)))
1532 (beginning-of-line tonew
)
1534 (beginning-of-line 0)
1535 (org-move-to-column col
)
1536 (unless (or hline1p hline2p
1537 (not (or (not org-table-fix-formulas-confirm
)
1538 (funcall org-table-fix-formulas-confirm
1539 "Fix formulas? "))))
1540 (org-table-fix-formulas
1541 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1542 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1545 (defun org-table-insert-row (&optional arg
)
1546 "Insert a new row above the current line into the table.
1547 With prefix ARG, insert below the current line."
1549 (if (not (org-at-table-p))
1550 (user-error "Not at a table"))
1551 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1552 (new (org-table-clean-line line
)))
1553 ;; Fix the first field if necessary
1554 (if (string-match "^[ \t]*| *[#$] *|" line
)
1555 (setq new
(replace-match (match-string 0 line
) t t new
)))
1556 (beginning-of-line (if arg
2 1))
1557 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1558 (beginning-of-line 0)
1559 (re-search-forward "| ?" (point-at-eol) t
)
1560 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1562 (when (or (not org-table-fix-formulas-confirm
)
1563 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1564 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1567 (defun org-table-insert-hline (&optional above
)
1568 "Insert a horizontal-line below the current line into the table.
1569 With prefix ABOVE, insert above the current line."
1571 (if (not (org-at-table-p))
1572 (user-error "Not at a table"))
1573 (when (eobp) (insert "\n") (backward-char 1))
1574 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1576 (let ((line (org-table-clean-line
1577 (buffer-substring (point-at-bol) (point-at-eol))))
1578 (col (current-column)))
1579 (while (string-match "|\\( +\\)|" line
)
1580 (setq line
(replace-match
1581 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1582 ?-
) "|") t t line
)))
1583 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1584 (beginning-of-line (if above
1 2))
1586 (beginning-of-line (if above
1 -
1))
1587 (org-move-to-column col
)
1588 (and org-table-overlay-coordinates
(org-table-align))))
1591 (defun org-table-hline-and-move (&optional same-column
)
1592 "Insert a hline and move to the row below that line."
1594 (let ((col (org-table-current-column)))
1595 (org-table-maybe-eval-formula)
1596 (org-table-maybe-recalculate-line)
1597 (org-table-insert-hline)
1599 (if (looking-at "\n[ \t]*|-")
1600 (progn (insert "\n|") (org-table-align))
1601 (org-table-next-field))
1602 (if same-column
(org-table-goto-column col
))))
1604 (defun org-table-clean-line (s)
1605 "Convert a table line S into a string with only \"|\" and space.
1606 In particular, this does handle wide and invisible characters."
1607 (if (string-match "^[ \t]*|-" s
)
1608 ;; It's a hline, just map the characters
1609 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1610 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1611 (setq s
(replace-match
1612 (concat "|" (make-string (org-string-width (match-string 1 s
))
1618 (defun org-table-kill-row ()
1619 "Delete the current row or horizontal line from the table."
1621 (if (not (org-at-table-p))
1622 (user-error "Not at a table"))
1623 (let ((col (current-column))
1624 (dline (org-table-current-dline)))
1625 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1626 (if (not (org-at-table-p)) (beginning-of-line 0))
1627 (org-move-to-column col
)
1628 (when (or (not org-table-fix-formulas-confirm
)
1629 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1630 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1634 (defun org-table-sort-lines (with-case &optional sorting-type
)
1635 "Sort table lines according to the column at point.
1637 The position of point indicates the column to be used for
1638 sorting, and the range of lines is the range between the nearest
1639 horizontal separator lines, or the entire table of no such lines
1640 exist. If point is before the first column, you will be prompted
1641 for the sorting column. If there is an active region, the mark
1642 specifies the first line and the sorting column, while point
1643 should be in the last line to be included into the sorting.
1645 The command then prompts for the sorting type which can be
1646 alphabetically, numerically, or by time (as given in a time stamp
1647 in the field). Sorting in reverse order is also possible.
1649 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1651 If SORTING-TYPE is specified when this function is called from a Lisp
1652 program, no prompting will take place. SORTING-TYPE must be a character,
1653 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1654 should be done in reverse order."
1656 (let* ((thisline (org-current-line))
1657 (thiscol (org-table-current-column))
1658 (otc org-table-overlay-coordinates
)
1659 beg end bcol ecol tend tbeg column lns pos
)
1660 (when (equal thiscol
0)
1661 (if (org-called-interactively-p 'any
)
1664 (read-string "Use column N for sorting: ")))
1666 (org-table-goto-column thiscol
))
1667 (org-table-check-inside-data-field)
1668 (if (org-region-active-p)
1670 (setq beg
(region-beginning) end
(region-end))
1672 (setq column
(org-table-current-column)
1675 (setq end
(point-at-bol 2)))
1676 (setq column
(org-table-current-column)
1678 tbeg
(org-table-begin)
1679 tend
(org-table-end))
1680 (if (re-search-backward org-table-hline-regexp tbeg t
)
1681 (setq beg
(point-at-bol 2))
1683 (setq beg
(point-at-bol 1)))
1685 (if (re-search-forward org-table-hline-regexp tend t
)
1686 (setq end
(point-at-bol 1))
1688 (setq end
(point-at-bol))))
1689 (setq beg
(move-marker (make-marker) beg
)
1690 end
(move-marker (make-marker) end
))
1693 (org-table-goto-column column
)
1694 (skip-chars-backward "^|")
1695 (setq bcol
(current-column))
1696 (org-table-goto-column (1+ column
))
1697 (skip-chars-backward "^|")
1698 (setq ecol
(1- (current-column)))
1699 (org-table-goto-column column
)
1700 (setq lns
(mapcar (lambda(x) (cons
1701 (org-sort-remove-invisible
1703 (org-split-string x
"[ \t]*|[ \t]*")))
1705 (org-split-string (buffer-substring beg end
) "\n")))
1706 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1707 (when org-table-overlay-coordinates
1708 (org-table-toggle-coordinate-overlays))
1709 (delete-region beg end
)
1710 (move-marker beg nil
)
1711 (move-marker end nil
)
1712 (insert (mapconcat 'cdr lns
"\n") "\n")
1713 (org-goto-line thisline
)
1714 (org-table-goto-column thiscol
)
1715 (when otc
(org-table-toggle-coordinate-overlays))
1716 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1719 (defun org-table-cut-region (beg end
)
1720 "Copy region in table to the clipboard and blank all relevant fields.
1721 If there is no active region, use just the field at point."
1723 (if (org-region-active-p) (region-beginning) (point))
1724 (if (org-region-active-p) (region-end) (point))))
1725 (org-table-copy-region beg end
'cut
))
1728 (defun org-table-copy-region (beg end
&optional cut
)
1729 "Copy rectangular region in table to clipboard.
1730 A special clipboard is used which can only be accessed
1731 with `org-table-paste-rectangle'."
1733 (if (org-region-active-p) (region-beginning) (point))
1734 (if (org-region-active-p) (region-end) (point))
1735 current-prefix-arg
))
1736 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1738 (rpl (if cut
" " nil
)))
1740 (org-table-check-inside-data-field)
1741 (setq l01
(org-current-line)
1742 c01
(org-table-current-column))
1744 (org-table-check-inside-data-field)
1745 (setq l02
(org-current-line)
1746 c02
(org-table-current-column))
1747 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1748 c1
(min c01 c02
) c2
(max c01 c02
))
1752 (if (> l1 l2
) (throw 'exit t
))
1754 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1755 (setq cols nil ic1 c1 ic2 c2
)
1756 (while (< ic1
(1+ ic2
))
1757 (push (org-table-get-field ic1 rpl
) cols
)
1758 (setq ic1
(1+ ic1
)))
1759 (push (nreverse cols
) region
)
1760 (setq l1
(1+ l1
)))))
1761 (setq org-table-clip
(nreverse region
))
1762 (if cut
(org-table-align))
1766 (defun org-table-paste-rectangle ()
1767 "Paste a rectangular region into a table.
1768 The upper right corner ends up in the current field. All involved fields
1769 will be overwritten. If the rectangle does not fit into the present table,
1770 the table is enlarged as needed. The process ignores horizontal separator
1773 (unless (and org-table-clip
(listp org-table-clip
))
1774 (user-error "First cut/copy a region to paste!"))
1775 (org-table-check-inside-data-field)
1776 (let* ((clip org-table-clip
)
1777 (line (org-current-line))
1778 (col (org-table-current-column))
1779 (org-enable-table-editor t
)
1780 (org-table-automatic-realign nil
)
1782 (while (setq cols
(pop clip
))
1783 (while (org-at-table-hline-p) (beginning-of-line 2))
1784 (if (not (org-at-table-p))
1785 (progn (end-of-line 0) (org-table-next-field)))
1787 (while (setq field
(pop cols
))
1788 (org-table-goto-column c nil
'force
)
1789 (org-table-get-field nil field
)
1791 (beginning-of-line 2))
1792 (org-goto-line line
)
1793 (org-table-goto-column col
)
1797 (defun org-table-convert ()
1798 "Convert from `org-mode' table to table.el and back.
1799 Obviously, this only works within limits. When an Org-mode table is
1800 converted to table.el, all horizontal separator lines get lost, because
1801 table.el uses these as cell boundaries and has no notion of horizontal lines.
1802 A table.el table can be converted to an Org-mode table only if it does not
1803 do row or column spanning. Multiline cells will become multiple cells.
1804 Beware, Org-mode does not test if the table can be successfully converted - it
1805 blindly applies a recipe that works for simple tables."
1808 (if (org-at-table.el-p
)
1809 ;; convert to Org-mode table
1810 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1811 (end (move-marker (make-marker) (org-table-end t
))))
1812 (table-unrecognize-region beg end
)
1814 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1817 (if (org-at-table-p)
1818 ;; convert to table.el table
1819 (let ((beg (move-marker (make-marker) (org-table-begin)))
1820 (end (move-marker (make-marker) (org-table-end))))
1821 ;; first, get rid of all horizontal lines
1823 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1825 ;; insert a hline before first
1827 (org-table-insert-hline 'above
)
1828 (beginning-of-line -
1)
1829 ;; insert a hline after each line
1830 (while (progn (beginning-of-line 3) (< (point) end
))
1831 (org-table-insert-hline))
1833 (setq end
(move-marker end
(org-table-end)))
1834 ;; replace "+" at beginning and ending of hlines
1835 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1836 (replace-match "\\1+-"))
1838 (while (re-search-forward "-|[ \t]*$" end t
)
1839 (replace-match "-+"))
1842 (defun org-table-transpose-table-at-point ()
1843 "Transpose orgmode table at point and eliminate hlines.
1851 will be transposed as
1858 Note that horizontal lines disappeared."
1861 (apply #'mapcar
* #'list
1862 ;; remove 'hline from list
1863 (delq nil
(mapcar (lambda (x) (when (listp x
) x
))
1864 (org-table-to-lisp))))))
1865 (delete-region (org-table-begin) (org-table-end))
1866 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1871 (defun org-table-wrap-region (arg)
1872 "Wrap several fields in a column like a paragraph.
1873 This is useful if you'd like to spread the contents of a field over several
1874 lines, in order to keep the table compact.
1876 If there is an active region, and both point and mark are in the same column,
1877 the text in the column is wrapped to minimum width for the given number of
1878 lines. Generally, this makes the table more compact. A prefix ARG may be
1879 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1880 formats the selected text to two lines. If the region was longer than two
1881 lines, the remaining lines remain empty. A negative prefix argument reduces
1882 the current number of lines by that amount. The wrapped text is pasted back
1883 into the table. If you formatted it to more lines than it was before, fields
1884 further down in the table get overwritten - so you might need to make space in
1887 If there is no region, the current field is split at the cursor position and
1888 the text fragment to the right of the cursor is prepended to the field one
1891 If there is no region, but you specify a prefix ARG, the current field gets
1892 blank, and the content is appended to the field above."
1894 (org-table-check-inside-data-field)
1895 (if (org-region-active-p)
1896 ;; There is a region: fill as a paragraph
1897 (let* ((beg (region-beginning))
1898 (cline (save-excursion (goto-char beg
) (org-current-line)))
1899 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1901 (org-table-cut-region (region-beginning) (region-end))
1902 (if (> (length (car org-table-clip
)) 1)
1903 (user-error "Region must be limited to single column"))
1904 (setq nlines
(if arg
1906 (+ (length org-table-clip
) arg
)
1908 (length org-table-clip
)))
1909 (setq org-table-clip
1910 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1912 (org-goto-line cline
)
1913 (org-table-goto-column ccol
)
1914 (org-table-paste-rectangle))
1915 ;; No region, split the current field at point
1916 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1917 (skip-chars-forward "^\r\n|"))
1919 ;; combine with field above
1920 (let ((s (org-table-blank-field))
1921 (col (org-table-current-column)))
1922 (beginning-of-line 0)
1923 (while (org-at-table-hline-p) (beginning-of-line 0))
1924 (org-table-goto-column col
)
1925 (skip-chars-forward "^|")
1926 (skip-chars-backward " ")
1927 (insert " " (org-trim s
))
1930 (if (looking-at "\\([^|]+\\)+|")
1931 (let ((s (match-string 1)))
1932 (replace-match " |")
1933 (goto-char (match-beginning 0))
1934 (org-table-next-row)
1935 (insert (org-trim s
) " ")
1937 (org-table-next-row)))))
1939 (defvar org-field-marker nil
)
1942 (defun org-table-edit-field (arg)
1943 "Edit table field in a different window.
1944 This is mainly useful for fields that contain hidden parts.
1945 When called with a \\[universal-argument] prefix, just make the full field visible so that
1946 it can be edited in place."
1950 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1952 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1953 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1954 (remove-text-properties b e
'(org-cwidth t invisible t
1955 display t intangible t
))
1956 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1957 (font-lock-fontify-block))))
1959 (let ((pos (point-marker))
1961 (if (eq org-table-use-standard-references t
)
1962 (concat (org-number-to-letters (org-table-current-column))
1963 (int-to-string (org-table-current-dline)))
1964 (concat "@" (int-to-string (org-table-current-dline))
1965 "$" (int-to-string (org-table-current-column)))))
1966 (field (org-table-get-field))
1967 (cw (current-window-configuration))
1970 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1971 (when (and (local-variable-p 'org-field-marker
)
1972 (markerp org-field-marker
))
1973 (move-marker org-field-marker nil
))
1975 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1976 (let ((org-inhibit-startup t
)) (org-mode))
1978 (setq truncate-lines nil
)
1980 (goto-char (setq p
(point-max)))
1981 (insert (org-trim field
))
1982 (remove-text-properties p
(point-max)
1983 '(invisible t org-cwidth t display t
1986 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1987 (org-set-local 'org-window-configuration cw
)
1988 (org-set-local 'org-field-marker pos
)
1989 (message "Edit and finish with C-c C-c")))))
1991 (defun org-table-finish-edit-field ()
1992 "Finish editing a table data field.
1993 Remove all newline characters, insert the result into the table, realign
1994 the table and kill the editing buffer."
1995 (let ((pos org-field-marker
)
1996 (cw org-window-configuration
)
1997 (cb (current-buffer))
1999 (goto-char (point-min))
2000 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2001 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2002 (replace-match " "))
2003 (setq text
(org-trim (buffer-string)))
2004 (set-window-configuration cw
)
2006 (select-window (get-buffer-window (marker-buffer pos
)))
2008 (move-marker pos nil
)
2009 (org-table-check-inside-data-field)
2010 (org-table-get-field nil text
)
2012 (message "New field value inserted")))
2014 (define-minor-mode org-table-follow-field-mode
2015 "Minor mode to make the table field editor window follow the cursor.
2016 When this mode is active, the field editor window will always show the
2017 current field. The mode exits automatically when the cursor leaves the
2018 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2019 nil
" TblFollow" nil
2020 (if org-table-follow-field-mode
2021 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2023 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2024 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2025 (win (and buf
(get-buffer-window buf
))))
2026 (when win
(delete-window win
))
2028 (with-current-buffer buf
2029 (move-marker org-field-marker nil
))
2030 (kill-buffer buf
)))))
2032 (defun org-table-follow-fields-with-editor ()
2033 (if (and org-table-exit-follow-field-mode-when-leaving-table
2034 (not (org-at-table-p)))
2035 ;; We have left the table, exit the follow mode
2036 (org-table-follow-field-mode -
1)
2037 (when (org-table-check-inside-data-field 'noerror
)
2038 (let ((win (selected-window)))
2039 (org-table-edit-field nil
)
2040 (org-fit-window-to-buffer)
2041 (select-window win
)))))
2043 (defvar org-timecnt
) ; dynamically scoped parameter
2046 (defun org-table-sum (&optional beg end nlast
)
2047 "Sum numbers in region of current table column.
2048 The result will be displayed in the echo area, and will be available
2049 as kill to be inserted with \\[yank].
2051 If there is an active region, it is interpreted as a rectangle and all
2052 numbers in that rectangle will be summed. If there is no active
2053 region and point is located in a table column, sum all numbers in that
2056 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2057 numbers are assumed to be times as well (in decimal hours) and the
2058 numbers are added as such.
2060 If NLAST is a number, only the NLAST fields will actually be summed."
2063 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2065 ((and beg end
)) ; beg and end given explicitly
2066 ((org-region-active-p)
2067 (setq beg
(region-beginning) end
(region-end)))
2069 (setq col
(org-table-current-column))
2070 (goto-char (org-table-begin))
2071 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2072 (user-error "No table data"))
2073 (org-table-goto-column col
)
2075 (goto-char (org-table-end))
2076 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2077 (user-error "No table data"))
2078 (org-table-goto-column col
)
2079 (setq end
(point))))
2080 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2081 (items1 (cond ((not nlast
) items
)
2082 ((>= nlast
(length items
)) items
)
2083 (t (setq items
(reverse items
))
2084 (setcdr (nthcdr (1- nlast
) items
) nil
)
2086 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2088 (res (apply '+ numbers
))
2089 (sres (if (= org-timecnt
0)
2090 (number-to-string res
)
2091 (setq diff
(* 3600 res
)
2092 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2093 m
(floor (/ diff
60)) diff
(mod diff
60)
2095 (format "%d:%02d:%02d" h m s
))))
2097 (if (org-called-interactively-p 'interactive
)
2099 (substitute-command-keys
2100 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2101 (length numbers
) sres
))))
2104 (defun org-table-get-number-for-summing (s)
2106 (if (string-match "^ *|? *" s
)
2107 (setq s
(replace-match "" nil nil s
)))
2108 (if (string-match " *|? *$" s
)
2109 (setq s
(replace-match "" nil nil s
)))
2110 (setq n
(string-to-number s
))
2112 ((and (string-match "0" s
)
2113 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2114 ((string-match "\\`[ \t]+\\'" s
) nil
)
2115 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2116 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2117 (m (string-to-number (or (match-string 2 s
) "0")))
2118 (s (string-to-number (or (match-string 4 s
) "0"))))
2119 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2120 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2124 (defun org-table-current-field-formula (&optional key noerror
)
2125 "Return the formula active for the current field.
2126 Assumes that specials are in place.
2127 If KEY is given, return the key to this formula.
2128 Otherwise return the formula preceded with \"=\" or \":=\"."
2129 (let* ((name (car (rassoc (list (org-current-line)
2130 (org-table-current-column))
2131 org-table-named-field-locations
)))
2132 (col (org-table-current-column))
2133 (scol (int-to-string col
))
2134 (ref (format "@%d$%d" (org-table-current-dline) col
))
2135 (stored-list (org-table-get-stored-formulas noerror
))
2136 (ass (or (assoc name stored-list
)
2137 (assoc ref stored-list
)
2138 (assoc scol stored-list
))))
2141 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2144 (defun org-table-get-formula (&optional equation named
)
2145 "Read a formula from the minibuffer, offer stored formula as default.
2146 When NAMED is non-nil, look for a named equation."
2147 (let* ((stored-list (org-table-get-stored-formulas))
2148 (name (car (rassoc (list (org-current-line)
2149 (org-table-current-column))
2150 org-table-named-field-locations
)))
2151 (ref (format "@%d$%d" (org-table-current-dline)
2152 (org-table-current-column)))
2153 (refass (assoc ref stored-list
))
2154 (nameass (assoc name stored-list
))
2156 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2159 (int-to-string (org-table-current-column))))
2160 (dummy (and (or nameass refass
) (not named
)
2161 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2162 (message "Formula not replaced")))
2163 (name (or name ref
))
2164 (org-table-may-need-update nil
)
2165 (stored (cdr (assoc scol stored-list
)))
2167 ((and stored equation
(string-match "^ *=? *$" equation
))
2171 (t (org-table-formula-from-user
2173 (org-table-formula-to-user
2174 (format "%s formula %s%s="
2175 (if named
"Field" "Column")
2176 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2178 (if stored
(org-table-formula-to-user stored
) "")
2179 'org-table-formula-history
2182 (when (not (string-match "\\S-" eq
))
2184 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2185 (org-table-store-formulas stored-list
)
2186 (user-error "Formula removed"))
2187 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2188 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2189 (if (and name
(not named
))
2190 ;; We set the column equation, delete the named one.
2191 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2194 (setcdr (assoc scol stored-list
) eq
)
2195 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2196 (if (or mustsave
(not (equal stored eq
)))
2197 (org-table-store-formulas stored-list
))
2200 (defun org-table-store-formulas (alist)
2201 "Store the list of formulas below the current table."
2202 (setq alist
(sort alist
'org-table-formula-less-p
))
2203 (let ((case-fold-search t
))
2205 (goto-char (org-table-end))
2206 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2208 ;; don't overwrite TBLFM, we might use text properties to store stuff
2209 (goto-char (match-beginning 3))
2210 (delete-region (match-beginning 3) (match-end 0)))
2212 (insert (or (match-string 2) "#+TBLFM:")))
2214 (mapconcat (lambda (x)
2216 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2217 (car x
) "=" (cdr x
)))
2221 (defsubst org-table-formula-make-cmp-string
(a)
2222 (when (string-match "\\`$[<>]" a
)
2223 (let ((arrow (string-to-char (substring a
1))))
2224 ;; Fake a high number to make sure this is sorted at the end.
2225 (setq a
(org-table-formula-handle-first/last-rc a
))
2226 (setq a
(format "$%d" (+ 10000
2227 (if (= arrow ?
<) -
1000 0)
2228 (string-to-number (substring a
1)))))))
2230 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2234 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2236 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2238 (concat "@@" (match-string 5 a
))))))
2240 (defun org-table-formula-less-p (a b
)
2241 "Compare two formulas for sorting."
2242 (let ((as (org-table-formula-make-cmp-string (car a
)))
2243 (bs (org-table-formula-make-cmp-string (car b
))))
2244 (and as bs
(string< as bs
))))
2247 (defun org-table-get-stored-formulas (&optional noerror
)
2248 "Return an alist with the stored formulas directly after current table."
2249 (interactive) ;; FIXME interactive?
2250 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2252 (goto-char (org-table-end))
2253 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2254 (setq strings
(org-split-string (org-match-string-no-properties 2)
2256 (while (setq string
(pop strings
))
2257 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2258 (setq scol
(if (match-end 2)
2259 (match-string 2 string
)
2260 (match-string 1 string
))
2261 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2262 (concat "$" scol
) scol
)
2263 eq
(match-string 3 string
)
2264 eq-alist
(cons (cons scol eq
) eq-alist
))
2265 (if (member scol seen
)
2268 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2271 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2272 (push scol seen
))))))
2273 (nreverse eq-alist
)))
2275 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2276 "Modify the equations after the table structure has been edited.
2277 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2278 For all numbers larger than LIMIT, shift them by DELTA."
2280 (goto-char (org-table-end))
2281 (when (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2282 (let ((msg "The formulas in #+TBLFM have been updated")
2283 (re (concat key
"\\([0-9]+\\)"))
2286 (if (or (equal key
"$") (equal key
"$LR"))
2287 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2288 (regexp-quote key
) remove
)
2289 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2292 (while (re-search-forward re2
(point-at-eol) t
)
2293 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2294 (if (equal (char-before (match-beginning 0)) ?.
)
2295 (user-error "Change makes TBLFM term %s invalid, use undo to recover"
2297 (replace-match "")))))
2298 (while (re-search-forward re
(point-at-eol) t
)
2299 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2300 (setq s
(match-string 1) n
(string-to-number s
))
2302 ((setq a
(assoc s replace
))
2303 (replace-match (concat key
(cdr a
)) t t
)
2305 ((and limit
(> n limit
))
2306 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2307 (message msg
)))))))))
2309 (defun org-table-get-specials ()
2310 "Get the column names and local parameters for this table."
2312 (let ((beg (org-table-begin)) (end (org-table-end))
2313 names name fields fields1 field cnt
2314 c v l line col types dlines hlines last-dline
)
2315 (setq org-table-column-names nil
2316 org-table-local-parameters nil
2317 org-table-named-field-locations nil
2318 org-table-current-begin-line nil
2319 org-table-current-begin-pos nil
2320 org-table-current-line-types nil
2321 org-table-current-ncol
0)
2323 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2324 (setq names
(org-split-string (match-string 1) " *| *")
2326 (while (setq name
(pop names
))
2328 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2329 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2330 (setq org-table-column-names
(nreverse org-table-column-names
))
2331 (setq org-table-column-name-regexp
2332 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2334 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2335 (setq fields
(org-split-string (match-string 1) " *| *"))
2336 (while (setq field
(pop fields
))
2337 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2338 (push (cons (match-string 1 field
) (match-string 2 field
))
2339 org-table-local-parameters
))))
2341 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2342 (setq c
(match-string 1)
2343 fields
(org-split-string (match-string 2) " *| *"))
2345 (beginning-of-line (if (equal c
"_") 2 0))
2346 (setq line
(org-current-line) col
1)
2347 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2348 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2349 (while (and fields1
(setq field
(pop fields
)))
2350 (setq v
(pop fields1
) col
(1+ col
))
2351 (when (and (stringp field
) (stringp v
)
2352 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2353 (push (cons field v
) org-table-local-parameters
)
2354 (push (list field line col
) org-table-named-field-locations
))))
2355 ;; Analyse the line types
2357 (setq org-table-current-begin-line
(org-current-line)
2358 org-table-current-begin-pos
(point)
2359 l org-table-current-begin-line
)
2360 (while (looking-at "[ \t]*|\\(-\\)?")
2361 (push (if (match-end 1) 'hline
'dline
) types
)
2362 (if (match-end 1) (push l hlines
) (push l dlines
))
2363 (beginning-of-line 2)
2365 (push 'hline types
) ;; add an imaginary extra hline to the end
2366 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2367 last-dline
(car dlines
)
2368 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2369 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2370 (org-goto-line last-dline
)
2371 (let* ((l last-dline
)
2372 (fields (org-split-string
2373 (buffer-substring (point-at-bol) (point-at-eol))
2375 (nfields (length fields
))
2377 (setq org-table-current-ncol nfields
)
2378 (loop for i from
1 to nfields do
2379 (push (list (format "LR%d" i
) l i
) al
)
2380 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2381 (setq org-table-named-field-locations
2382 (append org-table-named-field-locations al
))
2383 (setq org-table-local-parameters
2384 (append org-table-local-parameters al2
))))))
2387 (defun org-table-maybe-eval-formula ()
2388 "Check if the current field starts with \"=\" or \":=\".
2389 If yes, store the formula and apply it."
2390 ;; We already know we are in a table. Get field will only return a formula
2391 ;; when appropriate. It might return a separator line, but no problem.
2392 (when org-table-formula-evaluate-inline
2393 (let* ((field (org-trim (or (org-table-get-field) "")))
2395 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2396 (setq named
(equal (string-to-char field
) ?
:)
2397 eq
(match-string 1 field
))
2398 (if (or (fboundp 'calc-eval
)
2399 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2400 (org-table-eval-formula (if named
'(4) nil
)
2401 (org-table-formula-from-user eq
))
2402 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2404 (defvar org-recalc-commands nil
2405 "List of commands triggering the recalculation of a line.
2406 Will be filled automatically during use.")
2408 (defvar org-recalc-marks
2409 '((" " .
"Unmarked: no special line, no automatic recalculation")
2410 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2411 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2412 ("!" .
"Column name definition line. Reference in formula as $name.")
2413 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2414 ("_" .
"Names for values in row below this one.")
2415 ("^" .
"Names for values in row above this one.")))
2418 (defun org-table-rotate-recalc-marks (&optional newchar
)
2419 "Rotate the recalculation mark in the first column.
2420 If in any row, the first field is not consistent with a mark,
2421 insert a new column for the markers.
2422 When there is an active region, change all the lines in the region,
2423 after prompting for the marking character.
2424 After each change, a message will be displayed indicating the meaning
2427 (unless (org-at-table-p) (user-error "Not at a table"))
2428 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2429 (beg (org-table-begin))
2430 (end (org-table-end))
2431 (l (org-current-line))
2432 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2433 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2437 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2438 (col (org-table-current-column))
2439 (forcenew (car (assoc newchar org-recalc-marks
)))
2442 (message "Change region to what mark? Type # * ! $ or SPC: ")
2443 (setq newchar
(char-to-string (read-char-exclusive))
2444 forcenew
(car (assoc newchar org-recalc-marks
))))
2445 (if (and newchar
(not forcenew
))
2446 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2448 (if l1
(org-goto-line l1
))
2450 (beginning-of-line 1)
2451 (unless (looking-at org-table-dataline-regexp
)
2452 (user-error "Not at a table data line")))
2454 (org-table-goto-column 1)
2455 (org-table-insert-column)
2456 (org-table-goto-column (1+ col
)))
2457 (setq epos
(point-at-eol))
2459 (beginning-of-line 1)
2460 (org-table-get-field
2461 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2463 (setq new
(or forcenew
2464 (cadr (member (match-string 1) marks
))))
2470 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2471 (and (looking-at org-table-dataline-regexp
)
2472 (org-table-get-field 1 (concat " " new
" "))))
2473 (org-goto-line l1
)))
2474 (if (not (= epos
(point-at-eol))) (org-table-align))
2476 (and (org-called-interactively-p 'interactive
)
2477 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2480 (defun org-table-maybe-recalculate-line ()
2481 "Recompute the current line if marked for it, and if we haven't just done it."
2483 (and org-table-allow-automatic-line-recalculation
2484 (not (and (memq last-command org-recalc-commands
)
2485 (equal org-last-recalc-line
(org-current-line))))
2486 (save-excursion (beginning-of-line 1)
2487 (looking-at org-table-auto-recalculate-regexp
))
2488 (org-table-recalculate) t
))
2490 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2491 (defsubst org-set-calc-mode
(var &optional value
)
2493 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2494 ("R" calc-angle-mode rad
)
2495 ("F" calc-prefer-frac t
)
2496 ("S" calc-symbolic-mode t
)))
2497 value
(nth 2 var
) var
(nth 1 var
)))
2498 (if (memq var org-tbl-calc-modes
)
2499 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2500 (cons var
(cons value org-tbl-calc-modes
)))
2504 (defun org-table-eval-formula (&optional arg equation
2505 suppress-align suppress-const
2506 suppress-store suppress-analysis
)
2507 "Replace the table field value at the cursor by the result of a calculation.
2509 This function makes use of Dave Gillespie's Calc package, in my view the
2510 most exciting program ever written for GNU Emacs. So you need to have Calc
2511 installed in order to use this function.
2513 In a table, this command replaces the value in the current field with the
2514 result of a formula. It also installs the formula as the \"current\" column
2515 formula, by storing it in a special line below the table. When called
2516 with a `C-u' prefix, the current field must be a named field, and the
2517 formula is installed as valid in only this specific field.
2519 When called with two `C-u' prefixes, insert the active equation
2520 for the field back into the current field, so that it can be
2521 edited there. This is useful in order to use \\[org-table-show-reference]
2522 to check the referenced fields.
2524 When called, the command first prompts for a formula, which is read in
2525 the minibuffer. Previously entered formulas are available through the
2526 history list, and the last used formula is offered as a default.
2527 These stored formulas are adapted correctly when moving, inserting, or
2528 deleting columns with the corresponding commands.
2530 The formula can be any algebraic expression understood by the Calc package.
2531 For details, see the Org-mode manual.
2533 This function can also be called from Lisp programs and offers
2534 additional arguments: EQUATION can be the formula to apply. If this
2535 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2536 used to speed-up recursive calls by by-passing unnecessary aligns.
2537 SUPPRESS-CONST suppresses the interpretation of constants in the
2538 formula, assuming that this has been done already outside the function.
2539 SUPPRESS-STORE means the formula should not be stored, either because
2540 it is already stored, or because it is a modified equation that should
2541 not overwrite the stored one."
2543 (org-table-check-inside-data-field)
2544 (or suppress-analysis
(org-table-get-specials))
2545 (if (equal arg
'(16))
2546 (let ((eq (org-table-current-field-formula)))
2547 (or eq
(user-error "No equation active for current field"))
2548 (org-table-get-field nil eq
)
2550 (setq org-table-may-need-update t
))
2552 (ndown (if (integerp arg
) arg
1))
2553 (org-table-automatic-realign nil
)
2554 (case-fold-search nil
)
2556 (formula (if (and equation suppress-store
)
2558 (org-table-get-formula equation
(equal arg
'(4)))))
2559 (n0 (org-table-current-column))
2560 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2561 (numbers nil
) ; was a variable, now fixed default
2563 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2564 duration duration-output-format
)
2565 ;; Parse the format string. Since we have a lot of modes, this is
2566 ;; a lot of work. However, I think calc still uses most of the time.
2567 (if (string-match ";" formula
)
2568 (let ((tmp (org-split-string formula
";")))
2569 (setq formula
(car tmp
)
2570 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2572 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2573 (setq c
(string-to-char (match-string 1 fmt
))
2574 n
(string-to-number (match-string 2 fmt
)))
2576 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2577 (setq org-tbl-calc-modes
2580 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2581 (?s . sci
) (?e . eng
))))
2583 (setq fmt
(replace-match "" t t fmt
)))
2584 (if (string-match "T" fmt
)
2585 (setq duration t numbers t
2586 duration-output-format nil
2587 fmt
(replace-match "" t t fmt
)))
2588 (if (string-match "t" fmt
)
2590 duration-output-format org-table-duration-custom-format
2592 fmt
(replace-match "" t t fmt
)))
2593 (if (string-match "N" fmt
)
2595 fmt
(replace-match "" t t fmt
)))
2596 (if (string-match "L" fmt
)
2598 fmt
(replace-match "" t t fmt
)))
2599 (if (string-match "E" fmt
)
2601 fmt
(replace-match "" t t fmt
)))
2602 (while (string-match "[DRFS]" fmt
)
2603 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2604 (setq fmt
(replace-match "" t t fmt
)))
2605 (unless (string-match "\\S-" fmt
)
2607 (if (and (not suppress-const
) org-table-formula-use-constants
)
2608 (setq formula
(org-table-formula-substitute-names formula
)))
2609 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2611 (setq fields
(org-split-string
2612 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2614 ;; replace fields with duration values if relevant
2617 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2620 (setq fields
(mapcar
2622 (if (string-match "\\S-" x
)
2623 (number-to-string (string-to-number x
))
2626 (setq ndown
(1- ndown
))
2627 (setq form
(copy-sequence formula
)
2628 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2629 (if (and lispp literal
) (setq lispp
'literal
))
2631 ;; Insert row and column number of formula result field
2632 (while (string-match "[@$]#" form
)
2637 (if (equal (substring form
(match-beginning 0)
2638 (1+ (match-beginning 0)))
2640 (org-table-current-dline)
2641 (org-table-current-column))))
2644 ;; Check for old vertical references
2645 (setq form
(org-table-rewrite-old-row-references form
))
2646 ;; Insert remote references
2647 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2651 (org-table-make-reference
2652 (let ((rmtrng (org-table-get-remote-range
2653 (match-string 1 form
) (match-string 2 form
))))
2656 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2657 (org-table-time-string-to-seconds rmtrng
))
2659 keep-empty numbers lispp
))
2661 ;; Insert complex ranges
2662 (while (and (string-match org-table-range-regexp form
)
2663 (> (length (match-string 0 form
)) 1))
2664 (setq formrg
(save-match-data
2665 (org-table-get-range (match-string 0 form
) nil n0
)))
2668 (org-table-make-reference
2669 ;; possibly handle durations
2672 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2673 (org-table-time-string-to-seconds formrg
))
2675 keep-empty numbers lispp
)))
2676 (if (not (save-match-data
2677 (string-match (regexp-quote form
) formrpl
)))
2678 (setq form
(replace-match formrpl t t form
))
2679 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2680 ;; Insert simple ranges
2681 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2685 (org-table-make-reference
2687 fields
(string-to-number (match-string 1 form
))
2688 (string-to-number (match-string 2 form
)))
2689 keep-empty numbers lispp
))
2692 ;; Insert the references to fields in same row
2693 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2694 (setq n
(+ (string-to-number (match-string 1 form
))
2695 (if (match-end 2) n0
0))
2696 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2697 (unless x
(user-error "Invalid field specifier \"%s\""
2698 (match-string 0 form
)))
2699 (setq form
(replace-match
2701 (org-table-make-reference
2702 x keep-empty numbers lispp
))
2706 (setq ev
(condition-case nil
2707 (eval (eval (read form
)))
2709 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2710 ev
(if duration
(org-table-time-seconds-to-string
2711 (string-to-number ev
)
2712 duration-output-format
) ev
))
2713 (or (fboundp 'calc-eval
)
2714 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2715 ;; Use <...> time-stamps so that Calc can handle them
2716 (setq form
(replace-regexp-in-string org-ts-regexp3
"<\\1>" form
))
2717 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2718 (when (string-match org-ts-regexp2 form
)
2719 (let* ((ts (match-string 0 form
))
2720 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2721 (system-time-locale "C")
2722 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2723 (cdr org-time-stamp-formats
))
2724 (car org-time-stamp-formats
))))
2725 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2727 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2729 (calc-eval (cons form org-tbl-calc-modes
)
2730 (when (and (not keep-empty
) numbers
) 'num
)))
2731 ev
(if duration
(org-table-time-seconds-to-string
2732 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2733 (string-to-number (org-table-time-string-to-seconds ev
))
2734 (string-to-number ev
))
2735 duration-output-format
)
2738 (when org-table-formula-debug
2739 (with-output-to-temp-buffer "*Substitution History*"
2740 (princ (format "Substitution history of formula
2744 $1-> %s\n" orig formula form0 form
))
2746 (princ (format " %s^\nError: %s"
2747 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2748 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2750 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2751 (setq bw
(get-buffer-window "*Substitution History*"))
2752 (org-fit-window-to-buffer bw
)
2753 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2754 (unless (let (inhibit-redisplay)
2755 (y-or-n-p "Debugging Formula. Continue to next? "))
2757 (user-error "Abort"))
2760 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2761 (org-table-justify-field-maybe
2762 (format org-table-formula-field-format
2763 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2764 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2765 (call-interactively 'org-return
)
2767 (and down
(org-table-maybe-recalculate-line))
2768 (or suppress-align
(and org-table-may-need-update
2769 (org-table-align))))))
2771 (defun org-table-put-field-property (prop value
)
2773 (put-text-property (progn (skip-chars-backward "^|") (point))
2774 (progn (skip-chars-forward "^|") (point))
2777 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2778 "Get a calc vector from a column, according to descriptor DESC.
2779 Optional arguments TBEG and COL can give the beginning of the table and
2780 the current column, to avoid unnecessary parsing.
2782 HIGHLIGHT means just highlight the range.
2784 When CORNERS-ONLY is set, only return the corners of the range as
2785 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2786 in the buffer and column1 and column2 are table column numbers."
2787 (if (not (equal (string-to-char desc
) ?
@))
2788 (setq desc
(concat "@" desc
)))
2790 (or tbeg
(setq tbeg
(org-table-begin)))
2791 (or col
(setq col
(org-table-current-column)))
2792 (let ((thisline (org-current-line))
2793 beg end c1 c2 r1 r2 rangep tmp
)
2794 (unless (string-match org-table-range-regexp desc
)
2795 (user-error "Invalid table range specifier `%s'" desc
))
2796 (setq rangep
(match-end 3)
2797 r1
(and (match-end 1) (match-string 1 desc
))
2798 r2
(and (match-end 4) (match-string 4 desc
))
2799 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2800 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2802 (and c1
(setq c1
(+ (string-to-number c1
)
2803 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2804 (and c2
(setq c2
(+ (string-to-number c2
)
2805 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2806 (if (equal r1
"") (setq r1 nil
))
2807 (if (equal r2
"") (setq r2 nil
))
2808 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2809 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2810 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2811 (if (not r1
) (setq r1 thisline
))
2812 (if (not r2
) (setq r2 thisline
))
2813 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2814 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2815 (if (and (not corners-only
)
2816 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2820 (while (not (looking-at org-table-dataline-regexp
))
2821 (beginning-of-line 2))
2822 (prog1 (org-trim (org-table-get-field c1
))
2823 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2824 ;; A range, return a vector
2825 ;; First sort the numbers to get a regular rectangle
2826 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2827 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2829 ;; Only return the corners of the range
2831 ;; Copy the range values into a list
2833 (while (not (looking-at org-table-dataline-regexp
))
2834 (beginning-of-line 2))
2835 (org-table-goto-column c1
)
2838 (while (not (looking-at org-table-dataline-regexp
))
2839 (beginning-of-line 0))
2840 (org-table-goto-column c2
)
2843 (org-table-highlight-rectangle
2844 beg
(progn (skip-chars-forward "^|\n") (point))))
2845 ;; return string representation of calc vector
2847 (apply 'append
(org-table-copy-region beg end
))))))))
2849 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2850 "Analyze descriptor DESC and retrieve the corresponding line number.
2851 The cursor is currently in line CLINE, the table begins in line BLINE,
2852 and TABLE is a vector with line types."
2853 (if (string-match "^[0-9]+$" desc
)
2854 (aref org-table-dlines
(string-to-number desc
))
2855 (setq cline
(or cline
(org-current-line))
2856 bline
(or bline org-table-current-begin-line
)
2857 table
(or table org-table-current-line-types
))
2859 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2861 (and (not (match-end 3)) (not (match-end 6)))
2862 (and (match-end 3) (match-end 6) (not (match-end 5))))
2863 (user-error "Invalid row descriptor `%s'" desc
))
2864 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2865 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2866 (odir (and (match-end 5) (match-string 5 desc
)))
2867 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2869 (rel (and (match-end 6)
2870 (or (and (match-end 1) (not (match-end 3)))
2872 (if (and hn
(not hdir
))
2875 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2876 (if (and (not hn
) on
(not odir
))
2877 (user-error "Should never happen");;(aref org-table-dlines on)
2878 (if (and hn
(> hn
0))
2879 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2880 nil hn cline desc
)))
2882 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2883 rel on cline desc
)))
2886 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2887 "FIXME: Needs more documentation."
2888 (let ((l (length table
)))
2890 (while (and (setq i
(+ i
(if backwards -
1 1)))
2892 (not (eq (aref table i
) type
))
2893 (if (and relative
(eq (aref table i
) 'hline
))
2895 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2896 ((eq org-table-relative-ref-may-cross-hline
'error
)
2897 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2898 (t (setq i
(- i
(if backwards -
1 1))
2903 (if (or (< i
0) (>= i l
))
2904 (user-error "Row descriptor %s used in line %d leads outside table"
2908 (defun org-table-rewrite-old-row-references (s)
2909 (if (string-match "&[-+0-9I]" s
)
2910 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2913 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2914 "Convert list ELEMENTS to something appropriate to insert into formula.
2915 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2916 NUMBERS indicates that everything should be converted to numbers.
2917 LISPP non-nil means to return something appropriate for a Lisp
2918 list, 'literal is for the format specifier L."
2919 ;; Calc nan (not a number) is used for the conversion of the empty
2920 ;; field to a reference for several reasons: (i) It is accepted in a
2921 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2922 ;; (ii) In a single field (not in range) it can be distinguished
2923 ;; from "(nan)" which is the reference made from a single field
2924 ;; containing "nan".
2925 (if (stringp elements
)
2928 (if (eq lispp
'literal
)
2930 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2931 (if (string-match "\\S-" elements
)
2933 (when numbers
(setq elements
(number-to-string
2934 (string-to-number elements
))))
2935 (concat "(" elements
")"))
2936 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2941 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2943 (setq elements
(or elements
'("")))
2947 (if (eq lispp
'literal
)
2949 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2951 (concat "[" (mapconcat
2953 (if (string-match "\\S-" x
)
2955 (number-to-string (string-to-number x
))
2957 (if (or (not keep-empty
) numbers
) "0" "nan")))
2962 (defun org-table-set-constants ()
2963 "Set `org-table-formula-constants-local' in the current buffer."
2964 (let (cst consts const-str
)
2966 (goto-char (point-min))
2967 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
2968 (setq const-str
(substring-no-properties (match-string 1)))
2969 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
2972 (while (setq e
(pop consts
))
2973 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
2974 (if (assoc-string (match-string 1 e
) cst
)
2975 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
2976 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
2977 (setq org-table-formula-constants-local cst
)))))))
2980 (defun org-table-recalculate (&optional all noalign
)
2981 "Recalculate the current table line by applying all stored formulas.
2982 With prefix arg ALL, do this for all lines in the table.
2983 With the prefix argument ALL is `(16)' \
2984 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2985 it is the symbol `iterate', recompute the table until it no longer changes.
2986 If NOALIGN is not nil, do not re-align the table after the computations
2987 are done. This is typically used internally to save time, if it is
2988 known that the table will be realigned a little later anyway."
2990 (or (memq this-command org-recalc-commands
)
2991 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2992 (unless (org-at-table-p) (user-error "Not at a table"))
2993 (if (or (eq all
'iterate
) (equal all
'(16)))
2995 (org-table-get-specials)
2996 (let* ((eqlist (sort (org-table-get-stored-formulas)
2997 (lambda (a b
) (string< (car a
) (car b
)))))
2998 (eqlist1 (copy-sequence eqlist
))
2999 (inhibit-redisplay (not debug-on-error
))
3000 (line-re org-table-dataline-regexp
)
3001 (thisline (org-current-line))
3002 (thiscol (org-table-current-column))
3004 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3005 ;; Insert constants in all formulas
3008 (when (string-match "\\`$[<>]" (car x
))
3010 (setq x
(cons (substring
3011 (org-table-formula-handle-first/last-rc
3014 (if (assoc (car x
) eqlist1
)
3015 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3018 (org-table-formula-handle-first/last-rc
(car x
))
3019 (org-table-formula-substitute-names
3020 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3022 ;; Split the equation list
3023 (while (setq eq
(pop eqlist
))
3024 (if (<= (string-to-char (car eq
)) ?
9)
3027 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3028 ;; Expand ranges in lhs of formulas
3029 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3031 ;; Get the correct line range to process
3034 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3035 (goto-char (setq beg
(org-table-begin)))
3036 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3037 ;; This is a table with marked lines, compute selected lines
3038 (setq line-re org-table-recalculate-regexp
)
3039 ;; Move forward to the first non-header line
3040 (if (and (re-search-forward org-table-dataline-regexp end t
)
3041 (re-search-forward org-table-hline-regexp end t
)
3042 (re-search-forward org-table-dataline-regexp end t
))
3043 (setq beg
(match-beginning 0))
3044 nil
))) ;; just leave beg where it is
3045 (setq beg
(point-at-bol)
3046 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3048 (and all
(message "Re-applying formulas to full table..."))
3050 ;; First find the named fields, and mark them untouchable.
3051 ;; Also check if several field/range formulas try to set the same field.
3052 (remove-text-properties beg end
'(org-untouchable t
))
3053 (while (setq eq
(pop eqlname
))
3055 a
(assoc name org-table-named-field-locations
))
3057 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3059 (when (member name1 seen-fields
)
3060 (user-error "Several field/range formulas try to set %s" name1
))
3061 (push name1 seen-fields
)
3064 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3067 (aref org-table-dlines
3068 (string-to-number (match-string 1 name
)))
3069 (error (user-error "Invalid row number in %s"
3071 (string-to-number (match-string 2 name
)))))
3072 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3073 (message "Re-applying formula to field: %s" name
)
3074 (org-goto-line (nth 1 a
))
3075 (org-table-goto-column (nth 2 a
))
3076 (push (append a
(list (cdr eq
))) eqlname1
)
3077 (org-table-put-field-property :org-untouchable t
)))
3078 (setq eqlname1
(nreverse eqlname1
))
3080 ;; Now evaluate the column formulas, but skip fields covered by
3083 (while (re-search-forward line-re end t
)
3084 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3085 ;; Unprotected line, recalculate
3086 (and all
(message "Re-applying formulas to full table...(line %d)"
3087 (setq cnt
(1+ cnt
))))
3088 (setq org-last-recalc-line
(org-current-line))
3090 (while (setq entry
(pop eql
))
3091 (org-goto-line org-last-recalc-line
)
3092 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3093 (unless (get-text-property (point) :org-untouchable
)
3094 (org-table-eval-formula nil
(cdr entry
)
3095 'noalign
'nocst
'nostore
'noanalysis
)))))
3097 ;; Now evaluate the field formulas
3098 (while (setq eq
(pop eqlname1
))
3099 (message "Re-applying formula to field: %s" (car eq
))
3100 (org-goto-line (nth 1 eq
))
3101 (org-table-goto-column (nth 2 eq
))
3102 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3103 'nostore
'noanalysis
))
3105 (org-goto-line thisline
)
3106 (org-table-goto-column thiscol
)
3107 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3108 (or noalign
(and org-table-may-need-update
(org-table-align))
3109 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3111 ;; back to initial position
3112 (message "Re-applying formulas...done")
3113 (org-goto-line thisline
)
3114 (org-table-goto-column thiscol
)
3115 (or noalign
(and org-table-may-need-update
(org-table-align))
3116 (and all
(message "Re-applying formulas...done"))))))
3119 (defun org-table-iterate (&optional arg
)
3120 "Recalculate the table until it does not change anymore.
3121 The maximum number of iterations is 10, but you can choose a different value
3122 with the prefix ARG."
3124 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3126 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3131 (org-table-recalculate 'all
)
3132 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3133 (if (not (string= lasttbl thistbl
))
3134 (setq lasttbl thistbl
)
3136 (message "Convergence after %d iterations" i
)
3137 (message "Table was already stable"))
3139 (user-error "No convergence after %d iterations" i
))))
3142 (defun org-table-recalculate-buffer-tables ()
3143 "Recalculate all tables in the current buffer."
3148 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3151 (defun org-table-iterate-buffer-tables ()
3152 "Iterate all tables in the buffer, to converge inter-table dependencies."
3156 (checksum (md5 (buffer-string)))
3164 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3165 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3167 (message "Convergence after %d iterations" (- imax i
))
3169 (setq checksum c1
)))
3170 (user-error "No convergence after %d iterations" imax
))))))
3172 (defun org-table-expand-lhs-ranges (equations)
3173 "Expand list of formulas.
3174 If some of the RHS in the formulas are ranges or a row reference, expand
3175 them to individual field equations for each field."
3176 (let (e res lhs rhs range r1 r2 c1 c2
)
3177 (while (setq e
(pop equations
))
3178 (setq lhs
(car e
) rhs
(cdr e
))
3180 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3181 ;; This just refers to one fixed field
3183 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3184 ;; This just refers to one fixed named field
3186 ((string-match "^@[0-9]+$" lhs
)
3187 (loop for ic from
1 to org-table-current-ncol do
3188 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3189 (put-text-property 0 (length (caar res
))
3190 :orig-eqn e
(caar res
))))
3192 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3194 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3195 r2
(nth 2 range
) c2
(nth 3 range
))
3196 (setq r1
(org-table-line-to-dline r1
))
3197 (setq r2
(org-table-line-to-dline r2
'above
))
3198 (loop for ir from r1 to r2 do
3199 (loop for ic from c1 to c2 do
3200 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3201 (put-text-property 0 (length (caar res
))
3202 :orig-eqn e
(caar res
)))))))
3205 (defun org-table-formula-handle-first/last-rc
(s)
3206 "Replace @<, @>, $<, $> with first/last row/column of the table.
3207 So @< and $< will always be replaced with @1 and $1, respectively.
3208 The advantage of these special markers are that structure editing of
3209 the table will not change them, while @1 and $1 will be modified
3210 when a line/row is swapped out of that privileged position. So for
3211 formulas that use a range of rows or columns, it may often be better
3212 to anchor the formula with \"I\" row markers, or to offset from the
3213 borders of the table using the @< @> $< $> makers."
3214 (let (n nmax len char
(start 0))
3215 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3218 (setq start
(match-end 3))
3219 (setq nmax
(if (equal (match-string 1 s
) "@")
3220 (1- (length org-table-dlines
))
3221 org-table-current-ncol
)
3222 len
(- (match-end 2) (match-beginning 2))
3223 char
(string-to-char (match-string 2 s
))
3227 (if (or (< n
1) (> n nmax
))
3228 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3229 (match-string 0 s
) s
))
3230 (setq start
(match-beginning 0))
3231 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3234 (defun org-table-formula-substitute-names (f)
3235 "Replace $const with values in string F."
3236 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3237 ;; First, check for column names
3238 (while (setq start
(string-match org-table-column-name-regexp f start
))
3239 (setq start
(1+ start
))
3240 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3241 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3242 ;; Parameters and constants
3244 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3246 (setq start
(match-end 2))
3247 (setq start
(1+ start
))
3248 (if (setq a
(save-match-data
3249 (org-table-get-constant (match-string 1 f
))))
3250 (setq f
(replace-match
3251 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3252 (if org-table-formula-debug
3253 (put-text-property 0 (length f
) :orig-formula f1 f
))
3256 (defun org-table-get-constant (const)
3257 "Find the value for a parameter or constant in a formula.
3258 Parameters get priority."
3259 (or (cdr (assoc const org-table-local-parameters
))
3260 (cdr (assoc const org-table-formula-constants-local
))
3261 (cdr (assoc const org-table-formula-constants
))
3262 (and (fboundp 'constants-get
) (constants-get const
))
3263 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3264 (org-entry-get nil
(substring const
5) 'inherit
))
3267 (defvar org-table-fedit-map
3268 (let ((map (make-sparse-keymap)))
3269 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3270 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3271 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3272 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3273 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3274 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3275 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3276 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3277 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3278 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3279 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3280 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3281 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3282 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3283 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3284 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3285 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3286 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3287 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3288 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3291 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3293 ["Finish and Install" org-table-fedit-finish t
]
3294 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3295 ["Abort" org-table-fedit-abort t
]
3297 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3298 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3300 "Shift Reference at Point"
3301 ["Up" org-table-fedit-ref-up t
]
3302 ["Down" org-table-fedit-ref-down t
]
3303 ["Left" org-table-fedit-ref-left t
]
3304 ["Right" org-table-fedit-ref-right t
]
3306 "Change Test Row for Column Formulas"
3307 ["Up" org-table-fedit-line-up t
]
3308 ["Down" org-table-fedit-line-down t
]
3310 ["Scroll Table Window" org-table-fedit-scroll t
]
3311 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3312 ["Show Table Grid" org-table-fedit-toggle-coordinates
3313 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3314 org-table-overlay-coordinates
)]
3316 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3317 :style toggle
:selected org-table-buffer-is-an
]))
3322 (defun org-table-edit-formulas ()
3323 "Edit the formulas of the current table in a separate buffer."
3325 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3326 (beginning-of-line 0))
3327 (unless (org-at-table-p) (user-error "Not at a table"))
3328 (org-table-get-specials)
3329 (let ((key (org-table-current-field-formula 'key
'noerror
))
3330 (eql (sort (org-table-get-stored-formulas 'noerror
)
3331 'org-table-formula-less-p
))
3332 (pos (point-marker))
3334 (wc (current-window-configuration))
3335 (sel-win (selected-window))
3336 (titles '((column .
"# Column Formulas\n")
3337 (field .
"# Field and Range Formulas\n")
3338 (named .
"# Named Field Formulas\n")))
3340 (org-switch-to-buffer-other-window "*Edit Formulas*")
3342 ;; Keep global-font-lock-mode from turning on font-lock-mode
3343 (let ((font-lock-global-modes '(not fundamental-mode
)))
3345 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3346 (org-set-local 'org-pos pos
)
3347 (org-set-local 'org-window-configuration wc
)
3348 (org-set-local 'org-selected-window sel-win
)
3349 (use-local-map org-table-fedit-map
)
3350 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3351 (easy-menu-add org-table-fedit-menu
)
3352 (setq startline
(org-current-line))
3353 (while (setq entry
(pop eql
))
3355 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3356 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3357 ((string-match "^[0-9]" (car entry
)) 'column
)
3359 (when (setq title
(assq type titles
))
3360 (or (bobp) (insert "\n"))
3361 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3362 (setq titles
(remove title titles
)))
3363 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3364 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3365 (car entry
) " = " (cdr entry
) "\n"))
3366 (remove-text-properties 0 (length s
) '(face nil
) s
)
3368 (if (eq org-table-use-standard-references t
)
3369 (org-table-fedit-toggle-ref-type))
3370 (org-goto-line startline
)
3371 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3373 (defun org-table-fedit-post-command ()
3374 (when (not (memq this-command
'(lisp-complete-symbol)))
3375 (let ((win (selected-window)))
3378 (org-table-show-reference)
3380 (select-window win
)))))
3382 (defun org-table-formula-to-user (s)
3383 "Convert a formula from internal to user representation."
3384 (if (eq org-table-use-standard-references t
)
3385 (org-table-convert-refs-to-an s
)
3388 (defun org-table-formula-from-user (s)
3389 "Convert a formula from user to internal representation."
3390 (if org-table-use-standard-references
3391 (org-table-convert-refs-to-rc s
)
3394 (defun org-table-convert-refs-to-rc (s)
3395 "Convert spreadsheet references from A7 to @7$28.
3396 Works for single references, but also for entire formulas and even the
3399 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3402 ;; format match, just advance
3403 (setq start
(match-end 0)))
3404 ((and (> (match-beginning 0) 0)
3405 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3406 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3407 ;; 3.e5 or something like this.
3408 (setq start
(match-end 0)))
3409 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3410 ;; (member (match-string 1 s)
3411 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3413 ;; function name, just advance
3414 (setq start
(match-end 0)))
3416 (setq start
(match-beginning 0)
3418 (if (equal (match-string 2 s
) "&")
3419 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3421 (string-to-number (match-string 2 s
))
3422 (org-letters-to-number (match-string 1 s
))))
3426 (defun org-table-convert-refs-to-an (s)
3427 "Convert spreadsheet references from to @7$28 to AB7.
3428 Works for single references, but also for entire formulas and even the
3430 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3431 (setq s
(replace-match
3433 (org-number-to-letters
3434 (string-to-number (match-string 2 s
)))
3435 (string-to-number (match-string 1 s
)))
3437 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3438 (setq s
(replace-match (concat "\\1"
3439 (org-number-to-letters
3440 (string-to-number (match-string 2 s
))) "&")
3444 (defun org-letters-to-number (s)
3445 "Convert a base 26 number represented by letters into an integer.
3446 For example: AB -> 28."
3449 (while (> (length s
) 0)
3450 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3454 (defun org-number-to-letters (n)
3455 "Convert an integer into a base 26 number represented by letters.
3456 For example: 28 -> AB."
3459 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3463 (defun org-table-time-string-to-seconds (s)
3464 "Convert a time string into numerical duration in seconds.
3465 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3466 If S is a string representing a number, keep this number."
3469 (let (hour minus min sec res
)
3471 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3472 (setq minus
(< 0 (length (match-string 1 s
)))
3473 hour
(string-to-number (match-string 2 s
))
3474 min
(string-to-number (match-string 3 s
))
3475 sec
(string-to-number (match-string 4 s
)))
3477 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3478 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3479 ((and (not (string-match org-ts-regexp-both s
))
3480 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3481 (setq minus
(< 0 (length (match-string 1 s
)))
3482 hour
(string-to-number (match-string 2 s
))
3483 min
(string-to-number (match-string 3 s
)))
3485 (setq res
(- (+ (* hour
3600) (* min
60))))
3486 (setq res
(+ (* hour
3600) (* min
60)))))
3487 (t (setq res
(string-to-number s
))))
3488 (number-to-string res
))))
3490 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3491 "Convert a number of seconds to a time string.
3492 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3493 minutes or seconds."
3494 (let* ((secs0 (abs secs
))
3496 (cond ((eq output-format
'days
)
3497 (format "%.3f" (/ (float secs0
) 86400)))
3498 ((eq output-format
'hours
)
3499 (format "%.2f" (/ (float secs0
) 3600)))
3500 ((eq output-format
'minutes
)
3501 (format "%.1f" (/ (float secs0
) 60)))
3502 ((eq output-format
'seconds
)
3503 (format "%d" secs0
))
3504 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3505 (if (< secs
0) (concat "-" res
) res
)))
3507 (defun org-table-fedit-convert-buffer (function)
3508 "Convert all references in this buffer, using FUNCTION."
3509 (let ((line (org-current-line)))
3510 (goto-char (point-min))
3512 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3513 (delete-region (point) (point-at-eol))
3514 (or (eobp) (forward-char 1)))
3515 (org-goto-line line
)))
3517 (defun org-table-fedit-toggle-ref-type ()
3518 "Convert all references in the buffer from B3 to @3$2 and back."
3520 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3521 (org-table-fedit-convert-buffer
3522 (if org-table-buffer-is-an
3523 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3524 (message "Reference type switched to %s"
3525 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3527 (defun org-table-fedit-ref-up ()
3528 "Shift the reference at point one row/hline up."
3530 (org-table-fedit-shift-reference 'up
))
3531 (defun org-table-fedit-ref-down ()
3532 "Shift the reference at point one row/hline down."
3534 (org-table-fedit-shift-reference 'down
))
3535 (defun org-table-fedit-ref-left ()
3536 "Shift the reference at point one field to the left."
3538 (org-table-fedit-shift-reference 'left
))
3539 (defun org-table-fedit-ref-right ()
3540 "Shift the reference at point one field to the right."
3542 (org-table-fedit-shift-reference 'right
))
3544 (defun org-table-fedit-shift-reference (dir)
3546 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3547 (if (memq dir
'(left right
))
3548 (org-rematch-and-replace 1 (eq dir
'left
))
3549 (user-error "Cannot shift reference in this direction")))
3550 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3551 ;; A B3-like reference
3552 (if (memq dir
'(up down
))
3553 (org-rematch-and-replace 2 (eq dir
'up
))
3554 (org-rematch-and-replace 1 (eq dir
'left
))))
3556 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3557 ;; An internal reference
3558 (if (memq dir
'(up down
))
3559 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3560 (org-rematch-and-replace 5 (eq dir
'left
))))))
3562 (defun org-rematch-and-replace (n &optional decr hline
)
3563 "Re-match the group N, and replace it with the shifted reference."
3564 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3565 (goto-char (match-beginning n
))
3566 (and (looking-at (regexp-quote (match-string n
)))
3567 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3570 (defun org-table-shift-refpart (ref &optional decr hline
)
3571 "Shift a reference part REF.
3572 If DECR is set, decrease the references row/column, else increase.
3573 If HLINE is set, this may be a hline reference, it certainly is not
3574 a translation reference."
3576 (let* ((sign (string-match "^[-+]" ref
)) n
)
3578 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3580 ((and hline
(string-match "^I+" ref
))
3581 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3582 (setq n
(+ n
(if decr -
1 1)))
3583 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3585 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3587 (concat sign
(make-string n ?I
)))
3589 ((string-match "^[0-9]+" ref
)
3590 (setq n
(string-to-number (concat sign ref
)))
3591 (setq n
(+ n
(if decr -
1 1)))
3593 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3594 (number-to-string (max 1 n
))))
3596 ((string-match "^[a-zA-Z]+" ref
)
3597 (org-number-to-letters
3598 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3600 (t (user-error "Cannot shift reference"))))))
3602 (defun org-table-fedit-toggle-coordinates ()
3603 "Toggle the display of coordinates in the referenced table."
3605 (let ((pos (marker-position org-pos
)))
3606 (with-current-buffer (marker-buffer org-pos
)
3609 (org-table-toggle-coordinate-overlays)))))
3611 (defun org-table-fedit-finish (&optional arg
)
3612 "Parse the buffer for formula definitions and install them.
3613 With prefix ARG, apply the new formulas to the table."
3615 (org-table-remove-rectangle-highlight)
3616 (if org-table-use-standard-references
3618 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3619 (setq org-table-buffer-is-an nil
)))
3620 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3621 (goto-char (point-min))
3622 (while (re-search-forward
3623 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3625 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3626 form
(match-string 3))
3627 (setq form
(org-trim form
))
3628 (when (not (equal form
""))
3629 (while (string-match "[ \t]*\n[ \t]*" form
)
3630 (setq form
(replace-match " " t t form
)))
3631 (when (assoc var eql
)
3632 (user-error "Double formulas for %s" var
))
3633 (push (cons var form
) eql
)))
3635 (set-window-configuration org-window-configuration
)
3636 (select-window sel-win
)
3638 (unless (org-at-table-p)
3639 (user-error "Lost table position - cannot install formulas"))
3640 (org-table-store-formulas eql
)
3641 (move-marker pos nil
)
3642 (kill-buffer "*Edit Formulas*")
3644 (org-table-recalculate 'all
)
3645 (message "New formulas installed - press C-u C-c C-c to apply."))))
3647 (defun org-table-fedit-abort ()
3648 "Abort editing formulas, without installing the changes."
3650 (org-table-remove-rectangle-highlight)
3651 (let ((pos org-pos
) (sel-win org-selected-window
))
3652 (set-window-configuration org-window-configuration
)
3653 (select-window sel-win
)
3655 (move-marker pos nil
)
3656 (message "Formula editing aborted without installing changes")))
3658 (defun org-table-fedit-lisp-indent ()
3659 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3661 (let ((pos (point)) beg end ind
)
3662 (beginning-of-line 1)
3664 ((looking-at "[ \t]")
3666 (call-interactively 'lisp-indent-line
))
3667 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3668 ((not (fboundp 'pp-buffer
))
3669 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3670 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3671 (goto-char (- (match-end 0) 2))
3673 (setq ind
(make-string (current-column) ?\
))
3674 (condition-case nil
(forward-sexp 1)
3676 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3679 (narrow-to-region beg end
)
3680 (if (eq last-command this-command
)
3682 (goto-char (point-min))
3683 (setq this-command nil
)
3684 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3685 (replace-match " ")))
3687 (untabify (point-min) (point-max))
3688 (goto-char (1+ (point-min)))
3689 (while (re-search-forward "^." nil t
)
3690 (beginning-of-line 1)
3692 (goto-char (point-max))
3693 (org-delete-backward-char 1)))
3697 (defvar org-show-positions nil
)
3699 (defun org-table-show-reference (&optional local
)
3700 "Show the location/value of the $ expression at point."
3702 (org-table-remove-rectangle-highlight)
3704 (let ((pos (if local
(point) org-pos
))
3706 (org-inhibit-highlight-removal t
)
3707 (win (selected-window))
3708 (org-show-positions nil
)
3709 var name e what match dest
)
3710 (if local
(org-table-get-specials))
3712 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3713 (setq match
(concat (substring (match-string 0) 0 -
1)
3715 (substring (match-string 0) 0 -
1)
3718 ((or (org-at-regexp-p org-table-range-regexp2
)
3719 (org-at-regexp-p org-table-translate-regexp
)
3720 (org-at-regexp-p org-table-range-regexp
))
3723 (org-table-convert-refs-to-rc (match-string 0))))
3725 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3726 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3728 (t (user-error "No reference at point")))
3729 match
(and what
(or match
(match-string 0))))
3730 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3731 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3732 'secondary-selection
))
3733 (org-add-hook 'before-change-functions
3734 'org-table-remove-rectangle-highlight
)
3735 (if (eq what
'name
) (setq var
(substring match
1)))
3736 (when (eq what
'range
)
3737 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3738 (setq match
(org-table-formula-substitute-names match
)))
3742 (re-search-backward "^\\S-" nil t
)
3743 (beginning-of-line 1)
3744 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3747 (org-table-convert-refs-to-rc (match-string 1))))
3748 (org-table-add-rectangle-overlay
3749 (match-beginning 1) (match-end 1) face2
))))
3750 (if (and (markerp pos
) (marker-buffer pos
))
3751 (if (get-buffer-window (marker-buffer pos
))
3752 (select-window (get-buffer-window (marker-buffer pos
)))
3753 (org-switch-to-buffer-other-window (get-buffer-window
3754 (marker-buffer pos
)))))
3756 (org-table-force-dataline)
3758 (setq name
(substring dest
1))
3760 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3761 (setq e
(assoc name org-table-named-field-locations
))
3762 (org-goto-line (nth 1 e
))
3763 (org-table-goto-column (nth 2 e
)))
3764 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3765 (let ((l (string-to-number (match-string 1 dest
)))
3766 (c (string-to-number (match-string 2 dest
))))
3767 (org-goto-line (aref org-table-dlines l
))
3768 (org-table-goto-column c
)))
3769 (t (org-table-goto-column (string-to-number name
))))
3770 (move-marker pos
(point))
3771 (org-table-highlight-rectangle nil nil face2
))
3773 ((equal dest match
))
3778 (org-table-get-range match nil nil
'highlight
))
3780 ((setq e
(assoc var org-table-named-field-locations
))
3781 (org-goto-line (nth 1 e
))
3782 (org-table-goto-column (nth 2 e
))
3783 (org-table-highlight-rectangle (point) (point))
3784 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3785 ((setq e
(assoc var org-table-column-names
))
3786 (org-table-goto-column (string-to-number (cdr e
)))
3787 (org-table-highlight-rectangle (point) (point))
3788 (goto-char (org-table-begin))
3789 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3792 (goto-char (match-beginning 1))
3793 (org-table-highlight-rectangle)
3794 (message "Named column (column %s)" (cdr e
)))
3795 (user-error "Column name not found")))
3798 (org-table-goto-column (string-to-number (substring match
1)))
3799 (org-table-highlight-rectangle (point) (point))
3800 (message "Column %s" (substring match
1)))
3801 ((setq e
(assoc var org-table-local-parameters
))
3802 (goto-char (org-table-begin))
3803 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3805 (goto-char (match-beginning 1))
3806 (org-table-highlight-rectangle)
3807 (message "Local parameter."))
3808 (user-error "Parameter not found")))
3811 ((not var
) (user-error "No reference at point"))
3812 ((setq e
(assoc var org-table-formula-constants-local
))
3813 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3815 ((setq e
(assoc var org-table-formula-constants
))
3816 (message "Constant: $%s=%s in `org-table-formula-constants'."
3818 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3819 (message "Constant: $%s=%s, from `constants.el'%s."
3820 var e
(format " (%s units)" constants-unit-system
)))
3821 (t (user-error "Undefined name $%s" var
)))))
3823 (when (and org-show-positions
3824 (not (memq this-command
'(org-table-fedit-scroll
3825 org-table-fedit-scroll-down
))))
3826 (push pos org-show-positions
)
3827 (push org-table-current-begin-pos org-show-positions
)
3828 (let ((min (apply 'min org-show-positions
))
3829 (max (apply 'max org-show-positions
)))
3830 (goto-char min
) (recenter 0)
3832 (or (pos-visible-in-window-p max
) (recenter -
1))))
3833 (select-window win
))))
3835 (defun org-table-force-dataline ()
3836 "Make sure the cursor is in a dataline in a table."
3837 (unless (save-excursion
3838 (beginning-of-line 1)
3839 (looking-at org-table-dataline-regexp
))
3840 (let* ((re org-table-dataline-regexp
)
3841 (p1 (save-excursion (re-search-forward re nil
'move
)))
3842 (p2 (save-excursion (re-search-backward re nil
'move
))))
3844 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3846 ((or p1 p2
) (goto-char (or p1 p2
)))
3847 (t (user-error "No table dataline around here"))))))
3849 (defun org-table-fedit-line-up ()
3850 "Move cursor one line up in the window showing the table."
3852 (org-table-fedit-move 'previous-line
))
3854 (defun org-table-fedit-line-down ()
3855 "Move cursor one line down in the window showing the table."
3857 (org-table-fedit-move 'next-line
))
3859 (defun org-table-fedit-move (command)
3860 "Move the cursor in the window showing the table.
3861 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3862 (let ((org-table-allow-automatic-line-recalculation nil
)
3863 (pos org-pos
) (win (selected-window)) p
)
3864 (select-window (get-buffer-window (marker-buffer org-pos
)))
3866 (call-interactively command
)
3867 (while (and (org-at-table-p)
3868 (org-at-table-hline-p))
3869 (call-interactively command
))
3870 (or (org-at-table-p) (goto-char p
))
3871 (move-marker pos
(point))
3872 (select-window win
)))
3874 (defun org-table-fedit-scroll (N)
3876 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3877 (scroll-other-window N
)))
3879 (defun org-table-fedit-scroll-down (N)
3881 (org-table-fedit-scroll (- N
)))
3883 (defvar org-table-rectangle-overlays nil
)
3885 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3886 "Add a new overlay."
3887 (let ((ov (make-overlay beg end
)))
3888 (overlay-put ov
'face
(or face
'secondary-selection
))
3889 (push ov org-table-rectangle-overlays
)))
3891 (defun org-table-highlight-rectangle (&optional beg end face
)
3892 "Highlight rectangular region in a table."
3893 (setq beg
(or beg
(point)) end
(or end
(point)))
3894 (let ((b (min beg end
))
3897 (and (boundp 'org-show-positions
)
3898 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3899 (goto-char (min beg end
))
3900 (setq l1
(org-current-line)
3901 c1
(org-table-current-column))
3902 (goto-char (max beg end
))
3903 (setq l2
(org-current-line)
3904 c2
(org-table-current-column))
3905 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3907 (beginning-of-line 1)
3908 (loop for line from l1 to l2 do
3909 (when (looking-at org-table-dataline-regexp
)
3910 (org-table-goto-column c1
)
3911 (skip-chars-backward "^|\n") (setq beg
(point))
3912 (org-table-goto-column c2
)
3913 (skip-chars-forward "^|\n") (setq end
(point))
3914 (org-table-add-rectangle-overlay beg end face
))
3915 (beginning-of-line 2))
3917 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3919 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3920 "Remove the rectangle overlays."
3921 (unless org-inhibit-highlight-removal
3922 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3923 (mapc 'delete-overlay org-table-rectangle-overlays
)
3924 (setq org-table-rectangle-overlays nil
)))
3926 (defvar org-table-coordinate-overlays nil
3927 "Collects the coordinate grid overlays, so that they can be removed.")
3928 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3930 (defun org-table-overlay-coordinates ()
3931 "Add overlays to the table at point, to show row/column coordinates."
3933 (mapc 'delete-overlay org-table-coordinate-overlays
)
3934 (setq org-table-coordinate-overlays nil
)
3936 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3937 (goto-char (org-table-begin))
3938 (while (org-at-table-p)
3939 (setq eol
(point-at-eol))
3940 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3941 (push ov org-table-coordinate-overlays
)
3942 (setq hline
(looking-at org-table-hline-regexp
))
3943 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3944 (format "%4d" (setq id
(1+ id
)))))
3945 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3948 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3949 (setq beg
(1+ (match-beginning 0))
3951 s1
(concat "$" (int-to-string ic
))
3952 s2
(org-number-to-letters ic
)
3953 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3954 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3955 (push ov org-table-coordinate-overlays
)
3956 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3957 (beginning-of-line 2)))))
3960 (defun org-table-toggle-coordinate-overlays ()
3961 "Toggle the display of Row/Column numbers in tables."
3963 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3964 (message "Tables Row/Column numbers display turned %s"
3965 (if org-table-overlay-coordinates
"on" "off"))
3966 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3968 (unless org-table-overlay-coordinates
3969 (mapc 'delete-overlay org-table-coordinate-overlays
)
3970 (setq org-table-coordinate-overlays nil
)))
3973 (defun org-table-toggle-formula-debugger ()
3974 "Toggle the formula debugger in tables."
3976 (setq org-table-formula-debug
(not org-table-formula-debug
))
3977 (message "Formula debugging has been turned %s"
3978 (if org-table-formula-debug
"on" "off")))
3980 ;;; The orgtbl minor mode
3982 ;; Define a minor mode which can be used in other modes in order to
3983 ;; integrate the org-mode table editor.
3985 ;; This is really a hack, because the org-mode table editor uses several
3986 ;; keys which normally belong to the major mode, for example the TAB and
3987 ;; RET keys. Here is how it works: The minor mode defines all the keys
3988 ;; necessary to operate the table editor, but wraps the commands into a
3989 ;; function which tests if the cursor is currently inside a table. If that
3990 ;; is the case, the table editor command is executed. However, when any of
3991 ;; those keys is used outside a table, the function uses `key-binding' to
3992 ;; look up if the key has an associated command in another currently active
3993 ;; keymap (minor modes, major mode, global), and executes that command.
3994 ;; There might be problems if any of the keys used by the table editor is
3995 ;; otherwise used as a prefix key.
3997 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3998 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3999 ;; addresses this by checking explicitly for both bindings.
4001 ;; The optimized version (see variable `orgtbl-optimized') takes over
4002 ;; all keys which are bound to `self-insert-command' in the *global map*.
4003 ;; Some modes bind other commands to simple characters, for example
4004 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4005 ;; active, this binding is ignored inside tables and replaced with a
4006 ;; modified self-insert.
4009 (defvar orgtbl-mode-map
(make-keymap)
4010 "Keymap for `orgtbl-mode'.")
4012 (defvar org-old-auto-fill-inhibit-regexp nil
4013 "Local variable used by `orgtbl-mode'.")
4015 (defconst orgtbl-line-start-regexp
4016 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4017 "Matches a line belonging to an orgtbl.")
4019 (defconst orgtbl-extra-font-lock-keywords
4020 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4021 0 (quote 'org-table
) 'prepend
))
4022 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4024 ;; Install it as a minor mode.
4025 (put 'orgtbl-mode
:included t
)
4026 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4029 (define-minor-mode orgtbl-mode
4030 "The `org-mode' table editor as a minor mode for use in other modes."
4031 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4032 (org-load-modules-maybe)
4034 ((derived-mode-p 'org-mode
)
4035 ;; Exit without error, in case some hook functions calls this
4036 ;; by accident in org-mode.
4037 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4039 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4040 ;; Make sure we are first in minor-mode-map-alist
4041 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4042 ;; FIXME: maybe it should use emulation-mode-map-alists?
4043 (and c
(setq minor-mode-map-alist
4044 (cons c
(delq c minor-mode-map-alist
)))))
4045 (org-set-local (quote org-table-may-need-update
) t
)
4046 (org-add-hook 'before-change-functions
'org-before-change-function
4048 (org-set-local 'org-old-auto-fill-inhibit-regexp
4049 auto-fill-inhibit-regexp
)
4050 (org-set-local 'auto-fill-inhibit-regexp
4051 (if auto-fill-inhibit-regexp
4052 (concat orgtbl-line-start-regexp
"\\|"
4053 auto-fill-inhibit-regexp
)
4054 orgtbl-line-start-regexp
))
4055 (add-to-invisibility-spec '(org-cwidth))
4056 (when (fboundp 'font-lock-add-keywords
)
4057 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4058 (org-restart-font-lock))
4059 (easy-menu-add orgtbl-mode-menu
))
4061 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4062 (org-table-cleanup-narrow-column-properties)
4063 (org-remove-from-invisibility-spec '(org-cwidth))
4064 (remove-hook 'before-change-functions
'org-before-change-function t
)
4065 (when (fboundp 'font-lock-remove-keywords
)
4066 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4067 (org-restart-font-lock))
4068 (easy-menu-remove orgtbl-mode-menu
)
4069 (force-mode-line-update 'all
))))
4071 (defun org-table-cleanup-narrow-column-properties ()
4072 "Remove all properties related to narrow-column invisibility."
4073 (let ((s (point-min)))
4074 (while (setq s
(text-property-any s
(point-max)
4075 'display org-narrow-column-arrow
))
4076 (remove-text-properties s
(1+ s
) '(display t
)))
4077 (setq s
(point-min))
4078 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4079 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4080 (setq s
(point-min))
4081 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4082 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4084 (defun orgtbl-make-binding (fun n
&rest keys
)
4085 "Create a function for binding in the table minor mode.
4086 FUN is the command to call inside a table. N is used to create a unique
4087 command name. KEYS are keys that should be checked in for a command
4088 to execute outside of tables."
4091 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4093 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4094 "Outside of tables, run the binding of `"
4095 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
4100 (list 'call-interactively
(list 'quote fun
))
4101 (list 'let
'(orgtbl-mode)
4102 (list 'call-interactively
4105 (list 'key-binding k
))
4107 '('orgtbl-error
))))))))
4109 (defun orgtbl-error ()
4110 "Error when there is no default binding for a table key."
4112 (user-error "This key has no function outside tables"))
4114 (defun orgtbl-setup ()
4115 "Setup orgtbl keymaps."
4118 '(([(meta shift left
)] org-table-delete-column
)
4119 ([(meta left
)] org-table-move-column-left
)
4120 ([(meta right
)] org-table-move-column-right
)
4121 ([(meta shift right
)] org-table-insert-column
)
4122 ([(meta shift up
)] org-table-kill-row
)
4123 ([(meta shift down
)] org-table-insert-row
)
4124 ([(meta up
)] org-table-move-row-up
)
4125 ([(meta down
)] org-table-move-row-down
)
4126 ("\C-c\C-w" org-table-cut-region
)
4127 ("\C-c\M-w" org-table-copy-region
)
4128 ("\C-c\C-y" org-table-paste-rectangle
)
4129 ("\C-c\C-w" org-table-wrap-region
)
4130 ("\C-c-" org-table-insert-hline
)
4131 ("\C-c}" org-table-toggle-coordinate-overlays
)
4132 ("\C-c{" org-table-toggle-formula-debugger
)
4133 ("\C-m" org-table-next-row
)
4134 ([(shift return
)] org-table-copy-down
)
4135 ("\C-c?" org-table-field-info
)
4136 ("\C-c " org-table-blank-field
)
4137 ("\C-c+" org-table-sum
)
4138 ("\C-c=" org-table-eval-formula
)
4139 ("\C-c'" org-table-edit-formulas
)
4140 ("\C-c`" org-table-edit-field
)
4141 ("\C-c*" org-table-recalculate
)
4142 ("\C-c^" org-table-sort-lines
)
4143 ("\M-a" org-table-beginning-of-field
)
4144 ("\M-e" org-table-end-of-field
)
4145 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4147 (while (setq elt
(pop bindings
))
4148 (setq nfunc
(1+ nfunc
))
4149 (setq key
(org-key (car elt
))
4151 cmd
(orgtbl-make-binding fun nfunc key
))
4152 (org-defkey orgtbl-mode-map key cmd
))
4154 ;; Special treatment needed for TAB and RET
4155 (org-defkey orgtbl-mode-map
[(return)]
4156 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4157 (org-defkey orgtbl-mode-map
"\C-m"
4158 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4160 (org-defkey orgtbl-mode-map
[(tab)]
4161 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4162 (org-defkey orgtbl-mode-map
"\C-i"
4163 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4165 (org-defkey orgtbl-mode-map
[(shift tab
)]
4166 (orgtbl-make-binding 'org-table-previous-field
104
4167 [(shift tab
)] [(tab)] "\C-i"))
4170 (unless (featurep 'xemacs
)
4171 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4172 (orgtbl-make-binding 'org-table-previous-field
107
4173 [S-iso-lefttab
] [backtab] [(shift tab)]
4176 (org-defkey orgtbl-mode-map [backtab]
4177 (orgtbl-make-binding 'org-table-previous-field
108
4178 [backtab] [S-iso-lefttab] [(shift tab)]
4181 (org-defkey orgtbl-mode-map "\M-\C-m"
4182 (orgtbl-make-binding 'org-table-wrap-region 105
4183 "\M-\C-m" [(meta return)]))
4184 (org-defkey orgtbl-mode-map [(meta return)]
4185 (orgtbl-make-binding 'org-table-wrap-region 106
4186 [(meta return)] "\M-\C-m"))
4188 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4189 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4191 (when orgtbl-optimized
4192 ;; If the user wants maximum table support, we need to hijack
4193 ;; some standard editing functions
4194 (org-remap orgtbl-mode-map
4195 'self-insert-command 'orgtbl-self-insert-command
4196 'delete-char 'org-delete-char
4197 'delete-backward-char 'org-delete-backward-char)
4198 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4199 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4201 ["Create or convert" org-table-create-or-convert-from-region
4202 :active (not (org-at-table-p)) :keys "C-c |" ]
4204 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4205 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4206 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4207 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4209 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4210 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4211 ["Copy Field from Above"
4212 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4215 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4216 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4217 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4218 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4220 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4221 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4222 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4223 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4224 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4226 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4228 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4229 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4230 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4231 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4234 ["Insert table template" orgtbl-insert-radio-table
4235 (assq major-mode orgtbl-radio-table-templates)]
4236 ["Comment/uncomment table" orgtbl-toggle-comment t])
4238 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4239 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4240 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4241 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4242 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4243 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4244 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4245 ["Sum Column/Rectangle" org-table-sum
4246 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4247 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4249 org-table-toggle-formula-debugger :active (org-at-table-p)
4251 :style toggle :selected org-table-formula-debug]
4252 ["Show Col/Row Numbers"
4253 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4255 :style toggle :selected org-table-overlay-coordinates]
4259 (defun orgtbl-ctrl-c-ctrl-c (arg)
4260 "If the cursor is inside a table, realign the table.
4261 If it is a table to be sent away to a receiver, do it.
4262 With prefix arg, also recompute table."
4264 (let ((case-fold-search t) (pos (point)) action)
4266 (beginning-of-line 1)
4268 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4269 ((looking-at "[ \t]*|") pos)
4270 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4274 (org-table-maybe-eval-formula)
4276 (call-interactively 'org-table-recalculate)
4277 (org-table-maybe-recalculate-line))
4278 (call-interactively 'org-table-align)
4279 (when (orgtbl-send-table 'maybe)
4280 (run-hooks 'orgtbl-after-send-table-hook)))
4281 ((eq action 'recalc)
4282 (org-table-set-constants)
4284 (beginning-of-line 1)
4285 (skip-chars-backward " \r\n\t")
4286 (if (org-at-table-p)
4287 (org-call-with-arg 'org-table-recalculate t))))
4288 (t (let (orgtbl-mode)
4289 (call-interactively (key-binding "\C-c\C-c")))))))
4291 (defun orgtbl-create-or-convert-from-region (arg)
4292 "Create table or convert region to table, if no conflicting binding.
4293 This installs the table binding `C-c |', but only if there is no
4294 conflicting binding to this key outside orgtbl-mode."
4296 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4298 (call-interactively cmd)
4299 (call-interactively 'org-table-create-or-convert-from-region))))
4301 (defun orgtbl-tab (arg)
4302 "Justification and field motion for `orgtbl-mode'."
4304 (if arg (org-table-edit-field t)
4305 (org-table-justify-field-maybe)
4306 (org-table-next-field)))
4308 (defun orgtbl-ret ()
4309 "Justification and field motion for `orgtbl-mode'."
4313 (org-table-justify-field-maybe)
4314 (org-table-next-row)))
4316 (defun orgtbl-self-insert-command (N)
4317 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4318 If the cursor is in a table looking at whitespace, the whitespace is
4319 overwritten, and the table is not marked as requiring realignment."
4321 (if (and (org-at-table-p)
4323 (and org-table-auto-blank-field
4324 (member last-command
4325 '(orgtbl-hijacker-command-100
4326 orgtbl-hijacker-command-101
4327 orgtbl-hijacker-command-102
4328 orgtbl-hijacker-command-103
4329 orgtbl-hijacker-command-104
4330 orgtbl-hijacker-command-105
4332 (org-table-blank-field))
4335 (looking-at "[^|\n]* +|"))
4336 (let (org-table-may-need-update)
4337 (goto-char (1- (match-end 0)))
4338 (org-delete-backward-char 1)
4339 (goto-char (match-beginning 0))
4340 (self-insert-command N))
4341 (setq org-table-may-need-update t)
4344 (cmd (or (key-binding
4345 (or (and (listp function-key-map)
4346 (setq a (assoc last-input-event function-key-map))
4348 (vector last-input-event)))
4349 'self-insert-command)))
4350 (call-interactively cmd)
4351 (if (and org-self-insert-cluster-for-undo
4352 (eq cmd 'self-insert-command))
4353 (if (not (eq last-command 'orgtbl-self-insert-command))
4354 (setq org-self-insert-command-undo-counter 1)
4355 (if (>= org-self-insert-command-undo-counter 20)
4356 (setq org-self-insert-command-undo-counter 1)
4357 (and (> org-self-insert-command-undo-counter 0)
4359 (not (cadr buffer-undo-list)) ; remove nil entry
4360 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4361 (setq org-self-insert-command-undo-counter
4362 (1+ org-self-insert-command-undo-counter))))))))
4364 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4365 "Regular expression matching exponentials as produced by calc.")
4367 (defun orgtbl-export (table target)
4368 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4369 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4370 org-table-last-alignment org-table-last-column-widths
4372 (if (not (fboundp func))
4373 (user-error "Cannot export orgtbl table to %s" target))
4374 (setq lines (org-table-clean-before-export lines))
4378 (if (string-match org-table-hline-regexp x)
4380 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4382 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4384 (loop for i from (1- maxcol) downto 0 do
4385 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4386 (setq column (delq nil column))
4387 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4388 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
4389 (funcall func table nil)))
4391 (defun orgtbl-gather-send-defs ()
4392 "Gather a plist of :name, :transform, :params for each destination before
4395 (goto-char (org-table-begin))
4397 (beginning-of-line 0)
4398 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4399 (let ((name (org-no-properties (match-string 1)))
4400 (transform (intern (match-string 2)))
4401 (params (if (match-end 3)
4402 (read (concat "(" (match-string 3) ")")))))
4403 (push (list :name name :transform transform :params params)
4405 (beginning-of-line 0)))
4408 (defun orgtbl-send-replace-tbl (name txt)
4409 "Find and replace table NAME with TXT."
4411 (goto-char (point-min))
4412 (unless (re-search-forward
4413 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4414 (user-error "Don't know where to insert translated table"))
4415 (goto-char (match-beginning 0))
4416 (beginning-of-line 2)
4418 (let ((beg (point)))
4419 (unless (re-search-forward
4420 (concat "END RECEIVE ORGTBL +" name) nil t)
4421 (user-error "Cannot find end of insertion region"))
4422 (beginning-of-line 1)
4423 (delete-region beg (point))))
4427 (defun org-table-to-lisp (&optional txt)
4428 "Convert the table at point to a Lisp structure.
4429 The structure will be a list. Each item is either the symbol `hline'
4430 for a horizontal separator line, or a list of field values as strings.
4431 The table is taken from the parameter TXT, or from the buffer at point."
4433 (unless (org-at-table-p)
4434 (user-error "No table at point")))
4436 (buffer-substring-no-properties (org-table-begin)
4438 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4442 (if (string-match org-table-hline-regexp x)
4444 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4447 (defun orgtbl-send-table (&optional maybe)
4448 "Send a transformed version of this table to the receiver position.
4449 With argument MAYBE, fail quietly if no transformation is defined for
4453 (unless (org-at-table-p) (user-error "Not at a table"))
4454 ;; when non-interactive, we assume align has just happened.
4455 (when (org-called-interactively-p 'any) (org-table-align))
4456 (let ((dests (orgtbl-gather-send-defs))
4457 (txt (buffer-substring-no-properties (org-table-begin)
4460 (unless dests (if maybe (throw 'exit nil)
4461 (user-error "Don't know how to transform this table")))
4462 (dolist (dest dests)
4463 (let* ((name (plist-get dest :name))
4464 (transform (plist-get dest :transform))
4465 (params (plist-get dest :params))
4466 (skip (plist-get params :skip))
4467 (skipcols (plist-get params :skipcols))
4468 (no-escape (plist-get params :no-escape))
4470 (lines (org-table-clean-before-export
4472 (org-split-string txt "[ \t]*\n[ \t]*"))))
4473 (i0 (if org-table-clean-did-remove-column 2 1))
4474 (lines (if no-escape lines
4475 (mapcar (lambda(l) (replace-regexp-in-string
4476 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4479 (if (string-match org-table-hline-regexp x)
4481 (org-remove-by-index
4482 (org-split-string (org-trim x) "\\s-*|\\s-*")
4485 (fun (if (= i0 2) 'cdr 'identity))
4486 (org-table-last-alignment
4487 (org-remove-by-index (funcall fun org-table-last-alignment)
4489 (org-table-last-column-widths
4490 (org-remove-by-index (funcall fun org-table-last-column-widths)
4492 (txt (if (fboundp transform)
4493 (funcall transform table params)
4494 (user-error "No such transformation function %s" transform))))
4495 (orgtbl-send-replace-tbl name txt))
4496 (setq ntbl (1+ ntbl)))
4497 (message "Table converted and installed at %d receiver location%s"
4498 ntbl (if (> ntbl 1) "s" ""))
4503 (defun org-remove-by-index (list indices &optional i0)
4504 "Remove the elements in LIST with indices in INDICES.
4505 First element has index 0, or I0 if given."
4508 (if (integerp indices) (setq indices (list indices)))
4509 (setq i0 (1- (or i0 0)))
4510 (delq :rm (mapcar (lambda (x)
4512 (if (memq i0 indices) :rm x))
4515 (defun orgtbl-toggle-comment ()
4516 "Comment or uncomment the orgtbl at point."
4518 (let* ((case-fold-search t)
4519 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4520 (re2 (concat "^" orgtbl-line-start-regexp))
4521 (commented (save-excursion (beginning-of-line 1)
4522 (cond ((looking-at re1) t)
4523 ((looking-at re2) nil)
4524 (t (user-error "Not at an org table")))))
4525 (re (if commented re1 re2))
4528 (beginning-of-line 1)
4529 (while (looking-at re) (beginning-of-line 0))
4530 (beginning-of-line 2)
4532 (while (looking-at re) (beginning-of-line 2))
4534 (comment-region beg end (if commented '(4) nil))))
4536 (defun orgtbl-insert-radio-table ()
4537 "Insert a radio table template appropriate for this major mode."
4539 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4542 (unless e (user-error "No radio table setup defined for %s" major-mode))
4543 (setq name (read-string "Table name: "))
4544 (while (string-match "%n" txt)
4545 (setq txt (replace-match name t t txt)))
4546 (or (bolp) (insert "\n"))
4551 ;; Dynamically bound input and output for table formatting.
4552 (defvar *orgtbl-table* nil
4553 "Carries the current table through formatting routines.")
4554 (defvar *orgtbl-rtn* nil
4555 "Formatting routines push the output lines here.")
4556 ;; Formatting parameters for the current table section.
4557 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4558 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4559 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4560 (defvar *orgtbl-fmt* nil "Format for each entry.")
4561 (defvar *orgtbl-efmt* nil "Format for numbers.")
4562 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4563 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4564 (defvar *orgtbl-lstart* nil "Text starting a row.")
4565 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4566 (defvar *orgtbl-lend* nil "Text ending a row.")
4567 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4569 (defsubst orgtbl-get-fmt (fmt i)
4570 "Retrieve the format from FMT corresponding to the Ith column."
4571 (if (and (not (functionp fmt)) (consp fmt))
4575 (defsubst orgtbl-apply-fmt (fmt &rest args)
4576 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4577 (cond ((functionp fmt) (apply fmt args))
4578 (fmt (apply 'format fmt args))
4582 (defsubst orgtbl-eval-str (str)
4583 "If STR is a function, evaluate it with no arguments."
4588 (defun orgtbl-format-line (line)
4589 "Format LINE as a table row."
4590 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4596 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4597 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4598 (orgtbl-apply-fmt efmt (match-string 1 f)
4601 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4602 *orgtbl-default-fmt*)
4605 (push (if *orgtbl-lfmt*
4606 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4607 (concat (orgtbl-eval-str *orgtbl-lstart*)
4608 (mapconcat 'identity line *orgtbl-sep*)
4609 (orgtbl-eval-str *orgtbl-lend*)))
4612 (defun orgtbl-format-section (section-stopper)
4613 "Format lines until the first occurrence of SECTION-STOPPER."
4616 (while (not (eq (car *orgtbl-table*) section-stopper))
4617 (if prevline (orgtbl-format-line prevline))
4618 (setq prevline (pop *orgtbl-table*)))
4619 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4620 (*orgtbl-lend* *orgtbl-llend*)
4621 (*orgtbl-lfmt* *orgtbl-llfmt*))
4622 (orgtbl-format-line prevline))))))
4625 (defun orgtbl-to-generic (table params &optional backend)
4626 "Convert the orgtbl-mode TABLE to some other format.
4627 This generic routine can be used for many standard cases.
4628 TABLE is a list, each entry either the symbol `hline' for a horizontal
4629 separator line, or a list of fields for that line.
4630 PARAMS is a property list of parameters that can influence the conversion.
4631 A third optional argument BACKEND can be used to convert the content of
4632 the cells using a specific export back-end.
4634 For the generic converter, some parameters are obligatory: you need to
4635 specify either :lfmt, or all of (:lstart :lend :sep).
4637 Valid parameters are:
4639 :splice When set to t, return only table body lines, don't wrap
4640 them into :tstart and :tend. Default is nil. When :splice
4641 is non-nil, this also means that the exporter should not look
4642 for and interpret header and footer sections.
4644 :hline String to be inserted on horizontal separation lines.
4645 May be nil to ignore hlines.
4647 :sep Separator between two fields
4648 :remove-nil-lines Do not include lines that evaluate to nil.
4650 Each in the following group may be either a string or a function
4651 of no arguments returning a string:
4653 :tstart String to start the table. Ignored when :splice is t.
4654 :tend String to end the table. Ignored when :splice is t.
4655 :lstart String to start a new table line.
4656 :llstart String to start the last table line, defaults to :lstart.
4657 :lend String to end a table line
4658 :llend String to end the last table line, defaults to :lend.
4660 Each in the following group may be a string, a function of one
4661 argument (the field or line) returning a string, or a plist
4662 mapping columns to either of the above:
4664 :lfmt Format for entire line, with enough %s to capture all fields.
4665 If this is present, :lstart, :lend, and :sep are ignored.
4666 :llfmt Format for the entire last line, defaults to :lfmt.
4667 :fmt A format to be used to wrap the field, should contain
4668 %s for the original field value. For example, to wrap
4669 everything in dollars, you could use :fmt \"$%s$\".
4670 This may also be a property list with column numbers and
4671 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4672 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4673 Same as above, specific for the header lines in the table.
4674 All lines before the first hline are treated as header.
4675 If any of these is not present, the data line value is used.
4677 This may be either a string or a function of two arguments:
4679 :efmt Use this format to print numbers with exponentials.
4680 The format should have %s twice for inserting mantissa
4681 and exponent, for example \"%s\\\\times10^{%s}\". This
4682 may also be a property list with column numbers and
4683 formats. :fmt will still be applied after :efmt.
4685 In addition to this, the parameters :skip and :skipcols are always handled
4686 directly by `orgtbl-send-table'. See manual."
4687 (let* ((splicep (plist-get params :splice))
4688 (hline (plist-get params :hline))
4689 (skipheadrule (plist-get params :skipheadrule))
4690 (remove-nil-linesp (plist-get params :remove-nil-lines))
4691 (remove-newlines (plist-get params :remove-newlines))
4692 (*orgtbl-hline* hline)
4693 (*orgtbl-table* table)
4694 (*orgtbl-sep* (plist-get params :sep))
4695 (*orgtbl-efmt* (plist-get params :efmt))
4696 (*orgtbl-lstart* (plist-get params :lstart))
4697 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4698 (*orgtbl-lend* (plist-get params :lend))
4699 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4700 (*orgtbl-lfmt* (plist-get params :lfmt))
4701 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4702 (*orgtbl-fmt* (plist-get params :fmt))
4704 ;; Convert cells content to backend BACKEND
4706 (setq *orgtbl-table*
4711 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4716 (when (plist-member params :tstart)
4717 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4718 (if tstart (push tstart *orgtbl-rtn*)))))
4719 ;; If we have a heading, format it and handle the trailing hline.
4720 (if (and (not splicep)
4721 (or (consp (car *orgtbl-table*))
4722 (consp (nth 1 *orgtbl-table*)))
4723 (memq 'hline (cdr *orgtbl-table*)))
4725 (when (eq 'hline (car *orgtbl-table*))
4726 ;; There is a hline before the first data line
4727 (and hline (push hline *orgtbl-rtn*))
4728 (pop *orgtbl-table*))
4729 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4731 (*orgtbl-llstart* (or (plist-get params :hllstart)
4733 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4734 (*orgtbl-llend* (or (plist-get params :hllend)
4735 (plist-get params :hlend) *orgtbl-llend*))
4736 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4737 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4738 (plist-get params :hlfmt) *orgtbl-llfmt*))
4739 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4740 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4741 (orgtbl-format-section 'hline))
4742 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4743 (pop *orgtbl-table*)))
4744 ;; Now format the main section.
4745 (orgtbl-format-section nil)
4747 (when (plist-member params :tend)
4748 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4749 (if tend (push tend *orgtbl-rtn*)))))
4750 (mapconcat (if remove-newlines
4752 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4754 (nreverse (if remove-nil-linesp
4755 (remq nil *orgtbl-rtn*)
4756 *orgtbl-rtn*)) "\n")))
4759 (defun orgtbl-to-tsv (table params)
4760 "Convert the orgtbl-mode table to TAB separated material."
4761 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4763 (defun orgtbl-to-csv (table params)
4764 "Convert the orgtbl-mode table to CSV material.
4765 This does take care of the proper quoting of fields with comma or quotes."
4766 (orgtbl-to-generic table (org-combine-plists
4767 '(:sep "," :fmt org-quote-csv-field)
4771 (defun orgtbl-to-latex (table params)
4772 "Convert the orgtbl-mode TABLE to LaTeX.
4773 TABLE is a list, each entry either the symbol `hline' for a horizontal
4774 separator line, or a list of fields for that line.
4775 PARAMS is a property list of parameters that can influence the conversion.
4776 Supports all parameters from `orgtbl-to-generic'. Most important for
4779 :splice When set to t, return only table body lines, don't wrap
4780 them into a tabular environment. Default is nil.
4782 :fmt A format to be used to wrap the field, should contain %s for the
4783 original field value. For example, to wrap everything in dollars,
4784 use :fmt \"$%s$\". This may also be a property list with column
4785 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4786 The format may also be a function that formats its one argument.
4788 :efmt Format for transforming numbers with exponentials. The format
4789 should have %s twice for inserting mantissa and exponent, for
4790 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4791 This may also be a property list with column numbers and formats.
4792 The format may also be a function that formats its two arguments.
4794 :llend If you find too much space below the last line of a table,
4795 pass a value of \"\" for :llend to suppress the final \\\\.
4797 The general parameters :skip and :skipcols have already been applied when
4798 this function is called."
4799 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4800 org-table-last-alignment ""))
4803 :tstart (concat "\\begin{tabular}{" alignment "}")
4804 :tend "\\end{tabular}"
4805 :lstart "" :lend " \\\\" :sep " & "
4806 :efmt "%s\\,(%s)" :hline "\\hline")))
4808 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4811 (defun orgtbl-to-html (table params)
4812 "Convert the orgtbl-mode TABLE to HTML.
4813 TABLE is a list, each entry either the symbol `hline' for a horizontal
4814 separator line, or a list of fields for that line.
4815 PARAMS is a property list of parameters that can influence the conversion.
4816 Currently this function recognizes the following parameters:
4818 :splice When set to t, return only table body lines, don't wrap
4819 them into a <table> environment. Default is nil.
4821 The general parameters :skip and :skipcols have already been applied when
4822 this function is called. The function does *not* use `orgtbl-to-generic',
4823 so you cannot specify parameters for it."
4825 (let ((output (org-export-string-as
4826 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4827 (if (not (plist-get params :splice)) output
4829 (replace-regexp-in-string
4830 "\\`<table .*>\n" ""
4831 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4834 (defun orgtbl-to-texinfo (table params)
4835 "Convert the orgtbl-mode TABLE to TeXInfo.
4836 TABLE is a list, each entry either the symbol `hline' for a horizontal
4837 separator line, or a list of fields for that line.
4838 PARAMS is a property list of parameters that can influence the conversion.
4839 Supports all parameters from `orgtbl-to-generic'. Most important for
4842 :splice nil/t When set to t, return only table body lines, don't wrap
4843 them into a multitable environment. Default is nil.
4845 :fmt fmt A format to be used to wrap the field, should contain
4846 %s for the original field value. For example, to wrap
4847 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4848 This may also be a property list with column numbers and
4849 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4850 Each format also may be a function that formats its one
4853 :cf \"f1 f2..\" The column fractions for the table. By default these
4854 are computed automatically from the width of the columns
4857 The general parameters :skip and :skipcols have already been applied when
4858 this function is called."
4859 (let* ((total (float (apply '+ org-table-last-column-widths)))
4860 (colfrac (or (plist-get params :cf)
4862 (lambda (x) (format "%.3f" (/ (float x) total)))
4863 org-table-last-column-widths " ")))
4866 :tstart (concat "@multitable @columnfractions " colfrac)
4867 :tend "@end multitable"
4868 :lstart "@item " :lend "" :sep " @tab "
4869 :hlstart "@headitem ")))
4870 (require 'ox-texinfo)
4871 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4874 (defun orgtbl-to-orgtbl (table params)
4875 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4876 Useful when slicing one table into many. The :hline, :sep,
4877 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4878 and :tend suppress strings without splicing; they can be set to
4879 provide ORGTBL directives for the generated table."
4883 :tstart nil :tend nil
4888 (params (org-combine-plists params2 params)))
4890 (insert (orgtbl-to-generic table params))
4891 (goto-char (point-min))
4892 (while (re-search-forward org-table-hline-regexp nil t)
4894 (buffer-substring 1 (buffer-size)))))
4896 (defun orgtbl-to-table.el (table params)
4897 "Convert the orgtbl-mode TABLE into a table.el table."
4899 (insert (orgtbl-to-orgtbl table params))
4901 (replace-regexp-in-string
4903 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4905 (defun orgtbl-to-unicode (table params)
4906 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4907 You need the ascii-art-to-unicode.el package for this. You can download
4908 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4910 (insert (orgtbl-to-table.el table params))
4911 (goto-char (point-min))
4912 (if (or (featurep 'ascii-art-to-unicode)
4913 (require 'ascii-art-to-unicode nil t))
4915 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4916 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4917 "Link to ascii-art-to-unicode.el") org-stored-links))
4918 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4921 (defun org-table-get-remote-range (name-or-id form)
4922 "Get a field value or a list of values in a range from table at ID.
4924 NAME-OR-ID may be the name of a table in the current file as set by
4925 a \"#+TBLNAME:\" directive. The first table following this line
4926 will then be used. Alternatively, it may be an ID referring to
4927 any entry, also in a different file. In this case, the first table
4928 in that entry will be referenced.
4929 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4930 \"@I$2..@II$2\". All the references must be absolute, not relative.
4932 The return value is either a single string for a single field, or a
4933 list of the fields in the rectangle ."
4935 (let ((case-fold-search t) (id-loc nil)
4936 ;; Protect a bunch of variables from being overwritten
4937 ;; by the context of the remote table
4938 org-table-column-names org-table-column-name-regexp
4939 org-table-local-parameters org-table-named-field-locations
4940 org-table-current-line-types org-table-current-begin-line
4941 org-table-current-begin-pos org-table-dlines
4942 org-table-current-ncol
4943 org-table-hlines org-table-last-alignment
4944 org-table-last-column-widths org-table-last-alignment
4945 org-table-last-column-widths tbeg
4947 (setq form (org-table-convert-refs-to-rc form))
4952 (goto-char (point-min))
4953 (if (re-search-forward
4954 (concat "^[ \t]*#\\+tblname:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4956 (setq buffer (current-buffer) loc (match-beginning 0))
4957 (setq id-loc (org-id-find name-or-id 'marker))
4958 (unless (and id-loc (markerp id-loc))
4959 (user-error "Can't find remote table \"%s\"" name-or-id))
4960 (setq buffer (marker-buffer id-loc)
4961 loc (marker-position id-loc))
4962 (move-marker id-loc nil)))
4963 (with-current-buffer buffer
4969 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4970 (not (match-beginning 1)))
4971 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
4972 (setq tbeg (point-at-bol))
4973 (org-table-get-specials)
4974 (setq form (org-table-formula-substitute-names
4975 (org-table-formula-handle-first/last-rc form)))
4976 (if (and (string-match org-table-range-regexp form)
4977 (> (length (match-string 0 form)) 1))
4979 (org-table-get-range (match-string 0 form) tbeg 1))
4982 (defmacro org-define-lookup-function (mode)
4983 (let ((mode-str (symbol-name mode))
4984 (first-p (equal mode 'first))
4985 (all-p (equal mode 'all)))
4986 (let ((plural-str (if all-p "s" "")))
4987 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4988 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4989 If R-LIST is nil, return matching element%s of S-LIST.
4990 If PREDICATE is not nil, use it instead of `equal' to match VAL.
4991 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
4992 This function is generated by a call to the macro `org-define-lookup-function'."
4993 mode-str plural-str plural-str plural-str)
4994 (let ,(let ((lvars '((p (or predicate 'equal))
4996 (rl (or r-list s-list))
4998 (if first-p (add-to-list 'lvars '(match-p nil)))
5000 (while ,(if first-p '(and (not match-p) sl) 'sl)
5002 (if (funcall p val (car sl))
5004 ,(if first-p '(setq match-p t))
5005 (let ((rval (car rl)))
5006 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5007 (setq sl (cdr sl) rl (cdr rl))))
5010 (org-define-lookup-function first)
5011 (org-define-lookup-function last)
5012 (org-define-lookup-function all)
5014 (provide 'org-table)
5017 ;; generated-autoload-file: "org-loaddefs.el"
5020 ;;; org-table.el ends here