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 (defvar org-table-TBLFM-begin-regexp
"|\n[ \t]*#\\+TBLFM: ")
57 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
58 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
59 In the optimized version, the table editor takes over all simple keys that
60 normally just insert a character. In tables, the characters are inserted
61 in a way to minimize disturbing the table structure (i.e. in overwrite mode
62 for empty fields). Outside tables, the correct binding of the keys is
65 The default for this option is t if the optimized version is also used in
66 Org-mode. See the variable `org-enable-table-editor' for details. Changing
67 this variable requires a restart of Emacs to become effective."
71 (defcustom orgtbl-radio-table-templates
72 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
73 % END RECEIVE ORGTBL %n
75 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
78 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
79 @c END RECEIVE ORGTBL %n
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
84 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
85 <!-- END RECEIVE ORGTBL %n -->
87 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
90 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
91 #+ END RECEIVE ORGTBL %n
93 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
96 "Templates for radio tables in different major modes.
97 Each template must define lines that will be treated as a comment and that
98 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
99 lines where \"%n\" will be replaced with the name of the table during
100 insertion of the template. The transformed table will later be inserted
103 The template should also contain a minimal table in a multiline comment.
104 If multiline comments are not possible in the buffer language,
105 you can pack it into a string that will not be used when the code
106 is compiled or executed. Above the table will you need a line with
107 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
108 convert the table into a data structure useful in the
109 language of the buffer. Check the manual for the section on
110 \"Translator functions\", and more generally check out
111 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
113 All occurrences of %n in a template will be replaced with the name of the
114 table, obtained by prompting the user."
117 (list (symbol :tag
"Major mode")
118 (string :tag
"Format"))))
120 (defgroup org-table-settings nil
121 "Settings for tables in Org-mode."
122 :tag
"Org Table Settings"
125 (defcustom org-table-default-size
"5x2"
126 "The default size for newly created tables, Columns x Rows."
127 :group
'org-table-settings
130 (defcustom org-table-number-regexp
131 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
132 "Regular expression for recognizing numbers in table columns.
133 If a table column contains mostly numbers, it will be aligned to the
134 right. If not, it will be aligned to the left.
136 The default value of this option is a regular expression which allows
137 anything which looks remotely like a number as used in scientific
138 context. For example, all of the following will be considered a
140 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
142 Other options offered by the customize interface are more restrictive."
143 :group
'org-table-settings
145 (const :tag
"Positive Integers"
147 (const :tag
"Integers"
149 (const :tag
"Floating Point Numbers"
150 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
151 (const :tag
"Floating Point Number or Integer"
152 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
153 (const :tag
"Exponential, Floating point, Integer"
154 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
155 (const :tag
"Very General Number-Like, including hex and Calc radix"
156 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
157 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
158 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
159 (string :tag
"Regexp:")))
161 (defcustom org-table-number-fraction
0.5
162 "Fraction of numbers in a column required to make the column align right.
163 In a column all non-white fields are considered. If at least
164 this fraction of fields is matched by `org-table-number-regexp',
165 alignment to the right border applies."
166 :group
'org-table-settings
169 (defgroup org-table-editing nil
170 "Behavior of tables during editing in Org-mode."
171 :tag
"Org Table Editing"
174 (defcustom org-table-automatic-realign t
175 "Non-nil means automatically re-align table when pressing TAB or RETURN.
176 When nil, aligning is only done with \\[org-table-align], or after column
178 :group
'org-table-editing
181 (defcustom org-table-auto-blank-field t
182 "Non-nil means automatically blank table field when starting to type into it.
183 This only happens when typing immediately after a field motion
184 command (TAB, S-TAB or RET).
185 Only relevant when `org-enable-table-editor' is equal to `optimized'."
186 :group
'org-table-editing
189 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
190 "Non-nil means automatically exit the follow mode.
191 When nil, the follow mode will stay on and be active in any table
192 the cursor enters. Since the table follow filed mode messes with the
193 window configuration, it is not recommended to set this variable to nil,
194 except maybe locally in a special file that has mostly tables with long
200 (defcustom org-table-fix-formulas-confirm nil
201 "Whether the user should confirm when Org fixes formulas."
202 :group
'org-table-editing
205 (const :tag
"with yes-or-no" yes-or-no-p
)
206 (const :tag
"with y-or-n" y-or-n-p
)
207 (const :tag
"no confirmation" nil
)))
208 (put 'org-table-fix-formulas-confirm
210 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
212 (defcustom org-table-tab-jumps-over-hlines t
213 "Non-nil means tab in the last column of a table with jump over a hline.
214 If a horizontal separator line is following the current line,
215 `org-table-next-field' can either create a new row before that line, or jump
216 over the line. When this option is nil, a new line will be created before
218 :group
'org-table-editing
221 (defgroup org-table-calculation nil
222 "Options concerning tables in Org-mode."
223 :tag
"Org Table Calculation"
226 (defcustom org-table-use-standard-references
'from
227 "Should org-mode work with table references like B3 instead of @3$2?
230 from accept as input, do not present for editing
231 t accept as input and present for editing"
232 :group
'org-table-calculation
234 (const :tag
"Never, don't even check user input for them" nil
)
235 (const :tag
"Always, both as user input, and when editing" t
)
236 (const :tag
"Convert user input, don't offer during editing" from
)))
238 (defcustom org-table-copy-increment t
239 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
240 :group
'org-table-calculation
243 (defcustom org-calc-default-modes
244 '(calc-internal-prec 12
245 calc-float-format
(float 8)
248 calc-symbolic-mode nil
249 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
250 calc-display-working-message t
252 "List with Calc mode settings for use in `calc-eval' for table formulas.
253 The list must contain alternating symbols (Calc modes variables and values).
254 Don't remove any of the default settings, just change the values. Org-mode
255 relies on the variables to be present in the list."
256 :group
'org-table-calculation
259 (defcustom org-table-duration-custom-format
'hours
260 "Format for the output of calc computations like $1+$2;t.
261 The default value is 'hours, and will output the results as a
262 number of hours. Other allowed values are 'seconds, 'minutes and
263 'days, and the output will be a fraction of seconds, minutes or
265 :group
'org-table-calculation
267 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
268 (symbol :tag
"Minutes" 'minutes
)
269 (symbol :tag
"Hours " 'hours
)
270 (symbol :tag
"Days " 'days
)))
272 (defcustom org-table-formula-field-format
"%s"
273 "Format for fields which contain the result of a formula.
274 For example, using \"~%s~\" will display the result within tilde
275 characters. Beware that modifying the display can prevent the
276 field from being used in another formula."
277 :group
'org-table-settings
281 (defcustom org-table-formula-evaluate-inline t
282 "Non-nil means TAB and RET evaluate a formula in current table field.
283 If the current field starts with an equal sign, it is assumed to be a formula
284 which should be evaluated as described in the manual and in the documentation
285 string of the command `org-table-eval-formula'. This feature requires the
287 When this variable is nil, formula calculation is only available through
288 the command \\[org-table-eval-formula]."
289 :group
'org-table-calculation
292 (defcustom org-table-formula-use-constants t
293 "Non-nil means interpret constants in formulas in tables.
294 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
295 by the value given in `org-table-formula-constants', or by a value obtained
296 from the `constants.el' package."
297 :group
'org-table-calculation
300 (defcustom org-table-formula-constants nil
301 "Alist with constant names and values, for use in table formulas.
302 The car of each element is a name of a constant, without the `$' before it.
303 The cdr is the value as a string. For example, if you'd like to use the
304 speed of light in a formula, you would configure
306 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
308 and then use it in an equation like `$1*$c'.
310 Constants can also be defined on a per-file basis using a line like
312 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
313 :group
'org-table-calculation
315 (cons (string :tag
"name")
316 (string :tag
"value"))))
318 (defcustom org-table-allow-automatic-line-recalculation t
319 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
320 Automatically means when TAB or RET or C-c C-c are pressed in the line."
321 :group
'org-table-calculation
324 (defcustom org-table-error-on-row-ref-crossing-hline t
325 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
329 (defcustom org-table-relative-ref-may-cross-hline t
330 "Non-nil means relative formula references may cross hlines.
331 Here are the allowed values:
333 nil Relative references may not cross hlines. They will reference the
334 field next to the hline instead. Coming from below, the reference
335 will be to the field below the hline. Coming from above, it will be
337 t Relative references may cross hlines.
338 error An attempt to cross a hline will throw an error.
340 It is probably good to never set this variable to nil, for the sake of
341 portability of tables."
342 :group
'org-table-calculation
344 (const :tag
"Allow to cross" t
)
345 (const :tag
"Stick to hline" nil
)
346 (const :tag
"Error on attempt to cross" error
)))
348 (defgroup org-table-import-export nil
349 "Options concerning table import and export in Org-mode."
350 :tag
"Org Table Import Export"
353 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
354 "Default export parameters for `org-table-export'.
355 These can be overridden for a specific table by setting the
356 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
357 radio tables for the different export transformations and
358 available parameters."
359 :group
'org-table-import-export
362 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
363 "Detects a table line marked for automatic recalculation.")
364 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
365 "Detects a table line marked for automatic recalculation.")
366 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
367 "Detects a table line marked for automatic recalculation.")
368 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
369 "Searching from within a table (any type) this finds the first line outside the table.")
370 (defvar org-table-last-highlighted-reference nil
)
371 (defvar org-table-formula-history nil
)
373 (defvar org-table-column-names nil
374 "Alist with column names, derived from the `!' line.")
375 (defvar org-table-column-name-regexp nil
376 "Regular expression matching the current column names.")
377 (defvar org-table-local-parameters nil
378 "Alist with parameter names, derived from the `$' line.")
379 (defvar org-table-named-field-locations nil
380 "Alist with locations of named fields.")
382 (defvar org-table-current-line-types nil
383 "Table row types, non-nil only for the duration of a command.")
384 (defvar org-table-current-begin-line nil
385 "Table begin line, non-nil only for the duration of a command.")
386 (defvar org-table-current-begin-pos nil
387 "Table begin position, non-nil only for the duration of a command.")
388 (defvar org-table-current-ncol nil
389 "Number of columns in table, non-nil only for the duration of a command.")
390 (defvar org-table-dlines nil
391 "Vector of data line line numbers in the current table.")
392 (defvar org-table-hlines nil
393 "Vector of hline line numbers in the current table.")
395 (defconst org-table-range-regexp
396 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
398 "Regular expression for matching ranges in formulas.")
400 (defconst org-table-range-regexp2
402 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
404 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
405 "Match a range for reference display.")
407 (defun org-table-colgroup-line-p (line)
408 "Is this a table line colgroup information?"
410 (and (string-match "[<>]\\|&[lg]t;" line
)
411 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
417 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
418 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
420 (defun org-table-cookie-line-p (line)
421 "Is this a table line with only alignment/width cookies?"
423 (and (string-match "[<>]\\|&[lg]t;" line
)
425 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
426 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
427 (not (delq nil
(mapcar
429 (not (or (equal s
"")
431 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
433 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
435 (org-split-string (match-string 1 line
)
436 "[ \t]*|[ \t]*")))))))
438 (defvar org-table-clean-did-remove-column nil
) ; dynamically scoped
439 (defun org-table-clean-before-export (lines &optional maybe-quoted
)
440 "Check if the table has a marking column.
441 If yes remove the column and the special lines."
442 (let ((special (if maybe-quoted
443 "^[ \t]*| *\\\\?[\#!$*_^/ ] *|"
444 "^[ \t]*| *[\#!$*_^/ ] *|"))
445 (ignore (if maybe-quoted
446 "^[ \t]*| *\\\\?[!$_^/] *|"
447 "^[ \t]*| *[!$_^/] *|")))
448 (setq org-table-clean-did-remove-column
452 (or (string-match org-table-hline-regexp line
)
453 (string-match special line
)))
459 ((or (org-table-colgroup-line-p line
) ;; colgroup info
460 (org-table-cookie-line-p line
) ;; formatting cookies
461 (and org-table-clean-did-remove-column
462 (string-match ignore line
))) ;; non-exportable data
464 ((and org-table-clean-did-remove-column
465 (or (string-match "^\\([ \t]*\\)|-+\\+" line
)
466 (string-match "^\\([ \t]*\\)|[^|]*|" line
)))
467 ;; remove the first column
468 (replace-match "\\1|" t nil line
))
472 (defconst org-table-translate-regexp
473 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
474 "Match a reference that needs translation, for reference display.")
477 (defun org-table-create-with-table.el
()
478 "Use the table.el package to insert a new table.
479 If there is already a table at point, convert between Org-mode tables
480 and table.el tables."
485 (if (y-or-n-p "Convert table to Org-mode table? ")
486 (org-table-convert)))
488 (when (y-or-n-p "Convert table to table.el table? ")
490 (org-table-convert)))
491 (t (call-interactively 'table-insert
))))
494 (defun org-table-create-or-convert-from-region (arg)
495 "Convert region to table, or create an empty table.
496 If there is an active region, convert it to a table, using the function
497 `org-table-convert-region'. See the documentation of that function
498 to learn how the prefix argument is interpreted to determine the field
500 If there is no such region, create an empty table with `org-table-create'."
502 (if (org-region-active-p)
503 (org-table-convert-region (region-beginning) (region-end) arg
)
504 (org-table-create arg
)))
507 (defun org-table-create (&optional size
)
508 "Query for a size and insert a table skeleton.
509 SIZE is a string Columns x Rows like for example \"3x2\"."
512 (setq size
(read-string
513 (concat "Table size Columns x Rows [e.g. "
514 org-table-default-size
"]: ")
515 "" nil org-table-default-size
)))
518 (indent (make-string (current-column) ?\
))
519 (split (org-split-string size
" *x *"))
520 (rows (string-to-number (nth 1 split
)))
521 (columns (string-to-number (car split
)))
522 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
524 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
525 (point-at-bol) (point)))
526 (beginning-of-line 1)
528 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
529 (dotimes (i rows
) (insert line
))
532 ;; Insert a hline after the first row.
540 (defun org-table-convert-region (beg0 end0
&optional separator
)
541 "Convert region to a table.
542 The region goes from BEG0 to END0, but these borders will be moved
543 slightly, to make sure a beginning of line in the first line is included.
545 SEPARATOR specifies the field separator in the lines. It can have the
548 '(4) Use the comma as a field separator
549 '(16) Use a TAB as field separator
550 '(64) Prompt for a regular expression as field separator
551 integer When a number, use that many spaces as field separator
552 regexp When a regular expression, use it to match the separator
553 nil When nil, the command tries to be smart and figure out the
554 separator in the following way:
555 - when each line contains a TAB, assume TAB-separated material
556 - when each line contains a comma, assume CSV material
557 - else, assume one or more SPACE characters as separator."
559 (let* ((beg (min beg0 end0
))
560 (end (max beg0 end0
))
562 (if (equal separator
'(64))
563 (setq separator
(read-regexp "Regexp for field separator")))
565 (beginning-of-line 1)
566 (setq beg
(point-marker))
568 (if (bolp) (backward-char 1) (end-of-line 1))
569 (setq end
(point-marker))
570 ;; Get the right field separator
575 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
576 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
579 (if (equal separator
'(4))
580 (while (< (point) end
)
581 ;; parse the csv stuff
583 ((looking-at "^") (insert "| "))
584 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
585 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
586 (replace-match "\\1")
587 (if (looking-at "\"") (insert "\"")))
588 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
589 ((looking-at "[ \t]*,") (replace-match " | "))
590 (t (beginning-of-line 2))))
592 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
593 ((equal separator
'(16)) "^\\|\t")
594 ((integerp separator
)
596 (user-error "Number of spaces in separator must be >= 1")
597 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
599 (format "^ *\\|%s" separator
))
600 (t (error "This should not happen"))))
601 (while (re-search-forward re end t
)
602 (replace-match "| " t t
)))
607 (defun org-table-import (file arg
)
608 "Import FILE as a table.
609 The file is assumed to be tab-separated. Such files can be produced by most
610 spreadsheet and database applications. If no tabs (at least one per line)
611 are found, lines will be split on whitespace into fields."
613 (or (bolp) (newline))
616 (insert-file-contents file
)
617 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
620 (defvar org-table-last-alignment
)
621 (defvar org-table-last-column-widths
)
623 (defun org-table-export (&optional file format
)
624 "Export table to a file, with configurable format.
625 Such a file can be imported into usual spreadsheet programs.
627 FILE can be the output file name. If not given, it will be taken
628 from a TABLE_EXPORT_FILE property in the current entry or higher
629 up in the hierarchy, or the user will be prompted for a file
630 name. FORMAT can be an export format, of the same kind as it
631 used when `orgtbl-mode' sends a table in a different format.
633 The command suggests a format depending on TABLE_EXPORT_FORMAT,
634 whether it is set locally or up in the hierarchy, then on the
635 extension of the given file name, and finally on the variable
636 `org-table-export-default-format'."
638 (unless (org-at-table-p) (user-error "No table at point"))
639 (org-table-align) ;; make sure we have everything we need
640 (let* ((beg (org-table-begin))
641 (end (org-table-end))
642 (txt (buffer-substring-no-properties beg end
))
643 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
644 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
645 "orgtbl-to-latex" "orgtbl-to-html"
646 "orgtbl-to-generic" "orgtbl-to-texinfo"
649 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
650 buf deffmt-readable fileext
)
652 (setq file
(read-file-name "Export table to: "))
653 (unless (or (not (file-exists-p file
))
654 (y-or-n-p (format "Overwrite file %s? " file
)))
655 (user-error "File not written")))
656 (if (file-directory-p file
)
657 (user-error "This is a directory path, not a file"))
658 (if (and (buffer-file-name)
659 (equal (file-truename file
)
660 (file-truename (buffer-file-name))))
661 (user-error "Please specify a file name that is different from current"))
662 (setq fileext
(concat (file-name-extension file
) "$"))
664 (setq deffmt-readable
665 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
666 org-table-export-default-format
))
667 (while (string-match "\t" deffmt-readable
)
668 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
669 (while (string-match "\n" deffmt-readable
)
670 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
671 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
672 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
673 (let* ((transform (intern (match-string 1 format
)))
674 (params (if (match-end 2)
675 (read (concat "(" (match-string 2 format
) ")"))))
676 (skip (plist-get params
:skip
))
677 (skipcols (plist-get params
:skipcols
))
678 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
679 (lines (org-table-clean-before-export lines
))
680 (i0 (if org-table-clean-did-remove-column
2 1))
683 (if (string-match org-table-hline-regexp x
)
686 (org-split-string (org-trim x
) "\\s-*|\\s-*")
689 (fun (if (= i0
2) 'cdr
'identity
))
690 (org-table-last-alignment
691 (org-remove-by-index (funcall fun org-table-last-alignment
)
693 (org-table-last-column-widths
694 (org-remove-by-index (funcall fun org-table-last-column-widths
)
697 (unless (fboundp transform
)
698 (user-error "No such transformation function %s" transform
))
699 (setq txt
(funcall transform table params
))
701 (with-current-buffer (find-file-noselect file
)
702 (setq buf
(current-buffer))
708 (message "Export done."))
709 (user-error "TABLE_EXPORT_FORMAT invalid"))))
711 (defvar org-table-aligned-begin-marker
(make-marker)
712 "Marker at the beginning of the table last aligned.
713 Used to check if cursor still is in that table, to minimize realignment.")
714 (defvar org-table-aligned-end-marker
(make-marker)
715 "Marker at the end of the table last aligned.
716 Used to check if cursor still is in that table, to minimize realignment.")
717 (defvar org-table-last-alignment nil
718 "List of flags for flushright alignment, from the last re-alignment.
719 This is being used to correctly align a single field after TAB or RET.")
720 (defvar org-table-last-column-widths nil
721 "List of max width of fields in each column.
722 This is being used to correctly align a single field after TAB or RET.")
723 (defvar org-table-formula-debug nil
724 "Non-nil means debug table formulas.
725 When nil, simply write \"#ERROR\" in corrupted fields.")
726 (make-variable-buffer-local 'org-table-formula-debug
)
727 (defvar org-table-overlay-coordinates nil
728 "Overlay coordinates after each align of a table.")
729 (make-variable-buffer-local 'org-table-overlay-coordinates
)
731 (defvar org-last-recalc-line nil
)
732 (defvar org-table-do-narrow t
) ; for dynamic scoping
733 (defconst org-narrow-column-arrow
"=>"
734 "Used as display property in narrowed table columns.")
737 (defun org-table-align ()
738 "Align the table at point by aligning all vertical bars."
742 (beg (org-table-begin))
743 (end (org-table-end))
744 ;; Current cursor position
745 (linepos (org-current-line))
746 (colpos (org-table-current-column))
747 (winstart (window-start))
748 (winstartline (org-current-line (min winstart
(1- (point-max)))))
749 lines
(new "") lengths l typenums ty fields maxfields i
757 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
759 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
760 emptystrings links dates emph raise narrow
761 falign falign1 fmax f1 len c e space
)
763 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
764 ;; Check if we have links or dates
766 (setq links
(re-search-forward org-bracket-link-regexp end t
))
768 (setq emph
(and org-hide-emphasis-markers
769 (re-search-forward org-emph-re end t
)))
771 (setq raise
(and org-use-sub-superscripts
772 (re-search-forward org-match-substring-regexp end t
)))
774 (setq dates
(and org-display-custom-times
775 (re-search-forward org-ts-regexp-both end t
)))
776 ;; Make sure the link properties are right
777 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
778 ;; Make sure the date properties are right
779 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
780 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
781 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
783 ;; Check if we are narrowing any columns
785 (setq narrow
(and org-table-do-narrow
786 org-format-transports-properties-p
787 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
789 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
792 (setq lines
(org-split-string
793 (buffer-substring beg end
) "\n"))
794 ;; Store the indentation of the first line
795 (if (string-match "^ *" (car lines
))
796 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
797 ;; Mark the hlines by setting the corresponding element to nil
798 ;; At the same time, we remove trailing space.
799 (setq lines
(mapcar (lambda (l)
800 (if (string-match "^ *|-" l
)
802 (if (string-match "[ \t]+$" l
)
803 (substring l
0 (match-beginning 0))
806 ;; Get the data fields by splitting the lines.
809 (org-split-string l
" *| *"))
810 (delq nil
(copy-sequence lines
))))
811 ;; How many fields in the longest line?
813 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
815 (kill-region beg end
)
816 (org-table-create org-table-default-size
)
817 (user-error "Empty table - created default table")))
818 ;; A list of empty strings to fill any short rows on output
819 (setq emptystrings
(make-list maxfields
""))
820 ;; Check for special formatting.
822 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
823 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
824 ;; Check if there is an explicit width specified
826 (when (or narrow falign
)
827 (setq c column fmax nil falign1 nil
)
830 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
831 (if (match-end 1) (setq falign1
(match-string 1 e
)))
832 (if (and org-table-do-narrow
(match-end 2))
833 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
834 ;; Find fields that are wider than fmax, and shorten them
836 (loop for xx in column do
837 (when (and (stringp xx
)
838 (> (org-string-width xx
) fmax
))
839 (org-add-props xx nil
841 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
842 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
844 (user-error "Cannot narrow field starting with wide link \"%s\""
845 (match-string 0 xx
)))
846 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
847 (add-text-properties (- f1
2) f1
848 (list 'display org-narrow-column-arrow
)
850 ;; Get the maximum width for each column
851 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
853 ;; Get the fraction of numbers, to decide about alignment of the column
855 (push (equal (downcase falign1
) "r") typenums
)
856 (setq cnt
0 frac
0.0)
857 (loop for x in column do
860 (setq frac
( / (+ (* frac cnt
)
861 (if (string-match org-table-number-regexp x
) 1 0))
862 (setq cnt
(1+ cnt
))))))
863 (push (>= frac org-table-number-fraction
) typenums
)))
864 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
866 ;; Store the alignment of this table, for later editing of single fields
867 (setq org-table-last-alignment typenums
868 org-table-last-column-widths lengths
)
870 ;; With invisible characters, `format' does not get the field width right
871 ;; So we need to make these fields wide by hand.
872 (when (or links emph raise
)
873 (loop for i from
0 upto
(1- maxfields
) do
874 (setq len
(nth i lengths
))
875 (loop for j from
0 upto
(1- (length fields
)) do
876 (setq c
(nthcdr i
(car (nthcdr j fields
))))
877 (if (and (stringp (car c
))
878 (or (text-property-any 0 (length (car c
))
879 'invisible
'org-link
(car c
))
880 (text-property-any 0 (length (car c
))
881 'org-dwidth t
(car c
)))
882 (< (org-string-width (car c
)) len
))
884 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
885 (setcar c
(if (nth i typenums
)
886 (concat space
(car c
))
887 (concat (car c
) space
))))))))
889 ;; Compute the formats needed for output of the table
890 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
891 (while (setq l
(pop lengths
))
892 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
893 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
894 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
895 (setq rfmt
(concat rfmt
"\n")
896 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
900 (if l
(apply 'format rfmt
901 (append (pop fields
) emptystrings
))
904 (move-marker org-table-aligned-begin-marker
(point))
906 ;; Replace the old one
907 (delete-region (point) end
)
908 (move-marker end nil
)
909 (move-marker org-table-aligned-end-marker
(point))
910 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
911 (goto-char org-table-aligned-begin-marker
)
912 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
913 ;; Try to move to the old location
914 (org-goto-line winstartline
)
915 (setq winstart
(point-at-bol))
916 (org-goto-line linepos
)
917 (when (eq (window-buffer (selected-window)) (current-buffer))
918 (set-window-start (selected-window) winstart
'noforce
))
919 (org-table-goto-column colpos
)
920 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
921 (setq org-table-may-need-update nil
)
925 (defun org-table-begin (&optional table-type
)
926 "Find the beginning of the table and return its position.
927 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
929 (if (not (re-search-backward
930 (if table-type org-table-any-border-regexp
931 org-table-border-regexp
)
933 (progn (goto-char (point-min)) (point))
934 (goto-char (match-beginning 0))
935 (beginning-of-line 2)
939 (defun org-table-end (&optional table-type
)
940 "Find the end of the table and return its position.
941 With argument TABLE-TYPE, go to the end of a table.el-type table."
943 (if (not (re-search-forward
944 (if table-type org-table-any-border-regexp
945 org-table-border-regexp
)
947 (goto-char (point-max))
948 (goto-char (match-beginning 0)))
952 (defun org-table-justify-field-maybe (&optional new
)
953 "Justify the current field, text to left, number to right.
954 Optional argument NEW may specify text to replace the current field content."
956 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
957 ((org-at-table-hline-p))
959 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
961 (< (point) org-table-aligned-begin-marker
)
962 (>= (point) org-table-aligned-end-marker
)))
963 ;; This is not the same table, force a full re-align
964 (setq org-table-may-need-update t
))
965 (t ;; realign the current field, based on previous full realign
966 (let* ((pos (point)) s
967 (col (org-table-current-column))
968 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
971 (skip-chars-backward "^|\n")
972 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
974 (setq s
(match-string 1)
976 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
977 e
(not (= (match-beginning 2) (match-end 2))))
978 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
979 l
(if e
"|" (setq org-table-may-need-update t
) ""))
982 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
983 (setq n
(format f new
))
984 (setq n
(concat new
"|") org-table-may-need-update t
)))
985 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
987 (let (org-table-may-need-update)
988 (replace-match n t t
))))
989 (setq org-table-may-need-update t
))
993 (defun org-table-next-field ()
994 "Go to the next field in the current table, creating new lines as needed.
995 Before doing so, re-align the table if necessary."
997 (org-table-maybe-eval-formula)
998 (org-table-maybe-recalculate-line)
999 (if (and org-table-automatic-realign
1000 org-table-may-need-update
)
1002 (let ((end (org-table-end)))
1003 (if (org-at-table-hline-p)
1007 (re-search-forward "|" end
)
1008 (if (looking-at "[ \t]*$")
1009 (re-search-forward "|" end
))
1010 (if (and (looking-at "-")
1011 org-table-tab-jumps-over-hlines
1012 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1013 (goto-char (match-beginning 1)))
1014 (if (looking-at "-")
1016 (beginning-of-line 0)
1017 (org-table-insert-row 'below
))
1018 (if (looking-at " ") (forward-char 1))))
1020 (org-table-insert-row 'below
)))))
1023 (defun org-table-previous-field ()
1024 "Go to the previous field in the table.
1025 Before doing so, re-align the table if necessary."
1027 (org-table-justify-field-maybe)
1028 (org-table-maybe-recalculate-line)
1029 (if (and org-table-automatic-realign
1030 org-table-may-need-update
)
1032 (if (org-at-table-hline-p)
1036 (re-search-backward "|" (org-table-begin))
1037 (re-search-backward "|" (org-table-begin)))
1038 (error (user-error "Cannot move to previous table field")))
1039 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1040 (re-search-backward "|" (org-table-begin)))
1041 (if (looking-at "| ?")
1042 (goto-char (match-end 0))))
1044 (defun org-table-beginning-of-field (&optional n
)
1045 "Move to the end of the current table field.
1046 If already at or after the end, move to the end of the next table field.
1047 With numeric argument N, move N-1 fields forward first."
1049 (let ((pos (point)))
1052 (org-table-previous-field))
1053 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1054 (user-error "No more table fields before the current")
1055 (goto-char (match-end 0))
1056 (and (looking-at " ") (forward-char 1)))
1057 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1059 (defun org-table-end-of-field (&optional n
)
1060 "Move to the beginning of the current table field.
1061 If already at or before the beginning, move to the beginning of the
1063 With numeric argument N, move N-1 fields backward first."
1065 (let ((pos (point)))
1068 (org-table-next-field))
1069 (when (re-search-forward "|" (point-at-eol 1) t
)
1071 (skip-chars-backward " ")
1072 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1074 (if (<= (point) pos
) (org-table-end-of-field 2))))
1077 (defun org-table-next-row ()
1078 "Go to the next row (same column) in the current table.
1079 Before doing so, re-align the table if necessary."
1081 (org-table-maybe-eval-formula)
1082 (org-table-maybe-recalculate-line)
1083 (if (or (looking-at "[ \t]*$")
1084 (save-excursion (skip-chars-backward " \t") (bolp)))
1086 (if (and org-table-automatic-realign
1087 org-table-may-need-update
)
1089 (let ((col (org-table-current-column)))
1090 (beginning-of-line 2)
1091 (if (or (not (org-at-table-p))
1092 (org-at-table-hline-p))
1094 (beginning-of-line 0)
1095 (org-table-insert-row 'below
)))
1096 (org-table-goto-column col
)
1097 (skip-chars-backward "^|\n\r")
1098 (if (looking-at " ") (forward-char 1)))))
1101 (defun org-table-copy-down (n)
1102 "Copy a field down in the current column.
1103 If the field at the cursor is empty, copy into it the content of
1104 the nearest non-empty field above. With argument N, use the Nth
1105 non-empty field. If the current field is not empty, it is copied
1106 down to the next row, and the cursor is moved with it.
1107 Therefore, repeating this command causes the column to be filled
1109 If the variable `org-table-copy-increment' is non-nil and the
1110 field is an integer or a timestamp, it will be incremented while
1111 copying. In the case of a timestamp, increment by one day."
1113 (let* ((colpos (org-table-current-column))
1114 (col (current-column))
1115 (field (save-excursion (org-table-get-field)))
1116 (non-empty (string-match "[^ \t]" field
))
1117 (beg (org-table-begin))
1120 (org-table-check-inside-data-field)
1123 (setq txt
(org-trim field
))
1124 (org-table-next-row)
1125 (org-table-blank-field))
1129 (while (progn (beginning-of-line 1)
1130 (re-search-backward org-table-dataline-regexp
1132 (org-table-goto-column colpos t
)
1133 (if (and (looking-at
1134 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1135 (<= (setq n
(1- n
)) 0))
1136 (throw 'exit
(match-string 1))))))))
1139 (if (and org-table-copy-increment
1140 (not (equal orig-n
0))
1141 (string-match "^[0-9]+$" txt
)
1142 (< (string-to-number txt
) 100000000))
1143 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1145 (org-move-to-column col
)
1146 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1147 (org-timestamp-up-day)
1148 (org-table-maybe-recalculate-line))
1150 (org-move-to-column col
))
1151 (user-error "No non-empty field found"))))
1153 (defun org-table-check-inside-data-field (&optional noerror
)
1154 "Is point inside a table data field?
1155 I.e. not on a hline or before the first or after the last column?
1156 This actually throws an error, so it aborts the current command."
1157 (if (or (not (org-at-table-p))
1158 (= (org-table-current-column) 0)
1159 (org-at-table-hline-p)
1160 (looking-at "[ \t]*$"))
1163 (user-error "Not in table data field"))
1166 (defvar org-table-clip nil
1167 "Clipboard for table regions.")
1169 (defun org-table-get (line column
)
1170 "Get the field in table line LINE, column COLUMN.
1171 If LINE is larger than the number of data lines in the table, the function
1172 returns nil. However, if COLUMN is too large, we will simply return an
1174 If LINE is nil, use the current line.
1175 If column is nil, use the current column."
1176 (setq column
(or column
(org-table-current-column)))
1178 (and (or (not line
) (org-table-goto-line line
))
1179 (org-trim (org-table-get-field column
)))))
1181 (defun org-table-put (line column value
&optional align
)
1182 "Put VALUE into line LINE, column COLUMN.
1183 When ALIGN is set, also realign the table."
1184 (setq column
(or column
(org-table-current-column)))
1185 (prog1 (save-excursion
1186 (and (or (not line
) (org-table-goto-line line
))
1187 (progn (org-table-goto-column column nil
'force
) t
)
1188 (org-table-get-field column value
)))
1189 (and align
(org-table-align))))
1191 (defun org-table-current-line ()
1192 "Return the index of the current data line."
1193 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1195 (goto-char (org-table-begin))
1196 (while (and (re-search-forward org-table-dataline-regexp end t
)
1198 (< (point-at-eol) pos
))))
1201 (defun org-table-goto-line (N)
1202 "Go to the Nth data line in the current table.
1203 Return t when the line exists, nil if it does not exist."
1204 (goto-char (org-table-begin))
1205 (let ((end (org-table-end)) (cnt 0))
1206 (while (and (re-search-forward org-table-dataline-regexp end t
)
1207 (< (setq cnt
(1+ cnt
)) N
)))
1211 (defun org-table-blank-field ()
1212 "Blank the current table field or active region."
1214 (org-table-check-inside-data-field)
1215 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1216 (let (org-table-clip)
1217 (org-table-cut-region (region-beginning) (region-end)))
1218 (skip-chars-backward "^|")
1220 (if (looking-at "|[^|\n]+")
1221 (let* ((pos (match-beginning 0))
1222 (match (match-string 0))
1223 (len (org-string-width match
)))
1224 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1225 (goto-char (+ 2 pos
))
1226 (substring match
1)))))
1228 (defun org-table-get-field (&optional n replace
)
1229 "Return the value of the field in column N of current row.
1230 N defaults to current field.
1231 If REPLACE is a string, replace field with this value. The return value
1232 is always the old value."
1233 (and n
(org-table-goto-column n
))
1234 (skip-chars-backward "^|\n")
1236 (if (looking-at "|[^|\r\n]*")
1237 (let* ((pos (match-beginning 0))
1238 (val (buffer-substring (1+ pos
) (match-end 0))))
1240 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1242 (goto-char (min (point-at-eol) (+ 2 pos
)))
1244 (forward-char 1) ""))
1247 (defun org-table-field-info (arg)
1248 "Show info about the current field, and highlight any reference at point."
1250 (org-table-get-specials)
1252 (let* ((pos (point))
1253 (col (org-table-current-column))
1254 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1255 (name (car (rassoc (list (org-current-line) col
)
1256 org-table-named-field-locations
)))
1257 (eql (org-table-expand-lhs-ranges
1260 (cons (org-table-formula-handle-first/last-rc
1262 (org-table-get-stored-formulas))))
1263 (dline (org-table-current-dline))
1264 (ref (format "@%d$%d" dline col
))
1265 (ref1 (org-table-convert-refs-to-an ref
))
1266 (fequation (or (assoc name eql
) (assoc ref eql
)))
1267 (cequation (assoc (int-to-string col
) eql
))
1268 (eqn (or fequation cequation
)))
1269 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1270 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1273 (org-table-show-reference 'local
)
1275 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1277 (if cname
(concat " or $" cname
) "")
1279 (if name
(concat " or $" name
) "")
1280 ;; FIXME: formula info not correct if special table line
1282 (concat ", formula: "
1283 (org-table-formula-to-user
1285 (if (string-match "^[$@]"(car eqn
)) "" "$")
1286 (car eqn
) "=" (cdr eqn
))))
1289 (defun org-table-current-column ()
1290 "Find out which column we are in."
1292 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1294 (let ((cnt 0) (pos (point)))
1295 (beginning-of-line 1)
1296 (while (search-forward "|" pos t
)
1297 (setq cnt
(1+ cnt
)))
1298 (when (org-called-interactively-p 'interactive
)
1299 (message "In table column %d" cnt
))
1303 (defun org-table-current-dline ()
1304 "Find out what table data line we are in.
1305 Only data lines count for this."
1307 (when (org-called-interactively-p 'any
)
1308 (org-table-check-inside-data-field))
1310 (let ((cnt 0) (pos (point)))
1311 (goto-char (org-table-begin))
1312 (while (<= (point) pos
)
1313 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1314 (beginning-of-line 2))
1315 (when (org-called-interactively-p 'any
)
1316 (message "This is table line %d" cnt
))
1320 (defun org-table-goto-column (n &optional on-delim force
)
1321 "Move the cursor to the Nth column in the current table line.
1322 With optional argument ON-DELIM, stop with point before the left delimiter
1324 If there are less than N fields, just go to after the last delimiter.
1325 However, when FORCE is non-nil, create new columns if necessary."
1327 (beginning-of-line 1)
1329 (while (and (> (setq n
(1- n
)) -
1)
1330 (or (search-forward "|" (point-at-eol) t
)
1332 (progn (end-of-line 1)
1333 (skip-chars-backward "^|")
1336 (when (and force
(not (looking-at ".*|")))
1337 (save-excursion (end-of-line 1) (insert " | ")))
1340 (if (looking-at " ") (forward-char 1)))))
1343 (defun org-table-insert-column ()
1344 "Insert a new column into the table."
1346 (if (not (org-at-table-p))
1347 (user-error "Not at a table"))
1348 (org-table-find-dataline)
1349 (let* ((col (max 1 (org-table-current-column)))
1350 (beg (org-table-begin))
1351 (end (org-table-end))
1352 ;; Current cursor position
1353 (linepos (org-current-line))
1356 (while (< (point) end
)
1357 (if (org-at-table-hline-p)
1359 (org-table-goto-column col t
)
1361 (beginning-of-line 2))
1362 (move-marker end nil
)
1363 (org-goto-line linepos
)
1364 (org-table-goto-column colpos
)
1366 (when (or (not org-table-fix-formulas-confirm
)
1367 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1368 (org-table-fix-formulas "$" nil
(1- col
) 1)
1369 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1371 (defun org-table-find-dataline ()
1372 "Find a data line in the current table, which is needed for column commands."
1373 (if (and (org-at-table-p)
1374 (not (org-at-table-hline-p)))
1376 (let ((col (current-column))
1377 (end (org-table-end)))
1378 (org-move-to-column col
)
1379 (while (and (< (point) end
)
1380 (or (not (= (current-column) col
))
1381 (org-at-table-hline-p)))
1382 (beginning-of-line 2)
1383 (org-move-to-column col
))
1384 (if (and (org-at-table-p)
1385 (not (org-at-table-hline-p)))
1388 "Please position cursor in a data line for column operations")))))
1390 (defun org-table-line-to-dline (line &optional above
)
1391 "Turn a buffer line number into a data line number.
1392 If there is no data line in this line, return nil.
1393 If there is no matching dline (most likely te reference was a hline), the
1394 first dline below it is used. When ABOVE is non-nil, the one above is used."
1396 (let ((ll (length org-table-dlines
))
1402 (if (<= (aref org-table-dlines i
) line
)
1407 (if (>= (aref org-table-dlines i
) line
)
1413 (defun org-table-delete-column ()
1414 "Delete a column from the table."
1416 (if (not (org-at-table-p))
1417 (user-error "Not at a table"))
1418 (org-table-find-dataline)
1419 (org-table-check-inside-data-field)
1420 (let* ((col (org-table-current-column))
1421 (beg (org-table-begin))
1422 (end (org-table-end))
1423 ;; Current cursor position
1424 (linepos (org-current-line))
1427 (while (< (point) end
)
1428 (if (org-at-table-hline-p)
1430 (org-table-goto-column col t
)
1431 (and (looking-at "|[^|\n]+|")
1432 (replace-match "|")))
1433 (beginning-of-line 2))
1434 (move-marker end nil
)
1435 (org-goto-line linepos
)
1436 (org-table-goto-column colpos
)
1438 (when (or (not org-table-fix-formulas-confirm
)
1439 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1440 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1442 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1446 (defun org-table-move-column-right ()
1447 "Move column to the right."
1449 (org-table-move-column nil
))
1451 (defun org-table-move-column-left ()
1452 "Move column to the left."
1454 (org-table-move-column 'left
))
1457 (defun org-table-move-column (&optional left
)
1458 "Move the current column to the right. With arg LEFT, move to the left."
1460 (if (not (org-at-table-p))
1461 (user-error "Not at a table"))
1462 (org-table-find-dataline)
1463 (org-table-check-inside-data-field)
1464 (let* ((col (org-table-current-column))
1465 (col1 (if left
(1- col
) col
))
1466 (beg (org-table-begin))
1467 (end (org-table-end))
1468 ;; Current cursor position
1469 (linepos (org-current-line))
1470 (colpos (if left
(1- col
) (1+ col
))))
1471 (if (and left
(= col
1))
1472 (user-error "Cannot move column further left"))
1473 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1474 (user-error "Cannot move column further right"))
1476 (while (< (point) end
)
1477 (if (org-at-table-hline-p)
1479 (org-table-goto-column col1 t
)
1480 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1481 (replace-match "|\\2|\\1|")))
1482 (beginning-of-line 2))
1483 (move-marker end nil
)
1484 (org-goto-line linepos
)
1485 (org-table-goto-column colpos
)
1487 (when (or (not org-table-fix-formulas-confirm
)
1488 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1489 (org-table-fix-formulas
1490 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1491 (cons (number-to-string colpos
) (number-to-string col
))))
1492 (org-table-fix-formulas
1493 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1494 (cons (number-to-string colpos
) (number-to-string col
)))))))
1497 (defun org-table-move-row-down ()
1498 "Move table row down."
1500 (org-table-move-row nil
))
1502 (defun org-table-move-row-up ()
1503 "Move table row up."
1505 (org-table-move-row 'up
))
1508 (defun org-table-move-row (&optional up
)
1509 "Move the current table line down. With arg UP, move it up."
1511 (let* ((col (current-column))
1513 (hline1p (save-excursion (beginning-of-line 1)
1514 (looking-at org-table-hline-regexp
)))
1515 (dline1 (org-table-current-dline))
1516 (dline2 (+ dline1
(if up -
1 1)))
1519 (beginning-of-line tonew
)
1520 (unless (org-at-table-p)
1522 (user-error "Cannot move row further"))
1523 (setq hline2p
(looking-at org-table-hline-regexp
))
1525 (beginning-of-line 1)
1527 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1528 (delete-region (point) (1+ (point-at-eol)))
1529 (beginning-of-line tonew
)
1531 (beginning-of-line 0)
1532 (org-move-to-column col
)
1533 (unless (or hline1p hline2p
1534 (not (or (not org-table-fix-formulas-confirm
)
1535 (funcall org-table-fix-formulas-confirm
1536 "Fix formulas? "))))
1537 (org-table-fix-formulas
1538 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1539 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1542 (defun org-table-insert-row (&optional arg
)
1543 "Insert a new row above the current line into the table.
1544 With prefix ARG, insert below the current line."
1546 (if (not (org-at-table-p))
1547 (user-error "Not at a table"))
1548 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1549 (new (org-table-clean-line line
)))
1550 ;; Fix the first field if necessary
1551 (if (string-match "^[ \t]*| *[#$] *|" line
)
1552 (setq new
(replace-match (match-string 0 line
) t t new
)))
1553 (beginning-of-line (if arg
2 1))
1554 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1555 (beginning-of-line 0)
1556 (re-search-forward "| ?" (point-at-eol) t
)
1557 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1559 (when (or (not org-table-fix-formulas-confirm
)
1560 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1561 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1564 (defun org-table-insert-hline (&optional above
)
1565 "Insert a horizontal-line below the current line into the table.
1566 With prefix ABOVE, insert above the current line."
1568 (if (not (org-at-table-p))
1569 (user-error "Not at a table"))
1570 (when (eobp) (insert "\n") (backward-char 1))
1571 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1573 (let ((line (org-table-clean-line
1574 (buffer-substring (point-at-bol) (point-at-eol))))
1575 (col (current-column)))
1576 (while (string-match "|\\( +\\)|" line
)
1577 (setq line
(replace-match
1578 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1579 ?-
) "|") t t line
)))
1580 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1581 (beginning-of-line (if above
1 2))
1583 (beginning-of-line (if above
1 -
1))
1584 (org-move-to-column col
)
1585 (and org-table-overlay-coordinates
(org-table-align))))
1588 (defun org-table-hline-and-move (&optional same-column
)
1589 "Insert a hline and move to the row below that line."
1591 (let ((col (org-table-current-column)))
1592 (org-table-maybe-eval-formula)
1593 (org-table-maybe-recalculate-line)
1594 (org-table-insert-hline)
1596 (if (looking-at "\n[ \t]*|-")
1597 (progn (insert "\n|") (org-table-align))
1598 (org-table-next-field))
1599 (if same-column
(org-table-goto-column col
))))
1601 (defun org-table-clean-line (s)
1602 "Convert a table line S into a string with only \"|\" and space.
1603 In particular, this does handle wide and invisible characters."
1604 (if (string-match "^[ \t]*|-" s
)
1605 ;; It's a hline, just map the characters
1606 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1607 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1608 (setq s
(replace-match
1609 (concat "|" (make-string (org-string-width (match-string 1 s
))
1615 (defun org-table-kill-row ()
1616 "Delete the current row or horizontal line from the table."
1618 (if (not (org-at-table-p))
1619 (user-error "Not at a table"))
1620 (let ((col (current-column))
1621 (dline (org-table-current-dline)))
1622 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1623 (if (not (org-at-table-p)) (beginning-of-line 0))
1624 (org-move-to-column col
)
1625 (when (or (not org-table-fix-formulas-confirm
)
1626 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1627 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1631 (defun org-table-sort-lines (with-case &optional sorting-type
)
1632 "Sort table lines according to the column at point.
1634 The position of point indicates the column to be used for
1635 sorting, and the range of lines is the range between the nearest
1636 horizontal separator lines, or the entire table of no such lines
1637 exist. If point is before the first column, you will be prompted
1638 for the sorting column. If there is an active region, the mark
1639 specifies the first line and the sorting column, while point
1640 should be in the last line to be included into the sorting.
1642 The command then prompts for the sorting type which can be
1643 alphabetically, numerically, or by time (as given in a time stamp
1644 in the field). Sorting in reverse order is also possible.
1646 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1648 If SORTING-TYPE is specified when this function is called from a Lisp
1649 program, no prompting will take place. SORTING-TYPE must be a character,
1650 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1651 should be done in reverse order."
1653 (let* ((thisline (org-current-line))
1654 (thiscol (org-table-current-column))
1655 (otc org-table-overlay-coordinates
)
1656 beg end bcol ecol tend tbeg column lns pos
)
1657 (when (equal thiscol
0)
1658 (if (org-called-interactively-p 'any
)
1661 (read-string "Use column N for sorting: ")))
1663 (org-table-goto-column thiscol
))
1664 (org-table-check-inside-data-field)
1665 (if (org-region-active-p)
1667 (setq beg
(region-beginning) end
(region-end))
1669 (setq column
(org-table-current-column)
1672 (setq end
(point-at-bol 2)))
1673 (setq column
(org-table-current-column)
1675 tbeg
(org-table-begin)
1676 tend
(org-table-end))
1677 (if (re-search-backward org-table-hline-regexp tbeg t
)
1678 (setq beg
(point-at-bol 2))
1680 (setq beg
(point-at-bol 1)))
1682 (if (re-search-forward org-table-hline-regexp tend t
)
1683 (setq end
(point-at-bol 1))
1685 (setq end
(point-at-bol))))
1686 (setq beg
(move-marker (make-marker) beg
)
1687 end
(move-marker (make-marker) end
))
1690 (org-table-goto-column column
)
1691 (skip-chars-backward "^|")
1692 (setq bcol
(current-column))
1693 (org-table-goto-column (1+ column
))
1694 (skip-chars-backward "^|")
1695 (setq ecol
(1- (current-column)))
1696 (org-table-goto-column column
)
1697 (setq lns
(mapcar (lambda(x) (cons
1698 (org-sort-remove-invisible
1700 (org-split-string x
"[ \t]*|[ \t]*")))
1702 (org-split-string (buffer-substring beg end
) "\n")))
1703 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1704 (when org-table-overlay-coordinates
1705 (org-table-toggle-coordinate-overlays))
1706 (delete-region beg end
)
1707 (move-marker beg nil
)
1708 (move-marker end nil
)
1709 (insert (mapconcat 'cdr lns
"\n") "\n")
1710 (org-goto-line thisline
)
1711 (org-table-goto-column thiscol
)
1712 (when otc
(org-table-toggle-coordinate-overlays))
1713 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1716 (defun org-table-cut-region (beg end
)
1717 "Copy region in table to the clipboard and blank all relevant fields.
1718 If there is no active region, use just the field at point."
1720 (if (org-region-active-p) (region-beginning) (point))
1721 (if (org-region-active-p) (region-end) (point))))
1722 (org-table-copy-region beg end
'cut
))
1725 (defun org-table-copy-region (beg end
&optional cut
)
1726 "Copy rectangular region in table to clipboard.
1727 A special clipboard is used which can only be accessed
1728 with `org-table-paste-rectangle'."
1730 (if (org-region-active-p) (region-beginning) (point))
1731 (if (org-region-active-p) (region-end) (point))
1732 current-prefix-arg
))
1733 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1735 (rpl (if cut
" " nil
)))
1737 (org-table-check-inside-data-field)
1738 (setq l01
(org-current-line)
1739 c01
(org-table-current-column))
1741 (org-table-check-inside-data-field)
1742 (setq l02
(org-current-line)
1743 c02
(org-table-current-column))
1744 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1745 c1
(min c01 c02
) c2
(max c01 c02
))
1749 (if (> l1 l2
) (throw 'exit t
))
1751 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1752 (setq cols nil ic1 c1 ic2 c2
)
1753 (while (< ic1
(1+ ic2
))
1754 (push (org-table-get-field ic1 rpl
) cols
)
1755 (setq ic1
(1+ ic1
)))
1756 (push (nreverse cols
) region
)
1757 (setq l1
(1+ l1
)))))
1758 (setq org-table-clip
(nreverse region
))
1759 (if cut
(org-table-align))
1763 (defun org-table-paste-rectangle ()
1764 "Paste a rectangular region into a table.
1765 The upper right corner ends up in the current field. All involved fields
1766 will be overwritten. If the rectangle does not fit into the present table,
1767 the table is enlarged as needed. The process ignores horizontal separator
1770 (unless (and org-table-clip
(listp org-table-clip
))
1771 (user-error "First cut/copy a region to paste!"))
1772 (org-table-check-inside-data-field)
1773 (let* ((clip org-table-clip
)
1774 (line (org-current-line))
1775 (col (org-table-current-column))
1776 (org-enable-table-editor t
)
1777 (org-table-automatic-realign nil
)
1779 (while (setq cols
(pop clip
))
1780 (while (org-at-table-hline-p) (beginning-of-line 2))
1781 (if (not (org-at-table-p))
1782 (progn (end-of-line 0) (org-table-next-field)))
1784 (while (setq field
(pop cols
))
1785 (org-table-goto-column c nil
'force
)
1786 (org-table-get-field nil field
)
1788 (beginning-of-line 2))
1789 (org-goto-line line
)
1790 (org-table-goto-column col
)
1794 (defun org-table-convert ()
1795 "Convert from `org-mode' table to table.el and back.
1796 Obviously, this only works within limits. When an Org-mode table is
1797 converted to table.el, all horizontal separator lines get lost, because
1798 table.el uses these as cell boundaries and has no notion of horizontal lines.
1799 A table.el table can be converted to an Org-mode table only if it does not
1800 do row or column spanning. Multiline cells will become multiple cells.
1801 Beware, Org-mode does not test if the table can be successfully converted - it
1802 blindly applies a recipe that works for simple tables."
1805 (if (org-at-table.el-p
)
1806 ;; convert to Org-mode table
1807 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1808 (end (move-marker (make-marker) (org-table-end t
))))
1809 (table-unrecognize-region beg end
)
1811 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1814 (if (org-at-table-p)
1815 ;; convert to table.el table
1816 (let ((beg (move-marker (make-marker) (org-table-begin)))
1817 (end (move-marker (make-marker) (org-table-end))))
1818 ;; first, get rid of all horizontal lines
1820 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1822 ;; insert a hline before first
1824 (org-table-insert-hline 'above
)
1825 (beginning-of-line -
1)
1826 ;; insert a hline after each line
1827 (while (progn (beginning-of-line 3) (< (point) end
))
1828 (org-table-insert-hline))
1830 (setq end
(move-marker end
(org-table-end)))
1831 ;; replace "+" at beginning and ending of hlines
1832 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1833 (replace-match "\\1+-"))
1835 (while (re-search-forward "-|[ \t]*$" end t
)
1836 (replace-match "-+"))
1839 (defun org-table-transpose-table-at-point ()
1840 "Transpose Org table at point and eliminate hlines.
1848 will be transposed as
1855 Note that horizontal lines disappear."
1857 (let* ((table (delete 'hline
(org-table-to-lisp)))
1858 (dline_old (org-table-current-line))
1859 (col_old (org-table-current-column))
1860 (contents (mapcar (lambda (p)
1866 (setq tp
(cdr tp
))))
1869 (goto-char (org-table-begin))
1870 (re-search-forward "|")
1872 (delete-region (point) (org-table-end))
1875 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1877 (org-table-goto-line col_old
)
1878 (org-table-goto-column dline_old
))
1882 (defun org-table-wrap-region (arg)
1883 "Wrap several fields in a column like a paragraph.
1884 This is useful if you'd like to spread the contents of a field over several
1885 lines, in order to keep the table compact.
1887 If there is an active region, and both point and mark are in the same column,
1888 the text in the column is wrapped to minimum width for the given number of
1889 lines. Generally, this makes the table more compact. A prefix ARG may be
1890 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1891 formats the selected text to two lines. If the region was longer than two
1892 lines, the remaining lines remain empty. A negative prefix argument reduces
1893 the current number of lines by that amount. The wrapped text is pasted back
1894 into the table. If you formatted it to more lines than it was before, fields
1895 further down in the table get overwritten - so you might need to make space in
1898 If there is no region, the current field is split at the cursor position and
1899 the text fragment to the right of the cursor is prepended to the field one
1902 If there is no region, but you specify a prefix ARG, the current field gets
1903 blank, and the content is appended to the field above."
1905 (org-table-check-inside-data-field)
1906 (if (org-region-active-p)
1907 ;; There is a region: fill as a paragraph
1908 (let* ((beg (region-beginning))
1909 (cline (save-excursion (goto-char beg
) (org-current-line)))
1910 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1912 (org-table-cut-region (region-beginning) (region-end))
1913 (if (> (length (car org-table-clip
)) 1)
1914 (user-error "Region must be limited to single column"))
1915 (setq nlines
(if arg
1917 (+ (length org-table-clip
) arg
)
1919 (length org-table-clip
)))
1920 (setq org-table-clip
1921 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1923 (org-goto-line cline
)
1924 (org-table-goto-column ccol
)
1925 (org-table-paste-rectangle))
1926 ;; No region, split the current field at point
1927 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1928 (skip-chars-forward "^\r\n|"))
1930 ;; combine with field above
1931 (let ((s (org-table-blank-field))
1932 (col (org-table-current-column)))
1933 (beginning-of-line 0)
1934 (while (org-at-table-hline-p) (beginning-of-line 0))
1935 (org-table-goto-column col
)
1936 (skip-chars-forward "^|")
1937 (skip-chars-backward " ")
1938 (insert " " (org-trim s
))
1941 (if (looking-at "\\([^|]+\\)+|")
1942 (let ((s (match-string 1)))
1943 (replace-match " |")
1944 (goto-char (match-beginning 0))
1945 (org-table-next-row)
1946 (insert (org-trim s
) " ")
1948 (org-table-next-row)))))
1950 (defvar org-field-marker nil
)
1953 (defun org-table-edit-field (arg)
1954 "Edit table field in a different window.
1955 This is mainly useful for fields that contain hidden parts.
1956 When called with a \\[universal-argument] prefix, just make the full field visible so that
1957 it can be edited in place."
1961 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1963 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1964 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1965 (remove-text-properties b e
'(org-cwidth t invisible t
1966 display t intangible t
))
1967 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1968 (font-lock-fontify-block))))
1970 (let ((pos (point-marker))
1972 (if (eq org-table-use-standard-references t
)
1973 (concat (org-number-to-letters (org-table-current-column))
1974 (int-to-string (org-table-current-dline)))
1975 (concat "@" (int-to-string (org-table-current-dline))
1976 "$" (int-to-string (org-table-current-column)))))
1977 (field (org-table-get-field))
1978 (cw (current-window-configuration))
1981 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1982 (when (and (local-variable-p 'org-field-marker
)
1983 (markerp org-field-marker
))
1984 (move-marker org-field-marker nil
))
1986 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1987 (let ((org-inhibit-startup t
)) (org-mode))
1989 (setq truncate-lines nil
)
1991 (goto-char (setq p
(point-max)))
1992 (insert (org-trim field
))
1993 (remove-text-properties p
(point-max)
1994 '(invisible t org-cwidth t display t
1997 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1998 (org-set-local 'org-window-configuration cw
)
1999 (org-set-local 'org-field-marker pos
)
2000 (message "Edit and finish with C-c C-c")))))
2002 (defun org-table-finish-edit-field ()
2003 "Finish editing a table data field.
2004 Remove all newline characters, insert the result into the table, realign
2005 the table and kill the editing buffer."
2006 (let ((pos org-field-marker
)
2007 (cw org-window-configuration
)
2008 (cb (current-buffer))
2010 (goto-char (point-min))
2011 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2012 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2013 (replace-match " "))
2014 (setq text
(org-trim (buffer-string)))
2015 (set-window-configuration cw
)
2017 (select-window (get-buffer-window (marker-buffer pos
)))
2019 (move-marker pos nil
)
2020 (org-table-check-inside-data-field)
2021 (org-table-get-field nil text
)
2023 (message "New field value inserted")))
2025 (define-minor-mode org-table-follow-field-mode
2026 "Minor mode to make the table field editor window follow the cursor.
2027 When this mode is active, the field editor window will always show the
2028 current field. The mode exits automatically when the cursor leaves the
2029 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2030 nil
" TblFollow" nil
2031 (if org-table-follow-field-mode
2032 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2034 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2035 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2036 (win (and buf
(get-buffer-window buf
))))
2037 (when win
(delete-window win
))
2039 (with-current-buffer buf
2040 (move-marker org-field-marker nil
))
2041 (kill-buffer buf
)))))
2043 (defun org-table-follow-fields-with-editor ()
2044 (if (and org-table-exit-follow-field-mode-when-leaving-table
2045 (not (org-at-table-p)))
2046 ;; We have left the table, exit the follow mode
2047 (org-table-follow-field-mode -
1)
2048 (when (org-table-check-inside-data-field 'noerror
)
2049 (let ((win (selected-window)))
2050 (org-table-edit-field nil
)
2051 (org-fit-window-to-buffer)
2052 (select-window win
)))))
2054 (defvar org-timecnt
) ; dynamically scoped parameter
2057 (defun org-table-sum (&optional beg end nlast
)
2058 "Sum numbers in region of current table column.
2059 The result will be displayed in the echo area, and will be available
2060 as kill to be inserted with \\[yank].
2062 If there is an active region, it is interpreted as a rectangle and all
2063 numbers in that rectangle will be summed. If there is no active
2064 region and point is located in a table column, sum all numbers in that
2067 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2068 numbers are assumed to be times as well (in decimal hours) and the
2069 numbers are added as such.
2071 If NLAST is a number, only the NLAST fields will actually be summed."
2074 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2076 ((and beg end
)) ; beg and end given explicitly
2077 ((org-region-active-p)
2078 (setq beg
(region-beginning) end
(region-end)))
2080 (setq col
(org-table-current-column))
2081 (goto-char (org-table-begin))
2082 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2083 (user-error "No table data"))
2084 (org-table-goto-column col
)
2086 (goto-char (org-table-end))
2087 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2088 (user-error "No table data"))
2089 (org-table-goto-column col
)
2090 (setq end
(point))))
2091 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2092 (items1 (cond ((not nlast
) items
)
2093 ((>= nlast
(length items
)) items
)
2094 (t (setq items
(reverse items
))
2095 (setcdr (nthcdr (1- nlast
) items
) nil
)
2097 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2099 (res (apply '+ numbers
))
2100 (sres (if (= org-timecnt
0)
2101 (number-to-string res
)
2102 (setq diff
(* 3600 res
)
2103 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2104 m
(floor (/ diff
60)) diff
(mod diff
60)
2106 (format "%.0f:%02.0f:%02.0f" h m s
))))
2108 (if (org-called-interactively-p 'interactive
)
2110 (substitute-command-keys
2111 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2112 (length numbers
) sres
))))
2115 (defun org-table-get-number-for-summing (s)
2117 (if (string-match "^ *|? *" s
)
2118 (setq s
(replace-match "" nil nil s
)))
2119 (if (string-match " *|? *$" s
)
2120 (setq s
(replace-match "" nil nil s
)))
2121 (setq n
(string-to-number s
))
2123 ((and (string-match "0" s
)
2124 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2125 ((string-match "\\`[ \t]+\\'" s
) nil
)
2126 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2127 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2128 (m (string-to-number (or (match-string 2 s
) "0")))
2129 (s (string-to-number (or (match-string 4 s
) "0"))))
2130 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2131 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2135 (defun org-table-current-field-formula (&optional key noerror
)
2136 "Return the formula active for the current field.
2137 Assumes that specials are in place.
2138 If KEY is given, return the key to this formula.
2139 Otherwise return the formula preceded with \"=\" or \":=\"."
2140 (let* ((name (car (rassoc (list (org-current-line)
2141 (org-table-current-column))
2142 org-table-named-field-locations
)))
2143 (col (org-table-current-column))
2144 (scol (int-to-string col
))
2145 (ref (format "@%d$%d" (org-table-current-dline) col
))
2146 (stored-list (org-table-get-stored-formulas noerror
))
2147 (ass (or (assoc name stored-list
)
2148 (assoc ref stored-list
)
2149 (assoc scol stored-list
))))
2152 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2155 (defun org-table-get-formula (&optional equation named
)
2156 "Read a formula from the minibuffer, offer stored formula as default.
2157 When NAMED is non-nil, look for a named equation."
2158 (let* ((stored-list (org-table-get-stored-formulas))
2159 (name (car (rassoc (list (org-current-line)
2160 (org-table-current-column))
2161 org-table-named-field-locations
)))
2162 (ref (format "@%d$%d" (org-table-current-dline)
2163 (org-table-current-column)))
2164 (refass (assoc ref stored-list
))
2165 (nameass (assoc name stored-list
))
2167 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2170 (int-to-string (org-table-current-column))))
2171 (dummy (and (or nameass refass
) (not named
)
2172 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2173 (message "Formula not replaced")))
2174 (name (or name ref
))
2175 (org-table-may-need-update nil
)
2176 (stored (cdr (assoc scol stored-list
)))
2178 ((and stored equation
(string-match "^ *=? *$" equation
))
2182 (t (org-table-formula-from-user
2184 (org-table-formula-to-user
2185 (format "%s formula %s%s="
2186 (if named
"Field" "Column")
2187 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2189 (if stored
(org-table-formula-to-user stored
) "")
2190 'org-table-formula-history
2193 (when (not (string-match "\\S-" eq
))
2195 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2196 (org-table-store-formulas stored-list
)
2197 (user-error "Formula removed"))
2198 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2199 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2200 (if (and name
(not named
))
2201 ;; We set the column equation, delete the named one.
2202 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2205 (setcdr (assoc scol stored-list
) eq
)
2206 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2207 (if (or mustsave
(not (equal stored eq
)))
2208 (org-table-store-formulas stored-list
))
2211 (defun org-table-store-formulas (alist)
2212 "Store the list of formulas below the current table."
2213 (setq alist
(sort alist
'org-table-formula-less-p
))
2214 (let ((case-fold-search t
))
2216 (goto-char (org-table-end))
2217 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2219 ;; don't overwrite TBLFM, we might use text properties to store stuff
2220 (goto-char (match-beginning 3))
2221 (delete-region (match-beginning 3) (match-end 0)))
2223 (insert (or (match-string 2) "#+TBLFM:")))
2225 (mapconcat (lambda (x)
2227 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2228 (car x
) "=" (cdr x
)))
2232 (defsubst org-table-formula-make-cmp-string
(a)
2233 (when (string-match "\\`$[<>]" a
)
2234 (let ((arrow (string-to-char (substring a
1))))
2235 ;; Fake a high number to make sure this is sorted at the end.
2236 (setq a
(org-table-formula-handle-first/last-rc a
))
2237 (setq a
(format "$%d" (+ 10000
2238 (if (= arrow ?
<) -
1000 0)
2239 (string-to-number (substring a
1)))))))
2241 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2245 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2247 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2249 (concat "@@" (match-string 5 a
))))))
2251 (defun org-table-formula-less-p (a b
)
2252 "Compare two formulas for sorting."
2253 (let ((as (org-table-formula-make-cmp-string (car a
)))
2254 (bs (org-table-formula-make-cmp-string (car b
))))
2255 (and as bs
(string< as bs
))))
2258 (defun org-table-get-stored-formulas (&optional noerror
)
2259 "Return an alist with the stored formulas directly after current table."
2260 (interactive) ;; FIXME interactive?
2261 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2263 (goto-char (org-table-end))
2264 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2265 (setq strings
(org-split-string (org-match-string-no-properties 2)
2267 (while (setq string
(pop strings
))
2268 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2269 (setq scol
(if (match-end 2)
2270 (match-string 2 string
)
2271 (match-string 1 string
))
2272 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2273 (concat "$" scol
) scol
)
2274 eq
(match-string 3 string
)
2275 eq-alist
(cons (cons scol eq
) eq-alist
))
2276 (if (member scol seen
)
2279 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2282 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2283 (push scol seen
))))))
2284 (nreverse eq-alist
)))
2286 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2287 "Modify the equations after the table structure has been edited.
2288 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2289 For all numbers larger than LIMIT, shift them by DELTA."
2291 (goto-char (org-table-end))
2292 (let ((case-fold-search t
)
2293 (s-end (save-excursion (re-search-forward "^\\S-*$\\|\\'" nil t
))))
2294 (while (re-search-forward "[ \t]*#\\+tblfm:" s-end t
)
2295 (let ((msg "The formulas in #+TBLFM have been updated")
2296 (re (concat key
"\\([0-9]+\\)"))
2299 (if (or (equal key
"$") (equal key
"$LR"))
2300 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2301 (regexp-quote key
) remove
)
2302 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2305 (while (re-search-forward re2
(point-at-eol) t
)
2306 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2307 (if (equal (char-before (match-beginning 0)) ?.
)
2308 (user-error "Change makes TBLFM term %s invalid, use undo to recover"
2310 (replace-match "")))))
2311 (while (re-search-forward re
(point-at-eol) t
)
2312 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2313 (setq s
(match-string 1) n
(string-to-number s
))
2315 ((setq a
(assoc s replace
))
2316 (replace-match (concat key
(cdr a
)) t t
)
2318 ((and limit
(> n limit
))
2319 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2320 (message msg
))))))))))
2322 (defun org-table-get-specials ()
2323 "Get the column names and local parameters for this table."
2325 (let ((beg (org-table-begin)) (end (org-table-end))
2326 names name fields fields1 field cnt
2327 c v l line col types dlines hlines last-dline
)
2328 (setq org-table-column-names nil
2329 org-table-local-parameters nil
2330 org-table-named-field-locations nil
2331 org-table-current-begin-line nil
2332 org-table-current-begin-pos nil
2333 org-table-current-line-types nil
2334 org-table-current-ncol
0)
2336 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2337 (setq names
(org-split-string (match-string 1) " *| *")
2339 (while (setq name
(pop names
))
2341 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2342 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2343 (setq org-table-column-names
(nreverse org-table-column-names
))
2344 (setq org-table-column-name-regexp
2345 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2347 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2348 (setq fields
(org-split-string (match-string 1) " *| *"))
2349 (while (setq field
(pop fields
))
2350 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2351 (push (cons (match-string 1 field
) (match-string 2 field
))
2352 org-table-local-parameters
))))
2354 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2355 (setq c
(match-string 1)
2356 fields
(org-split-string (match-string 2) " *| *"))
2358 (beginning-of-line (if (equal c
"_") 2 0))
2359 (setq line
(org-current-line) col
1)
2360 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2361 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2362 (while (and fields1
(setq field
(pop fields
)))
2363 (setq v
(pop fields1
) col
(1+ col
))
2364 (when (and (stringp field
) (stringp v
)
2365 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2366 (push (cons field v
) org-table-local-parameters
)
2367 (push (list field line col
) org-table-named-field-locations
))))
2368 ;; Analyse the line types
2370 (setq org-table-current-begin-line
(org-current-line)
2371 org-table-current-begin-pos
(point)
2372 l org-table-current-begin-line
)
2373 (while (looking-at "[ \t]*|\\(-\\)?")
2374 (push (if (match-end 1) 'hline
'dline
) types
)
2375 (if (match-end 1) (push l hlines
) (push l dlines
))
2376 (beginning-of-line 2)
2378 (push 'hline types
) ;; add an imaginary extra hline to the end
2379 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2380 last-dline
(car dlines
)
2381 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2382 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2383 (org-goto-line last-dline
)
2384 (let* ((l last-dline
)
2385 (fields (org-split-string
2386 (buffer-substring (point-at-bol) (point-at-eol))
2388 (nfields (length fields
))
2390 (setq org-table-current-ncol nfields
)
2391 (loop for i from
1 to nfields do
2392 (push (list (format "LR%d" i
) l i
) al
)
2393 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2394 (setq org-table-named-field-locations
2395 (append org-table-named-field-locations al
))
2396 (setq org-table-local-parameters
2397 (append org-table-local-parameters al2
))))))
2400 (defun org-table-maybe-eval-formula ()
2401 "Check if the current field starts with \"=\" or \":=\".
2402 If yes, store the formula and apply it."
2403 ;; We already know we are in a table. Get field will only return a formula
2404 ;; when appropriate. It might return a separator line, but no problem.
2405 (when org-table-formula-evaluate-inline
2406 (let* ((field (org-trim (or (org-table-get-field) "")))
2408 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2409 (setq named
(equal (string-to-char field
) ?
:)
2410 eq
(match-string 1 field
))
2411 (if (or (fboundp 'calc-eval
)
2412 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2413 (org-table-eval-formula (if named
'(4) nil
)
2414 (org-table-formula-from-user eq
))
2415 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2417 (defvar org-recalc-commands nil
2418 "List of commands triggering the recalculation of a line.
2419 Will be filled automatically during use.")
2421 (defvar org-recalc-marks
2422 '((" " .
"Unmarked: no special line, no automatic recalculation")
2423 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2424 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2425 ("!" .
"Column name definition line. Reference in formula as $name.")
2426 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2427 ("_" .
"Names for values in row below this one.")
2428 ("^" .
"Names for values in row above this one.")))
2431 (defun org-table-rotate-recalc-marks (&optional newchar
)
2432 "Rotate the recalculation mark in the first column.
2433 If in any row, the first field is not consistent with a mark,
2434 insert a new column for the markers.
2435 When there is an active region, change all the lines in the region,
2436 after prompting for the marking character.
2437 After each change, a message will be displayed indicating the meaning
2440 (unless (org-at-table-p) (user-error "Not at a table"))
2441 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2442 (beg (org-table-begin))
2443 (end (org-table-end))
2444 (l (org-current-line))
2445 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2446 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2450 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2451 (col (org-table-current-column))
2452 (forcenew (car (assoc newchar org-recalc-marks
)))
2455 (message "Change region to what mark? Type # * ! $ or SPC: ")
2456 (setq newchar
(char-to-string (read-char-exclusive))
2457 forcenew
(car (assoc newchar org-recalc-marks
))))
2458 (if (and newchar
(not forcenew
))
2459 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2461 (if l1
(org-goto-line l1
))
2463 (beginning-of-line 1)
2464 (unless (looking-at org-table-dataline-regexp
)
2465 (user-error "Not at a table data line")))
2467 (org-table-goto-column 1)
2468 (org-table-insert-column)
2469 (org-table-goto-column (1+ col
)))
2470 (setq epos
(point-at-eol))
2472 (beginning-of-line 1)
2473 (org-table-get-field
2474 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2476 (setq new
(or forcenew
2477 (cadr (member (match-string 1) marks
))))
2483 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2484 (and (looking-at org-table-dataline-regexp
)
2485 (org-table-get-field 1 (concat " " new
" "))))
2486 (org-goto-line l1
)))
2487 (if (not (= epos
(point-at-eol))) (org-table-align))
2489 (and (org-called-interactively-p 'interactive
)
2490 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2493 (defun org-table-maybe-recalculate-line ()
2494 "Recompute the current line if marked for it, and if we haven't just done it."
2496 (and org-table-allow-automatic-line-recalculation
2497 (not (and (memq last-command org-recalc-commands
)
2498 (equal org-last-recalc-line
(org-current-line))))
2499 (save-excursion (beginning-of-line 1)
2500 (looking-at org-table-auto-recalculate-regexp
))
2501 (org-table-recalculate) t
))
2503 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2504 (defsubst org-set-calc-mode
(var &optional value
)
2506 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2507 ("R" calc-angle-mode rad
)
2508 ("F" calc-prefer-frac t
)
2509 ("S" calc-symbolic-mode t
)))
2510 value
(nth 2 var
) var
(nth 1 var
)))
2511 (if (memq var org-tbl-calc-modes
)
2512 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2513 (cons var
(cons value org-tbl-calc-modes
)))
2517 (defun org-table-eval-formula (&optional arg equation
2518 suppress-align suppress-const
2519 suppress-store suppress-analysis
)
2520 "Replace the table field value at the cursor by the result of a calculation.
2522 This function makes use of Dave Gillespie's Calc package, in my view the
2523 most exciting program ever written for GNU Emacs. So you need to have Calc
2524 installed in order to use this function.
2526 In a table, this command replaces the value in the current field with the
2527 result of a formula. It also installs the formula as the \"current\" column
2528 formula, by storing it in a special line below the table. When called
2529 with a `C-u' prefix, the current field must be a named field, and the
2530 formula is installed as valid in only this specific field.
2532 When called with two `C-u' prefixes, insert the active equation
2533 for the field back into the current field, so that it can be
2534 edited there. This is useful in order to use \\[org-table-show-reference]
2535 to check the referenced fields.
2537 When called, the command first prompts for a formula, which is read in
2538 the minibuffer. Previously entered formulas are available through the
2539 history list, and the last used formula is offered as a default.
2540 These stored formulas are adapted correctly when moving, inserting, or
2541 deleting columns with the corresponding commands.
2543 The formula can be any algebraic expression understood by the Calc package.
2544 For details, see the Org-mode manual.
2546 This function can also be called from Lisp programs and offers
2547 additional arguments: EQUATION can be the formula to apply. If this
2548 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2549 used to speed-up recursive calls by by-passing unnecessary aligns.
2550 SUPPRESS-CONST suppresses the interpretation of constants in the
2551 formula, assuming that this has been done already outside the function.
2552 SUPPRESS-STORE means the formula should not be stored, either because
2553 it is already stored, or because it is a modified equation that should
2554 not overwrite the stored one."
2556 (org-table-check-inside-data-field)
2557 (or suppress-analysis
(org-table-get-specials))
2558 (if (equal arg
'(16))
2559 (let ((eq (org-table-current-field-formula)))
2560 (or eq
(user-error "No equation active for current field"))
2561 (org-table-get-field nil eq
)
2563 (setq org-table-may-need-update t
))
2565 (ndown (if (integerp arg
) arg
1))
2566 (org-table-automatic-realign nil
)
2567 (case-fold-search nil
)
2569 (formula (if (and equation suppress-store
)
2571 (org-table-get-formula equation
(equal arg
'(4)))))
2572 (n0 (org-table-current-column))
2573 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2574 (numbers nil
) ; was a variable, now fixed default
2576 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2577 duration duration-output-format
)
2578 ;; Parse the format string. Since we have a lot of modes, this is
2579 ;; a lot of work. However, I think calc still uses most of the time.
2580 (if (string-match ";" formula
)
2581 (let ((tmp (org-split-string formula
";")))
2582 (setq formula
(car tmp
)
2583 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2585 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2586 (setq c
(string-to-char (match-string 1 fmt
))
2587 n
(string-to-number (match-string 2 fmt
)))
2589 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2590 (setq org-tbl-calc-modes
2593 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2594 (?s . sci
) (?e . eng
))))
2596 (setq fmt
(replace-match "" t t fmt
)))
2597 (if (string-match "T" fmt
)
2598 (setq duration t numbers t
2599 duration-output-format nil
2600 fmt
(replace-match "" t t fmt
)))
2601 (if (string-match "t" fmt
)
2603 duration-output-format org-table-duration-custom-format
2605 fmt
(replace-match "" t t fmt
)))
2606 (if (string-match "N" fmt
)
2608 fmt
(replace-match "" t t fmt
)))
2609 (if (string-match "L" fmt
)
2611 fmt
(replace-match "" t t fmt
)))
2612 (if (string-match "E" fmt
)
2614 fmt
(replace-match "" t t fmt
)))
2615 (while (string-match "[DRFS]" fmt
)
2616 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2617 (setq fmt
(replace-match "" t t fmt
)))
2618 (unless (string-match "\\S-" fmt
)
2620 (if (and (not suppress-const
) org-table-formula-use-constants
)
2621 (setq formula
(org-table-formula-substitute-names formula
)))
2622 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2624 (setq fields
(org-split-string
2625 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2627 ;; replace fields with duration values if relevant
2630 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2633 (setq fields
(mapcar
2635 (if (string-match "\\S-" x
)
2636 (number-to-string (string-to-number x
))
2639 (setq ndown
(1- ndown
))
2640 (setq form
(copy-sequence formula
)
2641 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2642 (if (and lispp literal
) (setq lispp
'literal
))
2644 ;; Insert row and column number of formula result field
2645 (while (string-match "[@$]#" form
)
2650 (if (equal (substring form
(match-beginning 0)
2651 (1+ (match-beginning 0)))
2653 (org-table-current-dline)
2654 (org-table-current-column))))
2657 ;; Check for old vertical references
2658 (setq form
(org-table-rewrite-old-row-references form
))
2659 ;; Insert remote references
2660 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2664 (org-table-make-reference
2665 (let ((rmtrng (org-table-get-remote-range
2666 (match-string 1 form
) (match-string 2 form
))))
2669 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2670 (org-table-time-string-to-seconds rmtrng
))
2672 keep-empty numbers lispp
))
2674 ;; Insert complex ranges
2675 (while (and (string-match org-table-range-regexp form
)
2676 (> (length (match-string 0 form
)) 1))
2677 (setq formrg
(save-match-data
2678 (org-table-get-range (match-string 0 form
) nil n0
)))
2681 (org-table-make-reference
2682 ;; possibly handle durations
2685 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2686 (org-table-time-string-to-seconds formrg
))
2688 keep-empty numbers lispp
)))
2689 (if (not (save-match-data
2690 (string-match (regexp-quote form
) formrpl
)))
2691 (setq form
(replace-match formrpl t t form
))
2692 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2693 ;; Insert simple ranges
2694 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2698 (org-table-make-reference
2700 fields
(string-to-number (match-string 1 form
))
2701 (string-to-number (match-string 2 form
)))
2702 keep-empty numbers lispp
))
2705 ;; Insert the references to fields in same row
2706 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2707 (setq n
(+ (string-to-number (match-string 1 form
))
2708 (if (match-end 2) n0
0))
2709 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2710 (unless x
(user-error "Invalid field specifier \"%s\""
2711 (match-string 0 form
)))
2712 (setq form
(replace-match
2714 (org-table-make-reference
2715 x keep-empty numbers lispp
))
2719 (setq ev
(condition-case nil
2720 (eval (eval (read form
)))
2722 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2723 ev
(if duration
(org-table-time-seconds-to-string
2724 (string-to-number ev
)
2725 duration-output-format
) ev
))
2726 (or (fboundp 'calc-eval
)
2727 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2728 ;; Use <...> time-stamps so that Calc can handle them
2729 (setq form
(replace-regexp-in-string org-ts-regexp3
"<\\1>" form
))
2730 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2731 (when (string-match org-ts-regexp2 form
)
2732 (let* ((ts (match-string 0 form
))
2733 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2734 (system-time-locale "C")
2735 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2736 (cdr org-time-stamp-formats
))
2737 (car org-time-stamp-formats
))))
2738 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2740 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2742 (calc-eval (cons form org-tbl-calc-modes
)
2743 (when (and (not keep-empty
) numbers
) 'num
)))
2744 ev
(if duration
(org-table-time-seconds-to-string
2745 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2746 (string-to-number (org-table-time-string-to-seconds ev
))
2747 (string-to-number ev
))
2748 duration-output-format
)
2751 (when org-table-formula-debug
2752 (with-output-to-temp-buffer "*Substitution History*"
2753 (princ (format "Substitution history of formula
2757 $1-> %s\n" orig formula form0 form
))
2759 (princ (format " %s^\nError: %s"
2760 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2761 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2763 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2764 (setq bw
(get-buffer-window "*Substitution History*"))
2765 (org-fit-window-to-buffer bw
)
2766 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2767 (unless (let (inhibit-redisplay)
2768 (y-or-n-p "Debugging Formula. Continue to next? "))
2770 (user-error "Abort"))
2773 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2774 (org-table-justify-field-maybe
2775 (format org-table-formula-field-format
2776 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2777 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2778 (call-interactively 'org-return
)
2780 (and down
(org-table-maybe-recalculate-line))
2781 (or suppress-align
(and org-table-may-need-update
2782 (org-table-align))))))
2784 (defun org-table-put-field-property (prop value
)
2786 (put-text-property (progn (skip-chars-backward "^|") (point))
2787 (progn (skip-chars-forward "^|") (point))
2790 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2791 "Get a calc vector from a column, according to descriptor DESC.
2792 Optional arguments TBEG and COL can give the beginning of the table and
2793 the current column, to avoid unnecessary parsing.
2795 HIGHLIGHT means just highlight the range.
2797 When CORNERS-ONLY is set, only return the corners of the range as
2798 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2799 in the buffer and column1 and column2 are table column numbers."
2800 (if (not (equal (string-to-char desc
) ?
@))
2801 (setq desc
(concat "@" desc
)))
2803 (or tbeg
(setq tbeg
(org-table-begin)))
2804 (or col
(setq col
(org-table-current-column)))
2805 (let ((thisline (org-current-line))
2806 beg end c1 c2 r1 r2 rangep tmp
)
2807 (unless (string-match org-table-range-regexp desc
)
2808 (user-error "Invalid table range specifier `%s'" desc
))
2809 (setq rangep
(match-end 3)
2810 r1
(and (match-end 1) (match-string 1 desc
))
2811 r2
(and (match-end 4) (match-string 4 desc
))
2812 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2813 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2815 (and c1
(setq c1
(+ (string-to-number c1
)
2816 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2817 (and c2
(setq c2
(+ (string-to-number c2
)
2818 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2819 (if (equal r1
"") (setq r1 nil
))
2820 (if (equal r2
"") (setq r2 nil
))
2821 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2822 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2823 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2824 (if (not r1
) (setq r1 thisline
))
2825 (if (not r2
) (setq r2 thisline
))
2826 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2827 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2828 (if (and (not corners-only
)
2829 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2833 (while (not (looking-at org-table-dataline-regexp
))
2834 (beginning-of-line 2))
2835 (prog1 (org-trim (org-table-get-field c1
))
2836 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2837 ;; A range, return a vector
2838 ;; First sort the numbers to get a regular rectangle
2839 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2840 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2842 ;; Only return the corners of the range
2844 ;; Copy the range values into a list
2846 (while (not (looking-at org-table-dataline-regexp
))
2847 (beginning-of-line 2))
2848 (org-table-goto-column c1
)
2851 (while (not (looking-at org-table-dataline-regexp
))
2852 (beginning-of-line 0))
2853 (org-table-goto-column c2
)
2856 (org-table-highlight-rectangle
2857 beg
(progn (skip-chars-forward "^|\n") (point))))
2858 ;; return string representation of calc vector
2860 (apply 'append
(org-table-copy-region beg end
))))))))
2862 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2863 "Analyze descriptor DESC and retrieve the corresponding line number.
2864 The cursor is currently in line CLINE, the table begins in line BLINE,
2865 and TABLE is a vector with line types."
2866 (if (string-match "^[0-9]+$" desc
)
2867 (aref org-table-dlines
(string-to-number desc
))
2868 (setq cline
(or cline
(org-current-line))
2869 bline
(or bline org-table-current-begin-line
)
2870 table
(or table org-table-current-line-types
))
2872 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2874 (and (not (match-end 3)) (not (match-end 6)))
2875 (and (match-end 3) (match-end 6) (not (match-end 5))))
2876 (user-error "Invalid row descriptor `%s'" desc
))
2877 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2878 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2879 (odir (and (match-end 5) (match-string 5 desc
)))
2880 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2882 (rel (and (match-end 6)
2883 (or (and (match-end 1) (not (match-end 3)))
2885 (if (and hn
(not hdir
))
2888 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2889 (if (and (not hn
) on
(not odir
))
2890 (user-error "Should never happen");;(aref org-table-dlines on)
2891 (if (and hn
(> hn
0))
2892 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2893 nil hn cline desc
)))
2895 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2896 rel on cline desc
)))
2899 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2900 "FIXME: Needs more documentation."
2901 (let ((l (length table
)))
2903 (while (and (setq i
(+ i
(if backwards -
1 1)))
2905 (not (eq (aref table i
) type
))
2906 (if (and relative
(eq (aref table i
) 'hline
))
2908 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2909 ((eq org-table-relative-ref-may-cross-hline
'error
)
2910 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2911 (t (setq i
(- i
(if backwards -
1 1))
2916 (if (or (< i
0) (>= i l
))
2917 (user-error "Row descriptor %s used in line %d leads outside table"
2921 (defun org-table-rewrite-old-row-references (s)
2922 (if (string-match "&[-+0-9I]" s
)
2923 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2926 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2927 "Convert list ELEMENTS to something appropriate to insert into formula.
2928 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2929 NUMBERS indicates that everything should be converted to numbers.
2930 LISPP non-nil means to return something appropriate for a Lisp
2931 list, 'literal is for the format specifier L."
2932 ;; Calc nan (not a number) is used for the conversion of the empty
2933 ;; field to a reference for several reasons: (i) It is accepted in a
2934 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2935 ;; (ii) In a single field (not in range) it can be distinguished
2936 ;; from "(nan)" which is the reference made from a single field
2937 ;; containing "nan".
2938 (if (stringp elements
)
2941 (if (eq lispp
'literal
)
2943 (if (and (eq elements
"") (not keep-empty
))
2946 (if numbers
(string-to-number elements
) elements
))))
2947 (if (string-match "\\S-" elements
)
2949 (when numbers
(setq elements
(number-to-string
2950 (string-to-number elements
))))
2951 (concat "(" elements
")"))
2952 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2957 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2959 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
2963 (if (eq lispp
'literal
)
2965 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2967 (concat "[" (mapconcat
2969 (if (string-match "\\S-" x
)
2971 (number-to-string (string-to-number x
))
2973 (if (or (not keep-empty
) numbers
) "0" "nan")))
2978 (defun org-table-set-constants ()
2979 "Set `org-table-formula-constants-local' in the current buffer."
2980 (let (cst consts const-str
)
2982 (goto-char (point-min))
2983 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
2984 (setq const-str
(substring-no-properties (match-string 1)))
2985 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
2988 (while (setq e
(pop consts
))
2989 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
2990 (if (assoc-string (match-string 1 e
) cst
)
2991 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
2992 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
2993 (setq org-table-formula-constants-local cst
)))))))
2996 (defun org-table-recalculate (&optional all noalign
)
2997 "Recalculate the current table line by applying all stored formulas.
2998 With prefix arg ALL, do this for all lines in the table.
2999 With the prefix argument ALL is `(16)' \
3000 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3001 it is the symbol `iterate', recompute the table until it no longer changes.
3002 If NOALIGN is not nil, do not re-align the table after the computations
3003 are done. This is typically used internally to save time, if it is
3004 known that the table will be realigned a little later anyway."
3006 (or (memq this-command org-recalc-commands
)
3007 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
3008 (unless (org-at-table-p) (user-error "Not at a table"))
3009 (if (or (eq all
'iterate
) (equal all
'(16)))
3011 (org-table-get-specials)
3012 (let* ((eqlist (sort (org-table-get-stored-formulas)
3013 (lambda (a b
) (string< (car a
) (car b
)))))
3014 (eqlist1 (copy-sequence eqlist
))
3015 (inhibit-redisplay (not debug-on-error
))
3016 (line-re org-table-dataline-regexp
)
3017 (thisline (org-current-line))
3018 (thiscol (org-table-current-column))
3020 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3021 ;; Insert constants in all formulas
3024 (if (string-match "^@-?I+" (car x
))
3025 (user-error "Can't assign to hline relative reference"))
3026 (when (string-match "\\`$[<>]" (car x
))
3028 (setq x
(cons (substring
3029 (org-table-formula-handle-first/last-rc
3032 (if (assoc (car x
) eqlist1
)
3033 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3036 (org-table-formula-handle-first/last-rc
(car x
))
3037 (org-table-formula-substitute-names
3038 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3040 ;; Split the equation list
3041 (while (setq eq
(pop eqlist
))
3042 (if (<= (string-to-char (car eq
)) ?
9)
3045 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3046 ;; Expand ranges in lhs of formulas
3047 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3049 ;; Get the correct line range to process
3052 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3053 (goto-char (setq beg
(org-table-begin)))
3054 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3055 ;; This is a table with marked lines, compute selected lines
3056 (setq line-re org-table-recalculate-regexp
)
3057 ;; Move forward to the first non-header line
3058 (if (and (re-search-forward org-table-dataline-regexp end t
)
3059 (re-search-forward org-table-hline-regexp end t
)
3060 (re-search-forward org-table-dataline-regexp end t
))
3061 (setq beg
(match-beginning 0))
3062 nil
))) ;; just leave beg where it is
3063 (setq beg
(point-at-bol)
3064 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3066 (and all
(message "Re-applying formulas to full table..."))
3068 ;; First find the named fields, and mark them untouchable.
3069 ;; Also check if several field/range formulas try to set the same field.
3070 (remove-text-properties beg end
'(org-untouchable t
))
3071 (while (setq eq
(pop eqlname
))
3073 a
(assoc name org-table-named-field-locations
))
3075 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3077 (when (member name1 seen-fields
)
3078 (user-error "Several field/range formulas try to set %s" name1
))
3079 (push name1 seen-fields
)
3082 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3085 (aref org-table-dlines
3086 (string-to-number (match-string 1 name
)))
3087 (error (user-error "Invalid row number in %s"
3089 (string-to-number (match-string 2 name
)))))
3090 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3091 (message "Re-applying formula to field: %s" name
)
3092 (org-goto-line (nth 1 a
))
3093 (org-table-goto-column (nth 2 a
))
3094 (push (append a
(list (cdr eq
))) eqlname1
)
3095 (org-table-put-field-property :org-untouchable t
)))
3096 (setq eqlname1
(nreverse eqlname1
))
3098 ;; Now evaluate the column formulas, but skip fields covered by
3101 (while (re-search-forward line-re end t
)
3102 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3103 ;; Unprotected line, recalculate
3104 (and all
(message "Re-applying formulas to full table...(line %d)"
3105 (setq cnt
(1+ cnt
))))
3106 (setq org-last-recalc-line
(org-current-line))
3108 (while (setq entry
(pop eql
))
3109 (org-goto-line org-last-recalc-line
)
3110 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3111 (unless (get-text-property (point) :org-untouchable
)
3112 (org-table-eval-formula nil
(cdr entry
)
3113 'noalign
'nocst
'nostore
'noanalysis
)))))
3115 ;; Now evaluate the field formulas
3116 (while (setq eq
(pop eqlname1
))
3117 (message "Re-applying formula to field: %s" (car eq
))
3118 (org-goto-line (nth 1 eq
))
3119 (org-table-goto-column (nth 2 eq
))
3120 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3121 'nostore
'noanalysis
))
3123 (org-goto-line thisline
)
3124 (org-table-goto-column thiscol
)
3125 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3126 (or noalign
(and org-table-may-need-update
(org-table-align))
3127 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3129 ;; back to initial position
3130 (message "Re-applying formulas...done")
3131 (org-goto-line thisline
)
3132 (org-table-goto-column thiscol
)
3133 (or noalign
(and org-table-may-need-update
(org-table-align))
3134 (and all
(message "Re-applying formulas...done"))))))
3137 (defun org-table-iterate (&optional arg
)
3138 "Recalculate the table until it does not change anymore.
3139 The maximum number of iterations is 10, but you can choose a different value
3140 with the prefix ARG."
3142 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3144 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3149 (org-table-recalculate 'all
)
3150 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3151 (if (not (string= lasttbl thistbl
))
3152 (setq lasttbl thistbl
)
3154 (message "Convergence after %d iterations" i
)
3155 (message "Table was already stable"))
3157 (user-error "No convergence after %d iterations" i
))))
3160 (defun org-table-recalculate-buffer-tables ()
3161 "Recalculate all tables in the current buffer."
3166 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3169 (defun org-table-iterate-buffer-tables ()
3170 "Iterate all tables in the buffer, to converge inter-table dependencies."
3174 (checksum (md5 (buffer-string)))
3182 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3183 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3185 (message "Convergence after %d iterations" (- imax i
))
3187 (setq checksum c1
)))
3188 (user-error "No convergence after %d iterations" imax
))))))
3190 (defun org-table-calc-current-TBLFM (&optional arg
)
3191 "Apply the #+TBLFM in the line at point to the table."
3193 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3194 (let ((formula (buffer-substring
3199 ;; Insert a temporary formula at right after the table
3200 (goto-char (org-table-TBLFM-begin))
3201 (setq s
(set-marker (make-marker) (point)))
3202 (insert (concat formula
"\n"))
3203 (setq e
(set-marker (make-marker) (point)))
3204 ;; Recalculate the table
3205 (beginning-of-line 0) ; move to the inserted line
3206 (skip-chars-backward " \r\n\t")
3207 (if (org-at-table-p)
3209 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3210 ;; delete the formula inserted temporarily
3211 (delete-region s e
))))))
3213 (defun org-table-TBLFM-begin ()
3214 "Find the beginning of the TBLFM lines and return its position.
3215 Return nil when the beginning of TBLFM line was not found."
3217 (when (progn (forward-line 1)
3219 org-table-TBLFM-begin-regexp
3223 (defun org-table-expand-lhs-ranges (equations)
3224 "Expand list of formulas.
3225 If some of the RHS in the formulas are ranges or a row reference, expand
3226 them to individual field equations for each field."
3227 (let (e res lhs rhs range r1 r2 c1 c2
)
3228 (while (setq e
(pop equations
))
3229 (setq lhs
(car e
) rhs
(cdr e
))
3231 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3232 ;; This just refers to one fixed field
3234 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3235 ;; This just refers to one fixed named field
3237 ((string-match "^@[0-9]+$" lhs
)
3238 (loop for ic from
1 to org-table-current-ncol do
3239 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3240 (put-text-property 0 (length (caar res
))
3241 :orig-eqn e
(caar res
))))
3243 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3245 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3246 r2
(nth 2 range
) c2
(nth 3 range
))
3247 (setq r1
(org-table-line-to-dline r1
))
3248 (setq r2
(org-table-line-to-dline r2
'above
))
3249 (loop for ir from r1 to r2 do
3250 (loop for ic from c1 to c2 do
3251 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3252 (put-text-property 0 (length (caar res
))
3253 :orig-eqn e
(caar res
)))))))
3256 (defun org-table-formula-handle-first/last-rc
(s)
3257 "Replace @<, @>, $<, $> with first/last row/column of the table.
3258 So @< and $< will always be replaced with @1 and $1, respectively.
3259 The advantage of these special markers are that structure editing of
3260 the table will not change them, while @1 and $1 will be modified
3261 when a line/row is swapped out of that privileged position. So for
3262 formulas that use a range of rows or columns, it may often be better
3263 to anchor the formula with \"I\" row markers, or to offset from the
3264 borders of the table using the @< @> $< $> makers."
3265 (let (n nmax len char
(start 0))
3266 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3269 (setq start
(match-end 3))
3270 (setq nmax
(if (equal (match-string 1 s
) "@")
3271 (1- (length org-table-dlines
))
3272 org-table-current-ncol
)
3273 len
(- (match-end 2) (match-beginning 2))
3274 char
(string-to-char (match-string 2 s
))
3278 (if (or (< n
1) (> n nmax
))
3279 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3280 (match-string 0 s
) s
))
3281 (setq start
(match-beginning 0))
3282 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3285 (defun org-table-formula-substitute-names (f)
3286 "Replace $const with values in string F."
3287 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3288 ;; First, check for column names
3289 (while (setq start
(string-match org-table-column-name-regexp f start
))
3290 (setq start
(1+ start
))
3291 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3292 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3293 ;; Parameters and constants
3295 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3297 (setq start
(match-end 2))
3298 (setq start
(1+ start
))
3299 (if (setq a
(save-match-data
3300 (org-table-get-constant (match-string 1 f
))))
3301 (setq f
(replace-match
3302 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3303 (if org-table-formula-debug
3304 (put-text-property 0 (length f
) :orig-formula f1 f
))
3307 (defun org-table-get-constant (const)
3308 "Find the value for a parameter or constant in a formula.
3309 Parameters get priority."
3310 (or (cdr (assoc const org-table-local-parameters
))
3311 (cdr (assoc const org-table-formula-constants-local
))
3312 (cdr (assoc const org-table-formula-constants
))
3313 (and (fboundp 'constants-get
) (constants-get const
))
3314 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3315 (org-entry-get nil
(substring const
5) 'inherit
))
3318 (defvar org-table-fedit-map
3319 (let ((map (make-sparse-keymap)))
3320 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3321 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3322 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3323 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3324 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3325 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3326 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3327 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3328 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3329 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3330 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3331 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3332 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3333 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3334 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3335 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3336 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3337 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3338 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3339 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3342 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3344 ["Finish and Install" org-table-fedit-finish t
]
3345 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3346 ["Abort" org-table-fedit-abort t
]
3348 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3349 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3351 "Shift Reference at Point"
3352 ["Up" org-table-fedit-ref-up t
]
3353 ["Down" org-table-fedit-ref-down t
]
3354 ["Left" org-table-fedit-ref-left t
]
3355 ["Right" org-table-fedit-ref-right t
]
3357 "Change Test Row for Column Formulas"
3358 ["Up" org-table-fedit-line-up t
]
3359 ["Down" org-table-fedit-line-down t
]
3361 ["Scroll Table Window" org-table-fedit-scroll t
]
3362 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3363 ["Show Table Grid" org-table-fedit-toggle-coordinates
3364 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3365 org-table-overlay-coordinates
)]
3367 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3368 :style toggle
:selected org-table-buffer-is-an
]))
3373 (defun org-table-edit-formulas ()
3374 "Edit the formulas of the current table in a separate buffer."
3376 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3377 (beginning-of-line 0))
3378 (unless (org-at-table-p) (user-error "Not at a table"))
3379 (org-table-get-specials)
3380 (let ((key (org-table-current-field-formula 'key
'noerror
))
3381 (eql (sort (org-table-get-stored-formulas 'noerror
)
3382 'org-table-formula-less-p
))
3383 (pos (point-marker))
3385 (wc (current-window-configuration))
3386 (sel-win (selected-window))
3387 (titles '((column .
"# Column Formulas\n")
3388 (field .
"# Field and Range Formulas\n")
3389 (named .
"# Named Field Formulas\n")))
3391 (org-switch-to-buffer-other-window "*Edit Formulas*")
3393 ;; Keep global-font-lock-mode from turning on font-lock-mode
3394 (let ((font-lock-global-modes '(not fundamental-mode
)))
3396 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3397 (org-set-local 'org-pos pos
)
3398 (org-set-local 'org-window-configuration wc
)
3399 (org-set-local 'org-selected-window sel-win
)
3400 (use-local-map org-table-fedit-map
)
3401 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3402 (easy-menu-add org-table-fedit-menu
)
3403 (setq startline
(org-current-line))
3404 (while (setq entry
(pop eql
))
3406 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3407 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3408 ((string-match "^[0-9]" (car entry
)) 'column
)
3410 (when (setq title
(assq type titles
))
3411 (or (bobp) (insert "\n"))
3412 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3413 (setq titles
(remove title titles
)))
3414 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3415 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3416 (car entry
) " = " (cdr entry
) "\n"))
3417 (remove-text-properties 0 (length s
) '(face nil
) s
)
3419 (if (eq org-table-use-standard-references t
)
3420 (org-table-fedit-toggle-ref-type))
3421 (org-goto-line startline
)
3422 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3424 (defun org-table-fedit-post-command ()
3425 (when (not (memq this-command
'(lisp-complete-symbol)))
3426 (let ((win (selected-window)))
3429 (org-table-show-reference)
3431 (select-window win
)))))
3433 (defun org-table-formula-to-user (s)
3434 "Convert a formula from internal to user representation."
3435 (if (eq org-table-use-standard-references t
)
3436 (org-table-convert-refs-to-an s
)
3439 (defun org-table-formula-from-user (s)
3440 "Convert a formula from user to internal representation."
3441 (if org-table-use-standard-references
3442 (org-table-convert-refs-to-rc s
)
3445 (defun org-table-convert-refs-to-rc (s)
3446 "Convert spreadsheet references from A7 to @7$28.
3447 Works for single references, but also for entire formulas and even the
3450 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3453 ;; format match, just advance
3454 (setq start
(match-end 0)))
3455 ((and (> (match-beginning 0) 0)
3456 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3457 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3458 ;; 3.e5 or something like this.
3459 (setq start
(match-end 0)))
3460 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3461 ;; (member (match-string 1 s)
3462 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3464 ;; function name, just advance
3465 (setq start
(match-end 0)))
3467 (setq start
(match-beginning 0)
3469 (if (equal (match-string 2 s
) "&")
3470 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3472 (string-to-number (match-string 2 s
))
3473 (org-letters-to-number (match-string 1 s
))))
3477 (defun org-table-convert-refs-to-an (s)
3478 "Convert spreadsheet references from to @7$28 to AB7.
3479 Works for single references, but also for entire formulas and even the
3481 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3482 (setq s
(replace-match
3484 (org-number-to-letters
3485 (string-to-number (match-string 2 s
)))
3486 (string-to-number (match-string 1 s
)))
3488 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3489 (setq s
(replace-match (concat "\\1"
3490 (org-number-to-letters
3491 (string-to-number (match-string 2 s
))) "&")
3495 (defun org-letters-to-number (s)
3496 "Convert a base 26 number represented by letters into an integer.
3497 For example: AB -> 28."
3500 (while (> (length s
) 0)
3501 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3505 (defun org-number-to-letters (n)
3506 "Convert an integer into a base 26 number represented by letters.
3507 For example: 28 -> AB."
3510 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3514 (defun org-table-time-string-to-seconds (s)
3515 "Convert a time string into numerical duration in seconds.
3516 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3517 If S is a string representing a number, keep this number."
3520 (let (hour minus min sec res
)
3522 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3523 (setq minus
(< 0 (length (match-string 1 s
)))
3524 hour
(string-to-number (match-string 2 s
))
3525 min
(string-to-number (match-string 3 s
))
3526 sec
(string-to-number (match-string 4 s
)))
3528 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3529 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3530 ((and (not (string-match org-ts-regexp-both s
))
3531 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3532 (setq minus
(< 0 (length (match-string 1 s
)))
3533 hour
(string-to-number (match-string 2 s
))
3534 min
(string-to-number (match-string 3 s
)))
3536 (setq res
(- (+ (* hour
3600) (* min
60))))
3537 (setq res
(+ (* hour
3600) (* min
60)))))
3538 (t (setq res
(string-to-number s
))))
3539 (number-to-string res
))))
3541 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3542 "Convert a number of seconds to a time string.
3543 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3544 minutes or seconds."
3545 (let* ((secs0 (abs secs
))
3547 (cond ((eq output-format
'days
)
3548 (format "%.3f" (/ (float secs0
) 86400)))
3549 ((eq output-format
'hours
)
3550 (format "%.2f" (/ (float secs0
) 3600)))
3551 ((eq output-format
'minutes
)
3552 (format "%.1f" (/ (float secs0
) 60)))
3553 ((eq output-format
'seconds
)
3554 (format "%d" secs0
))
3555 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3556 (if (< secs
0) (concat "-" res
) res
)))
3558 (defun org-table-fedit-convert-buffer (function)
3559 "Convert all references in this buffer, using FUNCTION."
3560 (let ((line (org-current-line)))
3561 (goto-char (point-min))
3563 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3564 (delete-region (point) (point-at-eol))
3565 (or (eobp) (forward-char 1)))
3566 (org-goto-line line
)))
3568 (defun org-table-fedit-toggle-ref-type ()
3569 "Convert all references in the buffer from B3 to @3$2 and back."
3571 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3572 (org-table-fedit-convert-buffer
3573 (if org-table-buffer-is-an
3574 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3575 (message "Reference type switched to %s"
3576 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3578 (defun org-table-fedit-ref-up ()
3579 "Shift the reference at point one row/hline up."
3581 (org-table-fedit-shift-reference 'up
))
3582 (defun org-table-fedit-ref-down ()
3583 "Shift the reference at point one row/hline down."
3585 (org-table-fedit-shift-reference 'down
))
3586 (defun org-table-fedit-ref-left ()
3587 "Shift the reference at point one field to the left."
3589 (org-table-fedit-shift-reference 'left
))
3590 (defun org-table-fedit-ref-right ()
3591 "Shift the reference at point one field to the right."
3593 (org-table-fedit-shift-reference 'right
))
3595 (defun org-table-fedit-shift-reference (dir)
3597 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3598 (if (memq dir
'(left right
))
3599 (org-rematch-and-replace 1 (eq dir
'left
))
3600 (user-error "Cannot shift reference in this direction")))
3601 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3602 ;; A B3-like reference
3603 (if (memq dir
'(up down
))
3604 (org-rematch-and-replace 2 (eq dir
'up
))
3605 (org-rematch-and-replace 1 (eq dir
'left
))))
3607 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3608 ;; An internal reference
3609 (if (memq dir
'(up down
))
3610 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3611 (org-rematch-and-replace 5 (eq dir
'left
))))))
3613 (defun org-rematch-and-replace (n &optional decr hline
)
3614 "Re-match the group N, and replace it with the shifted reference."
3615 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3616 (goto-char (match-beginning n
))
3617 (and (looking-at (regexp-quote (match-string n
)))
3618 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3621 (defun org-table-shift-refpart (ref &optional decr hline
)
3622 "Shift a reference part REF.
3623 If DECR is set, decrease the references row/column, else increase.
3624 If HLINE is set, this may be a hline reference, it certainly is not
3625 a translation reference."
3627 (let* ((sign (string-match "^[-+]" ref
)) n
)
3629 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3631 ((and hline
(string-match "^I+" ref
))
3632 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3633 (setq n
(+ n
(if decr -
1 1)))
3634 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3636 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3638 (concat sign
(make-string n ?I
)))
3640 ((string-match "^[0-9]+" ref
)
3641 (setq n
(string-to-number (concat sign ref
)))
3642 (setq n
(+ n
(if decr -
1 1)))
3644 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3645 (number-to-string (max 1 n
))))
3647 ((string-match "^[a-zA-Z]+" ref
)
3648 (org-number-to-letters
3649 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3651 (t (user-error "Cannot shift reference"))))))
3653 (defun org-table-fedit-toggle-coordinates ()
3654 "Toggle the display of coordinates in the referenced table."
3656 (let ((pos (marker-position org-pos
)))
3657 (with-current-buffer (marker-buffer org-pos
)
3660 (org-table-toggle-coordinate-overlays)))))
3662 (defun org-table-fedit-finish (&optional arg
)
3663 "Parse the buffer for formula definitions and install them.
3664 With prefix ARG, apply the new formulas to the table."
3666 (org-table-remove-rectangle-highlight)
3667 (if org-table-use-standard-references
3669 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3670 (setq org-table-buffer-is-an nil
)))
3671 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3672 (goto-char (point-min))
3673 (while (re-search-forward
3674 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3676 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3677 form
(match-string 3))
3678 (setq form
(org-trim form
))
3679 (when (not (equal form
""))
3680 (while (string-match "[ \t]*\n[ \t]*" form
)
3681 (setq form
(replace-match " " t t form
)))
3682 (when (assoc var eql
)
3683 (user-error "Double formulas for %s" var
))
3684 (push (cons var form
) eql
)))
3686 (set-window-configuration org-window-configuration
)
3687 (select-window sel-win
)
3689 (unless (org-at-table-p)
3690 (user-error "Lost table position - cannot install formulas"))
3691 (org-table-store-formulas eql
)
3692 (move-marker pos nil
)
3693 (kill-buffer "*Edit Formulas*")
3695 (org-table-recalculate 'all
)
3696 (message "New formulas installed - press C-u C-c C-c to apply."))))
3698 (defun org-table-fedit-abort ()
3699 "Abort editing formulas, without installing the changes."
3701 (org-table-remove-rectangle-highlight)
3702 (let ((pos org-pos
) (sel-win org-selected-window
))
3703 (set-window-configuration org-window-configuration
)
3704 (select-window sel-win
)
3706 (move-marker pos nil
)
3707 (message "Formula editing aborted without installing changes")))
3709 (defun org-table-fedit-lisp-indent ()
3710 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3712 (let ((pos (point)) beg end ind
)
3713 (beginning-of-line 1)
3715 ((looking-at "[ \t]")
3717 (call-interactively 'lisp-indent-line
))
3718 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3719 ((not (fboundp 'pp-buffer
))
3720 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3721 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3722 (goto-char (- (match-end 0) 2))
3724 (setq ind
(make-string (current-column) ?\
))
3725 (condition-case nil
(forward-sexp 1)
3727 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3730 (narrow-to-region beg end
)
3731 (if (eq last-command this-command
)
3733 (goto-char (point-min))
3734 (setq this-command nil
)
3735 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3736 (replace-match " ")))
3738 (untabify (point-min) (point-max))
3739 (goto-char (1+ (point-min)))
3740 (while (re-search-forward "^." nil t
)
3741 (beginning-of-line 1)
3743 (goto-char (point-max))
3744 (org-delete-backward-char 1)))
3748 (defvar org-show-positions nil
)
3750 (defun org-table-show-reference (&optional local
)
3751 "Show the location/value of the $ expression at point."
3753 (org-table-remove-rectangle-highlight)
3755 (let ((pos (if local
(point) org-pos
))
3757 (org-inhibit-highlight-removal t
)
3758 (win (selected-window))
3759 (org-show-positions nil
)
3760 var name e what match dest
)
3761 (if local
(org-table-get-specials))
3763 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3764 (setq match
(concat (substring (match-string 0) 0 -
1)
3766 (substring (match-string 0) 0 -
1)
3769 ((or (org-at-regexp-p org-table-range-regexp2
)
3770 (org-at-regexp-p org-table-translate-regexp
)
3771 (org-at-regexp-p org-table-range-regexp
))
3774 (org-table-convert-refs-to-rc (match-string 0))))
3776 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3777 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3779 (t (user-error "No reference at point")))
3780 match
(and what
(or match
(match-string 0))))
3781 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3782 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3783 'secondary-selection
))
3784 (org-add-hook 'before-change-functions
3785 'org-table-remove-rectangle-highlight
)
3786 (if (eq what
'name
) (setq var
(substring match
1)))
3787 (when (eq what
'range
)
3788 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3789 (setq match
(org-table-formula-substitute-names match
)))
3793 (re-search-backward "^\\S-" nil t
)
3794 (beginning-of-line 1)
3795 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3798 (org-table-convert-refs-to-rc (match-string 1))))
3799 (org-table-add-rectangle-overlay
3800 (match-beginning 1) (match-end 1) face2
))))
3801 (if (and (markerp pos
) (marker-buffer pos
))
3802 (if (get-buffer-window (marker-buffer pos
))
3803 (select-window (get-buffer-window (marker-buffer pos
)))
3804 (org-switch-to-buffer-other-window (get-buffer-window
3805 (marker-buffer pos
)))))
3807 (org-table-force-dataline)
3809 (setq name
(substring dest
1))
3811 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3812 (setq e
(assoc name org-table-named-field-locations
))
3813 (org-goto-line (nth 1 e
))
3814 (org-table-goto-column (nth 2 e
)))
3815 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3816 (let ((l (string-to-number (match-string 1 dest
)))
3817 (c (string-to-number (match-string 2 dest
))))
3818 (org-goto-line (aref org-table-dlines l
))
3819 (org-table-goto-column c
)))
3820 (t (org-table-goto-column (string-to-number name
))))
3821 (move-marker pos
(point))
3822 (org-table-highlight-rectangle nil nil face2
))
3824 ((equal dest match
))
3829 (org-table-get-range match nil nil
'highlight
))
3831 ((setq e
(assoc var org-table-named-field-locations
))
3832 (org-goto-line (nth 1 e
))
3833 (org-table-goto-column (nth 2 e
))
3834 (org-table-highlight-rectangle (point) (point))
3835 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3836 ((setq e
(assoc var org-table-column-names
))
3837 (org-table-goto-column (string-to-number (cdr e
)))
3838 (org-table-highlight-rectangle (point) (point))
3839 (goto-char (org-table-begin))
3840 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3843 (goto-char (match-beginning 1))
3844 (org-table-highlight-rectangle)
3845 (message "Named column (column %s)" (cdr e
)))
3846 (user-error "Column name not found")))
3849 (org-table-goto-column (string-to-number (substring match
1)))
3850 (org-table-highlight-rectangle (point) (point))
3851 (message "Column %s" (substring match
1)))
3852 ((setq e
(assoc var org-table-local-parameters
))
3853 (goto-char (org-table-begin))
3854 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3856 (goto-char (match-beginning 1))
3857 (org-table-highlight-rectangle)
3858 (message "Local parameter."))
3859 (user-error "Parameter not found")))
3862 ((not var
) (user-error "No reference at point"))
3863 ((setq e
(assoc var org-table-formula-constants-local
))
3864 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3866 ((setq e
(assoc var org-table-formula-constants
))
3867 (message "Constant: $%s=%s in `org-table-formula-constants'."
3869 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3870 (message "Constant: $%s=%s, from `constants.el'%s."
3871 var e
(format " (%s units)" constants-unit-system
)))
3872 (t (user-error "Undefined name $%s" var
)))))
3874 (when (and org-show-positions
3875 (not (memq this-command
'(org-table-fedit-scroll
3876 org-table-fedit-scroll-down
))))
3877 (push pos org-show-positions
)
3878 (push org-table-current-begin-pos org-show-positions
)
3879 (let ((min (apply 'min org-show-positions
))
3880 (max (apply 'max org-show-positions
)))
3881 (goto-char min
) (recenter 0)
3883 (or (pos-visible-in-window-p max
) (recenter -
1))))
3884 (select-window win
))))
3886 (defun org-table-force-dataline ()
3887 "Make sure the cursor is in a dataline in a table."
3888 (unless (save-excursion
3889 (beginning-of-line 1)
3890 (looking-at org-table-dataline-regexp
))
3891 (let* ((re org-table-dataline-regexp
)
3892 (p1 (save-excursion (re-search-forward re nil
'move
)))
3893 (p2 (save-excursion (re-search-backward re nil
'move
))))
3895 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3897 ((or p1 p2
) (goto-char (or p1 p2
)))
3898 (t (user-error "No table dataline around here"))))))
3900 (defun org-table-fedit-line-up ()
3901 "Move cursor one line up in the window showing the table."
3903 (org-table-fedit-move 'previous-line
))
3905 (defun org-table-fedit-line-down ()
3906 "Move cursor one line down in the window showing the table."
3908 (org-table-fedit-move 'next-line
))
3910 (defun org-table-fedit-move (command)
3911 "Move the cursor in the window showing the table.
3912 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3913 (let ((org-table-allow-automatic-line-recalculation nil
)
3914 (pos org-pos
) (win (selected-window)) p
)
3915 (select-window (get-buffer-window (marker-buffer org-pos
)))
3917 (call-interactively command
)
3918 (while (and (org-at-table-p)
3919 (org-at-table-hline-p))
3920 (call-interactively command
))
3921 (or (org-at-table-p) (goto-char p
))
3922 (move-marker pos
(point))
3923 (select-window win
)))
3925 (defun org-table-fedit-scroll (N)
3927 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3928 (scroll-other-window N
)))
3930 (defun org-table-fedit-scroll-down (N)
3932 (org-table-fedit-scroll (- N
)))
3934 (defvar org-table-rectangle-overlays nil
)
3936 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3937 "Add a new overlay."
3938 (let ((ov (make-overlay beg end
)))
3939 (overlay-put ov
'face
(or face
'secondary-selection
))
3940 (push ov org-table-rectangle-overlays
)))
3942 (defun org-table-highlight-rectangle (&optional beg end face
)
3943 "Highlight rectangular region in a table."
3944 (setq beg
(or beg
(point)) end
(or end
(point)))
3945 (let ((b (min beg end
))
3948 (and (boundp 'org-show-positions
)
3949 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3950 (goto-char (min beg end
))
3951 (setq l1
(org-current-line)
3952 c1
(org-table-current-column))
3953 (goto-char (max beg end
))
3954 (setq l2
(org-current-line)
3955 c2
(org-table-current-column))
3956 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3958 (beginning-of-line 1)
3959 (loop for line from l1 to l2 do
3960 (when (looking-at org-table-dataline-regexp
)
3961 (org-table-goto-column c1
)
3962 (skip-chars-backward "^|\n") (setq beg
(point))
3963 (org-table-goto-column c2
)
3964 (skip-chars-forward "^|\n") (setq end
(point))
3965 (org-table-add-rectangle-overlay beg end face
))
3966 (beginning-of-line 2))
3968 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3970 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3971 "Remove the rectangle overlays."
3972 (unless org-inhibit-highlight-removal
3973 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3974 (mapc 'delete-overlay org-table-rectangle-overlays
)
3975 (setq org-table-rectangle-overlays nil
)))
3977 (defvar org-table-coordinate-overlays nil
3978 "Collects the coordinate grid overlays, so that they can be removed.")
3979 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3981 (defun org-table-overlay-coordinates ()
3982 "Add overlays to the table at point, to show row/column coordinates."
3984 (mapc 'delete-overlay org-table-coordinate-overlays
)
3985 (setq org-table-coordinate-overlays nil
)
3987 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3988 (goto-char (org-table-begin))
3989 (while (org-at-table-p)
3990 (setq eol
(point-at-eol))
3991 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3992 (push ov org-table-coordinate-overlays
)
3993 (setq hline
(looking-at org-table-hline-regexp
))
3994 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3995 (format "%4d" (setq id
(1+ id
)))))
3996 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3999 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4000 (setq beg
(1+ (match-beginning 0))
4002 s1
(concat "$" (int-to-string ic
))
4003 s2
(org-number-to-letters ic
)
4004 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4005 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4006 (push ov org-table-coordinate-overlays
)
4007 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4008 (beginning-of-line 2)))))
4011 (defun org-table-toggle-coordinate-overlays ()
4012 "Toggle the display of Row/Column numbers in tables."
4014 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4015 (message "Tables Row/Column numbers display turned %s"
4016 (if org-table-overlay-coordinates
"on" "off"))
4017 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4019 (unless org-table-overlay-coordinates
4020 (mapc 'delete-overlay org-table-coordinate-overlays
)
4021 (setq org-table-coordinate-overlays nil
)))
4024 (defun org-table-toggle-formula-debugger ()
4025 "Toggle the formula debugger in tables."
4027 (setq org-table-formula-debug
(not org-table-formula-debug
))
4028 (message "Formula debugging has been turned %s"
4029 (if org-table-formula-debug
"on" "off")))
4031 ;;; The orgtbl minor mode
4033 ;; Define a minor mode which can be used in other modes in order to
4034 ;; integrate the org-mode table editor.
4036 ;; This is really a hack, because the org-mode table editor uses several
4037 ;; keys which normally belong to the major mode, for example the TAB and
4038 ;; RET keys. Here is how it works: The minor mode defines all the keys
4039 ;; necessary to operate the table editor, but wraps the commands into a
4040 ;; function which tests if the cursor is currently inside a table. If that
4041 ;; is the case, the table editor command is executed. However, when any of
4042 ;; those keys is used outside a table, the function uses `key-binding' to
4043 ;; look up if the key has an associated command in another currently active
4044 ;; keymap (minor modes, major mode, global), and executes that command.
4045 ;; There might be problems if any of the keys used by the table editor is
4046 ;; otherwise used as a prefix key.
4048 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4049 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4050 ;; addresses this by checking explicitly for both bindings.
4052 ;; The optimized version (see variable `orgtbl-optimized') takes over
4053 ;; all keys which are bound to `self-insert-command' in the *global map*.
4054 ;; Some modes bind other commands to simple characters, for example
4055 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4056 ;; active, this binding is ignored inside tables and replaced with a
4057 ;; modified self-insert.
4060 (defvar orgtbl-mode-map
(make-keymap)
4061 "Keymap for `orgtbl-mode'.")
4063 (defvar org-old-auto-fill-inhibit-regexp nil
4064 "Local variable used by `orgtbl-mode'.")
4066 (defconst orgtbl-line-start-regexp
4067 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4068 "Matches a line belonging to an orgtbl.")
4070 (defconst orgtbl-extra-font-lock-keywords
4071 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4072 0 (quote 'org-table
) 'prepend
))
4073 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4075 ;; Install it as a minor mode.
4076 (put 'orgtbl-mode
:included t
)
4077 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4080 (define-minor-mode orgtbl-mode
4081 "The `org-mode' table editor as a minor mode for use in other modes."
4082 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4083 (org-load-modules-maybe)
4085 ((derived-mode-p 'org-mode
)
4086 ;; Exit without error, in case some hook functions calls this
4087 ;; by accident in org-mode.
4088 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4090 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4091 ;; Make sure we are first in minor-mode-map-alist
4092 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4093 ;; FIXME: maybe it should use emulation-mode-map-alists?
4094 (and c
(setq minor-mode-map-alist
4095 (cons c
(delq c minor-mode-map-alist
)))))
4096 (org-set-local (quote org-table-may-need-update
) t
)
4097 (org-add-hook 'before-change-functions
'org-before-change-function
4099 (org-set-local 'org-old-auto-fill-inhibit-regexp
4100 auto-fill-inhibit-regexp
)
4101 (org-set-local 'auto-fill-inhibit-regexp
4102 (if auto-fill-inhibit-regexp
4103 (concat orgtbl-line-start-regexp
"\\|"
4104 auto-fill-inhibit-regexp
)
4105 orgtbl-line-start-regexp
))
4106 (add-to-invisibility-spec '(org-cwidth))
4107 (when (fboundp 'font-lock-add-keywords
)
4108 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4109 (org-restart-font-lock))
4110 (easy-menu-add orgtbl-mode-menu
))
4112 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4113 (org-table-cleanup-narrow-column-properties)
4114 (org-remove-from-invisibility-spec '(org-cwidth))
4115 (remove-hook 'before-change-functions
'org-before-change-function t
)
4116 (when (fboundp 'font-lock-remove-keywords
)
4117 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4118 (org-restart-font-lock))
4119 (easy-menu-remove orgtbl-mode-menu
)
4120 (force-mode-line-update 'all
))))
4122 (defun org-table-cleanup-narrow-column-properties ()
4123 "Remove all properties related to narrow-column invisibility."
4124 (let ((s (point-min)))
4125 (while (setq s
(text-property-any s
(point-max)
4126 'display org-narrow-column-arrow
))
4127 (remove-text-properties s
(1+ s
) '(display t
)))
4128 (setq s
(point-min))
4129 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4130 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4131 (setq s
(point-min))
4132 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4133 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4135 (defun orgtbl-make-binding (fun n
&rest keys
)
4136 "Create a function for binding in the table minor mode.
4137 FUN is the command to call inside a table. N is used to create a unique
4138 command name. KEYS are keys that should be checked in for a command
4139 to execute outside of tables."
4142 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4144 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4145 "Outside of tables, run the binding of `"
4146 (mapconcat #'key-description keys
"' or `")
4151 (list 'call-interactively
(list 'quote fun
))
4152 (list 'let
'(orgtbl-mode)
4153 (list 'call-interactively
4156 (list 'key-binding k
))
4158 '('orgtbl-error
))))))))
4160 (defun orgtbl-error ()
4161 "Error when there is no default binding for a table key."
4163 (user-error "This key has no function outside tables"))
4165 (defun orgtbl-setup ()
4166 "Setup orgtbl keymaps."
4169 '(([(meta shift left
)] org-table-delete-column
)
4170 ([(meta left
)] org-table-move-column-left
)
4171 ([(meta right
)] org-table-move-column-right
)
4172 ([(meta shift right
)] org-table-insert-column
)
4173 ([(meta shift up
)] org-table-kill-row
)
4174 ([(meta shift down
)] org-table-insert-row
)
4175 ([(meta up
)] org-table-move-row-up
)
4176 ([(meta down
)] org-table-move-row-down
)
4177 ("\C-c\C-w" org-table-cut-region
)
4178 ("\C-c\M-w" org-table-copy-region
)
4179 ("\C-c\C-y" org-table-paste-rectangle
)
4180 ("\C-c\C-w" org-table-wrap-region
)
4181 ("\C-c-" org-table-insert-hline
)
4182 ("\C-c}" org-table-toggle-coordinate-overlays
)
4183 ("\C-c{" org-table-toggle-formula-debugger
)
4184 ("\C-m" org-table-next-row
)
4185 ([(shift return
)] org-table-copy-down
)
4186 ("\C-c?" org-table-field-info
)
4187 ("\C-c " org-table-blank-field
)
4188 ("\C-c+" org-table-sum
)
4189 ("\C-c=" org-table-eval-formula
)
4190 ("\C-c'" org-table-edit-formulas
)
4191 ("\C-c`" org-table-edit-field
)
4192 ("\C-c*" org-table-recalculate
)
4193 ("\C-c^" org-table-sort-lines
)
4194 ("\M-a" org-table-beginning-of-field
)
4195 ("\M-e" org-table-end-of-field
)
4196 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4198 (while (setq elt
(pop bindings
))
4199 (setq nfunc
(1+ nfunc
))
4200 (setq key
(org-key (car elt
))
4202 cmd
(orgtbl-make-binding fun nfunc key
))
4203 (org-defkey orgtbl-mode-map key cmd
))
4205 ;; Special treatment needed for TAB and RET
4206 (org-defkey orgtbl-mode-map
[(return)]
4207 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4208 (org-defkey orgtbl-mode-map
"\C-m"
4209 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4211 (org-defkey orgtbl-mode-map
[(tab)]
4212 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4213 (org-defkey orgtbl-mode-map
"\C-i"
4214 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4216 (org-defkey orgtbl-mode-map
[(shift tab
)]
4217 (orgtbl-make-binding 'org-table-previous-field
104
4218 [(shift tab
)] [(tab)] "\C-i"))
4221 (unless (featurep 'xemacs
)
4222 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4223 (orgtbl-make-binding 'org-table-previous-field
107
4224 [S-iso-lefttab
] [backtab] [(shift tab)]
4227 (org-defkey orgtbl-mode-map [backtab]
4228 (orgtbl-make-binding 'org-table-previous-field
108
4229 [backtab] [S-iso-lefttab] [(shift tab)]
4232 (org-defkey orgtbl-mode-map "\M-\C-m"
4233 (orgtbl-make-binding 'org-table-wrap-region 105
4234 "\M-\C-m" [(meta return)]))
4235 (org-defkey orgtbl-mode-map [(meta return)]
4236 (orgtbl-make-binding 'org-table-wrap-region 106
4237 [(meta return)] "\M-\C-m"))
4239 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4240 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4242 (when orgtbl-optimized
4243 ;; If the user wants maximum table support, we need to hijack
4244 ;; some standard editing functions
4245 (org-remap orgtbl-mode-map
4246 'self-insert-command 'orgtbl-self-insert-command
4247 'delete-char 'org-delete-char
4248 'delete-backward-char 'org-delete-backward-char)
4249 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4250 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4252 ["Create or convert" org-table-create-or-convert-from-region
4253 :active (not (org-at-table-p)) :keys "C-c |" ]
4255 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4256 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4257 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4258 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4260 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4261 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4262 ["Copy Field from Above"
4263 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4266 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4267 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4268 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4269 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4271 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4272 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4273 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4274 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4275 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4277 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4279 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4280 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4281 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4282 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4285 ["Insert table template" orgtbl-insert-radio-table
4286 (assq major-mode orgtbl-radio-table-templates)]
4287 ["Comment/uncomment table" orgtbl-toggle-comment t])
4289 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4290 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4291 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4292 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4293 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4294 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4295 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4296 ["Sum Column/Rectangle" org-table-sum
4297 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4298 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4300 org-table-toggle-formula-debugger :active (org-at-table-p)
4302 :style toggle :selected org-table-formula-debug]
4303 ["Show Col/Row Numbers"
4304 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4306 :style toggle :selected org-table-overlay-coordinates]
4310 (defun orgtbl-ctrl-c-ctrl-c (arg)
4311 "If the cursor is inside a table, realign the table.
4312 If it is a table to be sent away to a receiver, do it.
4313 With prefix arg, also recompute table."
4315 (let ((case-fold-search t) (pos (point)) action)
4317 (beginning-of-line 1)
4319 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4320 ((looking-at "[ \t]*|") pos)
4321 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4325 (org-table-maybe-eval-formula)
4327 (call-interactively 'org-table-recalculate)
4328 (org-table-maybe-recalculate-line))
4329 (call-interactively 'org-table-align)
4330 (when (orgtbl-send-table 'maybe)
4331 (run-hooks 'orgtbl-after-send-table-hook)))
4332 ((eq action 'recalc)
4333 (org-table-set-constants)
4335 (beginning-of-line 1)
4336 (skip-chars-backward " \r\n\t")
4337 (if (org-at-table-p)
4338 (org-call-with-arg 'org-table-recalculate t))))
4339 (t (let (orgtbl-mode)
4340 (call-interactively (key-binding "\C-c\C-c")))))))
4342 (defun orgtbl-create-or-convert-from-region (arg)
4343 "Create table or convert region to table, if no conflicting binding.
4344 This installs the table binding `C-c |', but only if there is no
4345 conflicting binding to this key outside orgtbl-mode."
4347 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4349 (call-interactively cmd)
4350 (call-interactively 'org-table-create-or-convert-from-region))))
4352 (defun orgtbl-tab (arg)
4353 "Justification and field motion for `orgtbl-mode'."
4355 (if arg (org-table-edit-field t)
4356 (org-table-justify-field-maybe)
4357 (org-table-next-field)))
4359 (defun orgtbl-ret ()
4360 "Justification and field motion for `orgtbl-mode'."
4364 (org-table-justify-field-maybe)
4365 (org-table-next-row)))
4367 (defun orgtbl-self-insert-command (N)
4368 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4369 If the cursor is in a table looking at whitespace, the whitespace is
4370 overwritten, and the table is not marked as requiring realignment."
4372 (if (and (org-at-table-p)
4374 (and org-table-auto-blank-field
4375 (member last-command
4376 '(orgtbl-hijacker-command-100
4377 orgtbl-hijacker-command-101
4378 orgtbl-hijacker-command-102
4379 orgtbl-hijacker-command-103
4380 orgtbl-hijacker-command-104
4381 orgtbl-hijacker-command-105
4383 (org-table-blank-field))
4386 (looking-at "[^|\n]* +|"))
4387 (let (org-table-may-need-update)
4388 (goto-char (1- (match-end 0)))
4389 (org-delete-backward-char 1)
4390 (goto-char (match-beginning 0))
4391 (self-insert-command N))
4392 (setq org-table-may-need-update t)
4395 (cmd (or (key-binding
4396 (or (and (listp function-key-map)
4397 (setq a (assoc last-input-event function-key-map))
4399 (vector last-input-event)))
4400 'self-insert-command)))
4401 (call-interactively cmd)
4402 (if (and org-self-insert-cluster-for-undo
4403 (eq cmd 'self-insert-command))
4404 (if (not (eq last-command 'orgtbl-self-insert-command))
4405 (setq org-self-insert-command-undo-counter 1)
4406 (if (>= org-self-insert-command-undo-counter 20)
4407 (setq org-self-insert-command-undo-counter 1)
4408 (and (> org-self-insert-command-undo-counter 0)
4410 (not (cadr buffer-undo-list)) ; remove nil entry
4411 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4412 (setq org-self-insert-command-undo-counter
4413 (1+ org-self-insert-command-undo-counter))))))))
4415 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4416 "Regular expression matching exponentials as produced by calc.")
4418 (defun orgtbl-gather-send-defs ()
4419 "Gather a plist of :name, :transform, :params for each destination before
4422 (goto-char (org-table-begin))
4424 (beginning-of-line 0)
4425 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4426 (let ((name (org-no-properties (match-string 1)))
4427 (transform (intern (match-string 2)))
4428 (params (if (match-end 3)
4429 (read (concat "(" (match-string 3) ")")))))
4430 (push (list :name name :transform transform :params params)
4432 (beginning-of-line 0)))
4435 (defun orgtbl-send-replace-tbl (name txt)
4436 "Find and replace table NAME with TXT."
4438 (goto-char (point-min))
4439 (unless (re-search-forward
4440 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4441 (user-error "Don't know where to insert translated table"))
4442 (goto-char (match-beginning 0))
4443 (beginning-of-line 2)
4445 (let ((beg (point)))
4446 (unless (re-search-forward
4447 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4448 (user-error "Cannot find end of insertion region"))
4449 (beginning-of-line 1)
4450 (delete-region beg (point))))
4454 (defun org-table-to-lisp (&optional txt)
4455 "Convert the table at point to a Lisp structure.
4456 The structure will be a list. Each item is either the symbol `hline'
4457 for a horizontal separator line, or a list of field values as strings.
4458 The table is taken from the parameter TXT, or from the buffer at point."
4460 (unless (org-at-table-p)
4461 (user-error "No table at point")))
4463 (buffer-substring-no-properties (org-table-begin)
4465 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4469 (if (string-match org-table-hline-regexp x)
4471 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4474 (defun orgtbl-send-table (&optional maybe)
4475 "Send a transformed version of this table to the receiver position.
4476 With argument MAYBE, fail quietly if no transformation is defined for
4480 (unless (org-at-table-p) (user-error "Not at a table"))
4481 ;; when non-interactive, we assume align has just happened.
4482 (when (org-called-interactively-p 'any) (org-table-align))
4483 (let ((dests (orgtbl-gather-send-defs))
4484 (txt (buffer-substring-no-properties (org-table-begin)
4487 (unless dests (if maybe (throw 'exit nil)
4488 (user-error "Don't know how to transform this table")))
4489 (dolist (dest dests)
4490 (let* ((name (plist-get dest :name))
4491 (transform (plist-get dest :transform))
4492 (params (plist-get dest :params))
4493 (skip (plist-get params :skip))
4494 (skipcols (plist-get params :skipcols))
4495 (no-escape (plist-get params :no-escape))
4497 (lines (org-table-clean-before-export
4499 (org-split-string txt "[ \t]*\n[ \t]*"))))
4500 (i0 (if org-table-clean-did-remove-column 2 1))
4501 (lines (if no-escape lines
4502 (mapcar (lambda(l) (replace-regexp-in-string
4503 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4506 (if (string-match org-table-hline-regexp x)
4508 (org-remove-by-index
4509 (org-split-string (org-trim x) "\\s-*|\\s-*")
4512 (fun (if (= i0 2) 'cdr 'identity))
4513 (org-table-last-alignment
4514 (org-remove-by-index (funcall fun org-table-last-alignment)
4516 (org-table-last-column-widths
4517 (org-remove-by-index (funcall fun org-table-last-column-widths)
4519 (txt (if (fboundp transform)
4520 (funcall transform table params)
4521 (user-error "No such transformation function %s" transform))))
4522 (orgtbl-send-replace-tbl name txt))
4523 (setq ntbl (1+ ntbl)))
4524 (message "Table converted and installed at %d receiver location%s"
4525 ntbl (if (> ntbl 1) "s" ""))
4530 (defun org-remove-by-index (list indices &optional i0)
4531 "Remove the elements in LIST with indices in INDICES.
4532 First element has index 0, or I0 if given."
4535 (if (integerp indices) (setq indices (list indices)))
4536 (setq i0 (1- (or i0 0)))
4537 (delq :rm (mapcar (lambda (x)
4539 (if (memq i0 indices) :rm x))
4542 (defun orgtbl-toggle-comment ()
4543 "Comment or uncomment the orgtbl at point."
4545 (let* ((case-fold-search t)
4546 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4547 (re2 (concat "^" orgtbl-line-start-regexp))
4548 (commented (save-excursion (beginning-of-line 1)
4549 (cond ((looking-at re1) t)
4550 ((looking-at re2) nil)
4551 (t (user-error "Not at an org table")))))
4552 (re (if commented re1 re2))
4555 (beginning-of-line 1)
4556 (while (looking-at re) (beginning-of-line 0))
4557 (beginning-of-line 2)
4559 (while (looking-at re) (beginning-of-line 2))
4561 (comment-region beg end (if commented '(4) nil))))
4563 (defun orgtbl-insert-radio-table ()
4564 "Insert a radio table template appropriate for this major mode."
4566 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4569 (unless e (user-error "No radio table setup defined for %s" major-mode))
4570 (setq name (read-string "Table name: "))
4571 (while (string-match "%n" txt)
4572 (setq txt (replace-match name t t txt)))
4573 (or (bolp) (insert "\n"))
4578 ;; Dynamically bound input and output for table formatting.
4579 (defvar *orgtbl-table* nil
4580 "Carries the current table through formatting routines.")
4581 (defvar *orgtbl-rtn* nil
4582 "Formatting routines push the output lines here.")
4583 ;; Formatting parameters for the current table section.
4584 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4585 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4586 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4587 (defvar *orgtbl-fmt* nil "Format for each entry.")
4588 (defvar *orgtbl-efmt* nil "Format for numbers.")
4589 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4590 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4591 (defvar *orgtbl-lstart* nil "Text starting a row.")
4592 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4593 (defvar *orgtbl-lend* nil "Text ending a row.")
4594 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4596 (defsubst orgtbl-get-fmt (fmt i)
4597 "Retrieve the format from FMT corresponding to the Ith column."
4598 (if (and (not (functionp fmt)) (consp fmt))
4602 (defsubst orgtbl-apply-fmt (fmt &rest args)
4603 "Apply format FMT to arguments ARGS.
4604 When FMT is nil, return the first argument from ARGS."
4605 (cond ((functionp fmt) (apply fmt args))
4606 (fmt (apply 'format fmt args))
4610 (defsubst orgtbl-eval-str (str)
4611 "If STR is a function, evaluate it with no arguments."
4616 (defun orgtbl-format-line (line)
4617 "Format LINE as a table row."
4618 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4624 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4625 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4626 (orgtbl-apply-fmt efmt (match-string 1 f)
4629 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4630 *orgtbl-default-fmt*)
4633 (push (if *orgtbl-lfmt*
4634 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4635 (concat (orgtbl-eval-str *orgtbl-lstart*)
4636 (mapconcat 'identity line *orgtbl-sep*)
4637 (orgtbl-eval-str *orgtbl-lend*)))
4640 (defun orgtbl-format-section (section-stopper)
4641 "Format lines until the first occurrence of SECTION-STOPPER."
4644 (while (not (eq (car *orgtbl-table*) section-stopper))
4645 (if prevline (orgtbl-format-line prevline))
4646 (setq prevline (pop *orgtbl-table*)))
4647 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4648 (*orgtbl-lend* *orgtbl-llend*)
4649 (*orgtbl-lfmt* *orgtbl-llfmt*))
4650 (orgtbl-format-line prevline))))))
4653 (defun orgtbl-to-generic (table params &optional backend)
4654 "Convert the orgtbl-mode TABLE to some other format.
4655 This generic routine can be used for many standard cases.
4656 TABLE is a list, each entry either the symbol `hline' for a horizontal
4657 separator line, or a list of fields for that line.
4658 PARAMS is a property list of parameters that can influence the conversion.
4659 A third optional argument BACKEND can be used to convert the content of
4660 the cells using a specific export back-end.
4662 For the generic converter, some parameters are obligatory: you need to
4663 specify either :lfmt, or all of (:lstart :lend :sep).
4665 Valid parameters are:
4667 :splice When set to t, return only table body lines, don't wrap
4668 them into :tstart and :tend. Default is nil. When :splice
4669 is non-nil, this also means that the exporter should not look
4670 for and interpret header and footer sections.
4672 :hline String to be inserted on horizontal separation lines.
4673 May be nil to ignore hlines.
4675 :sep Separator between two fields
4676 :remove-nil-lines Do not include lines that evaluate to nil.
4678 Each in the following group may be either a string or a function
4679 of no arguments returning a string:
4681 :tstart String to start the table. Ignored when :splice is t.
4682 :tend String to end the table. Ignored when :splice is t.
4683 :lstart String to start a new table line.
4684 :llstart String to start the last table line, defaults to :lstart.
4685 :lend String to end a table line
4686 :llend String to end the last table line, defaults to :lend.
4688 Each in the following group may be a string, a function of one
4689 argument (the field or line) returning a string, or a plist
4690 mapping columns to either of the above:
4692 :lfmt Format for entire line, with enough %s to capture all fields.
4693 If this is present, :lstart, :lend, and :sep are ignored.
4694 :llfmt Format for the entire last line, defaults to :lfmt.
4695 :fmt A format to be used to wrap the field, should contain
4696 %s for the original field value. For example, to wrap
4697 everything in dollars, you could use :fmt \"$%s$\".
4698 This may also be a property list with column numbers and
4699 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4700 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4701 Same as above, specific for the header lines in the table.
4702 All lines before the first hline are treated as header.
4703 If any of these is not present, the data line value is used.
4705 This may be either a string or a function of two arguments:
4707 :efmt Use this format to print numbers with exponentials.
4708 The format should have %s twice for inserting mantissa
4709 and exponent, for example \"%s\\\\times10^{%s}\". This
4710 may also be a property list with column numbers and
4711 formats. :fmt will still be applied after :efmt.
4713 In addition to this, the parameters :skip and :skipcols are always handled
4714 directly by `orgtbl-send-table'. See manual."
4715 (let* ((splicep (plist-get params :splice))
4716 (hline (plist-get params :hline))
4717 (skipheadrule (plist-get params :skipheadrule))
4718 (remove-nil-linesp (plist-get params :remove-nil-lines))
4719 (remove-newlines (plist-get params :remove-newlines))
4720 (*orgtbl-hline* hline)
4721 (*orgtbl-table* table)
4722 (*orgtbl-sep* (plist-get params :sep))
4723 (*orgtbl-efmt* (plist-get params :efmt))
4724 (*orgtbl-lstart* (plist-get params :lstart))
4725 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4726 (*orgtbl-lend* (plist-get params :lend))
4727 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4728 (*orgtbl-lfmt* (plist-get params :lfmt))
4729 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4730 (*orgtbl-fmt* (plist-get params :fmt))
4732 ;; Convert cells content to backend BACKEND
4734 (setq *orgtbl-table*
4740 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4746 (when (plist-member params :tstart)
4747 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4748 (if tstart (push tstart *orgtbl-rtn*)))))
4749 ;; If we have a heading, format it and handle the trailing hline.
4750 (if (and (not splicep)
4751 (or (consp (car *orgtbl-table*))
4752 (consp (nth 1 *orgtbl-table*)))
4753 (memq 'hline (cdr *orgtbl-table*)))
4755 (when (eq 'hline (car *orgtbl-table*))
4756 ;; There is a hline before the first data line
4757 (and hline (push hline *orgtbl-rtn*))
4758 (pop *orgtbl-table*))
4759 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4761 (*orgtbl-llstart* (or (plist-get params :hllstart)
4763 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4764 (*orgtbl-llend* (or (plist-get params :hllend)
4765 (plist-get params :hlend) *orgtbl-llend*))
4766 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4767 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4768 (plist-get params :hlfmt) *orgtbl-llfmt*))
4769 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4770 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4771 (orgtbl-format-section 'hline))
4772 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4773 (pop *orgtbl-table*)))
4774 ;; Now format the main section.
4775 (orgtbl-format-section nil)
4777 (when (plist-member params :tend)
4778 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4779 (if tend (push tend *orgtbl-rtn*)))))
4780 (mapconcat (if remove-newlines
4782 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4784 (nreverse (if remove-nil-linesp
4785 (remq nil *orgtbl-rtn*)
4786 *orgtbl-rtn*)) "\n")))
4789 (defun orgtbl-to-tsv (table params)
4790 "Convert the orgtbl-mode table to TAB separated material."
4791 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4793 (defun orgtbl-to-csv (table params)
4794 "Convert the orgtbl-mode table to CSV material.
4795 This does take care of the proper quoting of fields with comma or quotes."
4796 (orgtbl-to-generic table (org-combine-plists
4797 '(:sep "," :fmt org-quote-csv-field)
4801 (defun orgtbl-to-latex (table params)
4802 "Convert the orgtbl-mode TABLE to LaTeX.
4803 TABLE is a list, each entry either the symbol `hline' for a horizontal
4804 separator line, or a list of fields for that line.
4805 PARAMS is a property list of parameters that can influence the conversion.
4806 Supports all parameters from `orgtbl-to-generic'. Most important for
4809 :splice When set to t, return only table body lines, don't wrap
4810 them into a tabular environment. Default is nil.
4812 :fmt A format to be used to wrap the field, should contain %s for the
4813 original field value. For example, to wrap everything in dollars,
4814 use :fmt \"$%s$\". This may also be a property list with column
4815 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4816 The format may also be a function that formats its one argument.
4818 :efmt Format for transforming numbers with exponentials. The format
4819 should have %s twice for inserting mantissa and exponent, for
4820 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4821 This may also be a property list with column numbers and formats.
4822 The format may also be a function that formats its two arguments.
4824 :llend If you find too much space below the last line of a table,
4825 pass a value of \"\" for :llend to suppress the final \\\\.
4827 The general parameters :skip and :skipcols have already been applied when
4828 this function is called."
4829 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4830 org-table-last-alignment ""))
4833 :tstart (concat "\\begin{tabular}{" alignment "}")
4834 :tend "\\end{tabular}"
4835 :lstart "" :lend " \\\\" :sep " & "
4836 :efmt "%s\\,(%s)" :hline "\\hline")))
4838 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4841 (defun orgtbl-to-html (table params)
4842 "Convert the orgtbl-mode TABLE to HTML.
4843 TABLE is a list, each entry either the symbol `hline' for a horizontal
4844 separator line, or a list of fields for that line.
4845 PARAMS is a property list of parameters that can influence the conversion.
4846 Currently this function recognizes the following parameters:
4848 :splice When set to t, return only table body lines, don't wrap
4849 them into a <table> environment. Default is nil.
4851 The general parameters :skip and :skipcols have already been applied when
4852 this function is called. The function does *not* use `orgtbl-to-generic',
4853 so you cannot specify parameters for it."
4855 (let ((output (org-export-string-as
4856 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4857 (if (not (plist-get params :splice)) output
4859 (replace-regexp-in-string
4860 "\\`<table .*>\n" ""
4861 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4864 (defun orgtbl-to-texinfo (table params)
4865 "Convert the orgtbl-mode TABLE to TeXInfo.
4866 TABLE is a list, each entry either the symbol `hline' for a horizontal
4867 separator line, or a list of fields for that line.
4868 PARAMS is a property list of parameters that can influence the conversion.
4869 Supports all parameters from `orgtbl-to-generic'. Most important for
4872 :splice nil/t When set to t, return only table body lines, don't wrap
4873 them into a multitable environment. Default is nil.
4875 :fmt fmt A format to be used to wrap the field, should contain
4876 %s for the original field value. For example, to wrap
4877 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4878 This may also be a property list with column numbers and
4879 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4880 Each format also may be a function that formats its one
4883 :cf \"f1 f2..\" The column fractions for the table. By default these
4884 are computed automatically from the width of the columns
4887 The general parameters :skip and :skipcols have already been applied when
4888 this function is called."
4889 (let* ((total (float (apply '+ org-table-last-column-widths)))
4890 (colfrac (or (plist-get params :cf)
4892 (lambda (x) (format "%.3f" (/ (float x) total)))
4893 org-table-last-column-widths " ")))
4896 :tstart (concat "@multitable @columnfractions " colfrac)
4897 :tend "@end multitable"
4898 :lstart "@item " :lend "" :sep " @tab "
4899 :hlstart "@headitem ")))
4900 (require 'ox-texinfo)
4901 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4904 (defun orgtbl-to-orgtbl (table params)
4905 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4906 Useful when slicing one table into many. The :hline, :sep,
4907 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4908 and :tend suppress strings without splicing; they can be set to
4909 provide ORGTBL directives for the generated table."
4913 :tstart nil :tend nil
4918 (params (org-combine-plists params2 params)))
4920 (insert (orgtbl-to-generic table params))
4921 (goto-char (point-min))
4922 (while (re-search-forward org-table-hline-regexp nil t)
4924 (buffer-substring 1 (buffer-size)))))
4926 (defun orgtbl-to-table.el (table params)
4927 "Convert the orgtbl-mode TABLE into a table.el table."
4929 (insert (orgtbl-to-orgtbl table params))
4931 (replace-regexp-in-string
4933 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4935 (defun orgtbl-to-unicode (table params)
4936 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4937 You need the ascii-art-to-unicode.el package for this. You can download
4938 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4940 (insert (orgtbl-to-table.el table params))
4941 (goto-char (point-min))
4942 (if (or (featurep 'ascii-art-to-unicode)
4943 (require 'ascii-art-to-unicode nil t))
4945 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4946 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4947 "Link to ascii-art-to-unicode.el") org-stored-links))
4948 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4951 (defun org-table-get-remote-range (name-or-id form)
4952 "Get a field value or a list of values in a range from table at ID.
4954 NAME-OR-ID may be the name of a table in the current file as set
4955 by a \"#+NAME:\" directive. The first table following this line
4956 will then be used. Alternatively, it may be an ID referring to
4957 any entry, also in a different file. In this case, the first
4958 table in that entry will be referenced.
4959 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4960 \"@I$2..@II$2\". All the references must be absolute, not relative.
4962 The return value is either a single string for a single field, or a
4963 list of the fields in the rectangle."
4965 (let ((case-fold-search t) (id-loc nil)
4966 ;; Protect a bunch of variables from being overwritten
4967 ;; by the context of the remote table
4968 org-table-column-names org-table-column-name-regexp
4969 org-table-local-parameters org-table-named-field-locations
4970 org-table-current-line-types org-table-current-begin-line
4971 org-table-current-begin-pos org-table-dlines
4972 org-table-current-ncol
4973 org-table-hlines org-table-last-alignment
4974 org-table-last-column-widths org-table-last-alignment
4975 org-table-last-column-widths tbeg
4977 (setq form (org-table-convert-refs-to-rc form))
4982 (goto-char (point-min))
4983 (if (re-search-forward
4984 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
4985 (regexp-quote name-or-id) "[ \t]*$")
4987 (setq buffer (current-buffer) loc (match-beginning 0))
4988 (setq id-loc (org-id-find name-or-id 'marker))
4989 (unless (and id-loc (markerp id-loc))
4990 (user-error "Can't find remote table \"%s\"" name-or-id))
4991 (setq buffer (marker-buffer id-loc)
4992 loc (marker-position id-loc))
4993 (move-marker id-loc nil)))
4994 (with-current-buffer buffer
5000 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
5001 (not (match-beginning 1)))
5002 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5003 (setq tbeg (point-at-bol))
5004 (org-table-get-specials)
5005 (setq form (org-table-formula-substitute-names
5006 (org-table-formula-handle-first/last-rc form)))
5007 (if (and (string-match org-table-range-regexp form)
5008 (> (length (match-string 0 form)) 1))
5010 (org-table-get-range (match-string 0 form) tbeg 1))
5013 (defmacro org-define-lookup-function (mode)
5014 (let ((mode-str (symbol-name mode))
5015 (first-p (equal mode 'first))
5016 (all-p (equal mode 'all)))
5017 (let ((plural-str (if all-p "s" "")))
5018 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5019 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5020 If R-LIST is nil, return matching element%s of S-LIST.
5021 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5022 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5023 This function is generated by a call to the macro `org-define-lookup-function'."
5024 mode-str plural-str plural-str plural-str)
5025 (let ,(let ((lvars '((p (or predicate 'equal))
5027 (rl (or r-list s-list))
5029 (if first-p (add-to-list 'lvars '(match-p nil)))
5031 (while ,(if first-p '(and (not match-p) sl) 'sl)
5033 (if (funcall p val (car sl))
5035 ,(if first-p '(setq match-p t))
5036 (let ((rval (car rl)))
5037 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5038 (setq sl (cdr sl) rl (cdr rl))))
5041 (org-define-lookup-function first)
5042 (org-define-lookup-function last)
5043 (org-define-lookup-function all)
5045 (provide 'org-table)
5048 ;; generated-autoload-file: "org-loaddefs.el"
5051 ;;; org-table.el ends here