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 integer When a number, use that many spaces as field separator
551 nil When nil, the command tries to be smart and figure out the
552 separator in the following way:
553 - when each line contains a TAB, assume TAB-separated material
554 - when each line contains a comma, assume CSV material
555 - else, assume one or more SPACE characters as separator."
557 (let* ((beg (min beg0 end0
))
558 (end (max beg0 end0
))
561 (beginning-of-line 1)
562 (setq beg
(point-marker))
564 (if (bolp) (backward-char 1) (end-of-line 1))
565 (setq end
(point-marker))
566 ;; Get the right field separator
571 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
572 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
575 (if (equal separator
'(4))
576 (while (< (point) end
)
577 ;; parse the csv stuff
579 ((looking-at "^") (insert "| "))
580 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
581 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
582 (replace-match "\\1")
583 (if (looking-at "\"") (insert "\"")))
584 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
585 ((looking-at "[ \t]*,") (replace-match " | "))
586 (t (beginning-of-line 2))))
588 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
589 ((equal separator
'(16)) "^\\|\t")
590 ((integerp separator
)
592 (user-error "Number of spaces in separator must be >= 1")
593 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
594 (t (error "This should not happen"))))
595 (while (re-search-forward re end t
)
596 (replace-match "| " t t
)))
601 (defun org-table-import (file arg
)
602 "Import FILE as a table.
603 The file is assumed to be tab-separated. Such files can be produced by most
604 spreadsheet and database applications. If no tabs (at least one per line)
605 are found, lines will be split on whitespace into fields."
607 (or (bolp) (newline))
610 (insert-file-contents file
)
611 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
614 (defvar org-table-last-alignment
)
615 (defvar org-table-last-column-widths
)
617 (defun org-table-export (&optional file format
)
618 "Export table to a file, with configurable format.
619 Such a file can be imported into usual spreadsheet programs.
621 FILE can be the output file name. If not given, it will be taken
622 from a TABLE_EXPORT_FILE property in the current entry or higher
623 up in the hierarchy, or the user will be prompted for a file
624 name. FORMAT can be an export format, of the same kind as it
625 used when `orgtbl-mode' sends a table in a different format.
627 The command suggests a format depending on TABLE_EXPORT_FORMAT,
628 whether it is set locally or up in the hierarchy, then on the
629 extension of the given file name, and finally on the variable
630 `org-table-export-default-format'."
632 (unless (org-at-table-p) (user-error "No table at point"))
633 (org-table-align) ;; make sure we have everything we need
634 (let* ((beg (org-table-begin))
635 (end (org-table-end))
636 (txt (buffer-substring-no-properties beg end
))
637 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
638 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
639 "orgtbl-to-latex" "orgtbl-to-html"
640 "orgtbl-to-generic" "orgtbl-to-texinfo"
643 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
644 buf deffmt-readable fileext
)
646 (setq file
(read-file-name "Export table to: "))
647 (unless (or (not (file-exists-p file
))
648 (y-or-n-p (format "Overwrite file %s? " file
)))
649 (user-error "File not written")))
650 (if (file-directory-p file
)
651 (user-error "This is a directory path, not a file"))
652 (if (and (buffer-file-name)
653 (equal (file-truename file
)
654 (file-truename (buffer-file-name))))
655 (user-error "Please specify a file name that is different from current"))
656 (setq fileext
(concat (file-name-extension file
) "$"))
658 (setq deffmt-readable
659 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
660 org-table-export-default-format
))
661 (while (string-match "\t" deffmt-readable
)
662 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
663 (while (string-match "\n" deffmt-readable
)
664 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
665 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
666 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
667 (let* ((transform (intern (match-string 1 format
)))
668 (params (if (match-end 2)
669 (read (concat "(" (match-string 2 format
) ")"))))
670 (skip (plist-get params
:skip
))
671 (skipcols (plist-get params
:skipcols
))
672 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
673 (lines (org-table-clean-before-export lines
))
674 (i0 (if org-table-clean-did-remove-column
2 1))
677 (if (string-match org-table-hline-regexp x
)
680 (org-split-string (org-trim x
) "\\s-*|\\s-*")
683 (fun (if (= i0
2) 'cdr
'identity
))
684 (org-table-last-alignment
685 (org-remove-by-index (funcall fun org-table-last-alignment
)
687 (org-table-last-column-widths
688 (org-remove-by-index (funcall fun org-table-last-column-widths
)
691 (unless (fboundp transform
)
692 (user-error "No such transformation function %s" transform
))
693 (setq txt
(funcall transform table params
))
695 (with-current-buffer (find-file-noselect file
)
696 (setq buf
(current-buffer))
702 (message "Export done."))
703 (user-error "TABLE_EXPORT_FORMAT invalid"))))
705 (defvar org-table-aligned-begin-marker
(make-marker)
706 "Marker at the beginning of the table last aligned.
707 Used to check if cursor still is in that table, to minimize realignment.")
708 (defvar org-table-aligned-end-marker
(make-marker)
709 "Marker at the end of the table last aligned.
710 Used to check if cursor still is in that table, to minimize realignment.")
711 (defvar org-table-last-alignment nil
712 "List of flags for flushright alignment, from the last re-alignment.
713 This is being used to correctly align a single field after TAB or RET.")
714 (defvar org-table-last-column-widths nil
715 "List of max width of fields in each column.
716 This is being used to correctly align a single field after TAB or RET.")
717 (defvar org-table-formula-debug nil
718 "Non-nil means debug table formulas.
719 When nil, simply write \"#ERROR\" in corrupted fields.")
720 (make-variable-buffer-local 'org-table-formula-debug
)
721 (defvar org-table-overlay-coordinates nil
722 "Overlay coordinates after each align of a table.")
723 (make-variable-buffer-local 'org-table-overlay-coordinates
)
725 (defvar org-last-recalc-line nil
)
726 (defvar org-table-do-narrow t
) ; for dynamic scoping
727 (defconst org-narrow-column-arrow
"=>"
728 "Used as display property in narrowed table columns.")
731 (defun org-table-align ()
732 "Align the table at point by aligning all vertical bars."
736 (beg (org-table-begin))
737 (end (org-table-end))
738 ;; Current cursor position
739 (linepos (org-current-line))
740 (colpos (org-table-current-column))
741 (winstart (window-start))
742 (winstartline (org-current-line (min winstart
(1- (point-max)))))
743 lines
(new "") lengths l typenums ty fields maxfields i
751 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
753 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
754 emptystrings links dates emph raise narrow
755 falign falign1 fmax f1 len c e space
)
757 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
758 ;; Check if we have links or dates
760 (setq links
(re-search-forward org-bracket-link-regexp end t
))
762 (setq emph
(and org-hide-emphasis-markers
763 (re-search-forward org-emph-re end t
)))
765 (setq raise
(and org-use-sub-superscripts
766 (re-search-forward org-match-substring-regexp end t
)))
768 (setq dates
(and org-display-custom-times
769 (re-search-forward org-ts-regexp-both end t
)))
770 ;; Make sure the link properties are right
771 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
772 ;; Make sure the date properties are right
773 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
774 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
775 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
777 ;; Check if we are narrowing any columns
779 (setq narrow
(and org-table-do-narrow
780 org-format-transports-properties-p
781 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
783 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
786 (setq lines
(org-split-string
787 (buffer-substring beg end
) "\n"))
788 ;; Store the indentation of the first line
789 (if (string-match "^ *" (car lines
))
790 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
791 ;; Mark the hlines by setting the corresponding element to nil
792 ;; At the same time, we remove trailing space.
793 (setq lines
(mapcar (lambda (l)
794 (if (string-match "^ *|-" l
)
796 (if (string-match "[ \t]+$" l
)
797 (substring l
0 (match-beginning 0))
800 ;; Get the data fields by splitting the lines.
803 (org-split-string l
" *| *"))
804 (delq nil
(copy-sequence lines
))))
805 ;; How many fields in the longest line?
807 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
809 (kill-region beg end
)
810 (org-table-create org-table-default-size
)
811 (user-error "Empty table - created default table")))
812 ;; A list of empty strings to fill any short rows on output
813 (setq emptystrings
(make-list maxfields
""))
814 ;; Check for special formatting.
816 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
817 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
818 ;; Check if there is an explicit width specified
820 (when (or narrow falign
)
821 (setq c column fmax nil falign1 nil
)
824 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
825 (if (match-end 1) (setq falign1
(match-string 1 e
)))
826 (if (and org-table-do-narrow
(match-end 2))
827 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
828 ;; Find fields that are wider than fmax, and shorten them
830 (loop for xx in column do
831 (when (and (stringp xx
)
832 (> (org-string-width xx
) fmax
))
833 (org-add-props xx nil
835 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
836 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
838 (user-error "Cannot narrow field starting with wide link \"%s\""
839 (match-string 0 xx
)))
840 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
841 (add-text-properties (- f1
2) f1
842 (list 'display org-narrow-column-arrow
)
844 ;; Get the maximum width for each column
845 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
847 ;; Get the fraction of numbers, to decide about alignment of the column
849 (push (equal (downcase falign1
) "r") typenums
)
850 (setq cnt
0 frac
0.0)
851 (loop for x in column do
854 (setq frac
( / (+ (* frac cnt
)
855 (if (string-match org-table-number-regexp x
) 1 0))
856 (setq cnt
(1+ cnt
))))))
857 (push (>= frac org-table-number-fraction
) typenums
)))
858 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
860 ;; Store the alignment of this table, for later editing of single fields
861 (setq org-table-last-alignment typenums
862 org-table-last-column-widths lengths
)
864 ;; With invisible characters, `format' does not get the field width right
865 ;; So we need to make these fields wide by hand.
866 (when (or links emph raise
)
867 (loop for i from
0 upto
(1- maxfields
) do
868 (setq len
(nth i lengths
))
869 (loop for j from
0 upto
(1- (length fields
)) do
870 (setq c
(nthcdr i
(car (nthcdr j fields
))))
871 (if (and (stringp (car c
))
872 (or (text-property-any 0 (length (car c
))
873 'invisible
'org-link
(car c
))
874 (text-property-any 0 (length (car c
))
875 'org-dwidth t
(car c
)))
876 (< (org-string-width (car c
)) len
))
878 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
879 (setcar c
(if (nth i typenums
)
880 (concat space
(car c
))
881 (concat (car c
) space
))))))))
883 ;; Compute the formats needed for output of the table
884 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
885 (while (setq l
(pop lengths
))
886 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
887 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
888 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
889 (setq rfmt
(concat rfmt
"\n")
890 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
894 (if l
(apply 'format rfmt
895 (append (pop fields
) emptystrings
))
898 (move-marker org-table-aligned-begin-marker
(point))
900 ;; Replace the old one
901 (delete-region (point) end
)
902 (move-marker end nil
)
903 (move-marker org-table-aligned-end-marker
(point))
904 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
905 (goto-char org-table-aligned-begin-marker
)
906 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
907 ;; Try to move to the old location
908 (org-goto-line winstartline
)
909 (setq winstart
(point-at-bol))
910 (org-goto-line linepos
)
911 (when (eq (window-buffer (selected-window)) (current-buffer))
912 (set-window-start (selected-window) winstart
'noforce
))
913 (org-table-goto-column colpos
)
914 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
915 (setq org-table-may-need-update nil
)
919 (defun org-table-begin (&optional table-type
)
920 "Find the beginning of the table and return its position.
921 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
923 (if (not (re-search-backward
924 (if table-type org-table-any-border-regexp
925 org-table-border-regexp
)
927 (progn (goto-char (point-min)) (point))
928 (goto-char (match-beginning 0))
929 (beginning-of-line 2)
933 (defun org-table-end (&optional table-type
)
934 "Find the end of the table and return its position.
935 With argument TABLE-TYPE, go to the end of a table.el-type table."
937 (if (not (re-search-forward
938 (if table-type org-table-any-border-regexp
939 org-table-border-regexp
)
941 (goto-char (point-max))
942 (goto-char (match-beginning 0)))
946 (defun org-table-justify-field-maybe (&optional new
)
947 "Justify the current field, text to left, number to right.
948 Optional argument NEW may specify text to replace the current field content."
950 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
951 ((org-at-table-hline-p))
953 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
955 (< (point) org-table-aligned-begin-marker
)
956 (>= (point) org-table-aligned-end-marker
)))
957 ;; This is not the same table, force a full re-align
958 (setq org-table-may-need-update t
))
959 (t ;; realign the current field, based on previous full realign
960 (let* ((pos (point)) s
961 (col (org-table-current-column))
962 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
965 (skip-chars-backward "^|\n")
966 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
968 (setq s
(match-string 1)
970 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
971 e
(not (= (match-beginning 2) (match-end 2))))
972 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
973 l
(if e
"|" (setq org-table-may-need-update t
) ""))
976 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
977 (setq n
(format f new
))
978 (setq n
(concat new
"|") org-table-may-need-update t
)))
979 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
981 (let (org-table-may-need-update)
982 (replace-match n t t
))))
983 (setq org-table-may-need-update t
))
987 (defun org-table-next-field ()
988 "Go to the next field in the current table, creating new lines as needed.
989 Before doing so, re-align the table if necessary."
991 (org-table-maybe-eval-formula)
992 (org-table-maybe-recalculate-line)
993 (if (and org-table-automatic-realign
994 org-table-may-need-update
)
996 (let ((end (org-table-end)))
997 (if (org-at-table-hline-p)
1001 (re-search-forward "|" end
)
1002 (if (looking-at "[ \t]*$")
1003 (re-search-forward "|" end
))
1004 (if (and (looking-at "-")
1005 org-table-tab-jumps-over-hlines
1006 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1007 (goto-char (match-beginning 1)))
1008 (if (looking-at "-")
1010 (beginning-of-line 0)
1011 (org-table-insert-row 'below
))
1012 (if (looking-at " ") (forward-char 1))))
1014 (org-table-insert-row 'below
)))))
1017 (defun org-table-previous-field ()
1018 "Go to the previous field in the table.
1019 Before doing so, re-align the table if necessary."
1021 (org-table-justify-field-maybe)
1022 (org-table-maybe-recalculate-line)
1023 (if (and org-table-automatic-realign
1024 org-table-may-need-update
)
1026 (if (org-at-table-hline-p)
1030 (re-search-backward "|" (org-table-begin))
1031 (re-search-backward "|" (org-table-begin)))
1032 (error (user-error "Cannot move to previous table field")))
1033 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1034 (re-search-backward "|" (org-table-begin)))
1035 (if (looking-at "| ?")
1036 (goto-char (match-end 0))))
1038 (defun org-table-beginning-of-field (&optional n
)
1039 "Move to the end of the current table field.
1040 If already at or after the end, move to the end of the next table field.
1041 With numeric argument N, move N-1 fields forward first."
1043 (let ((pos (point)))
1046 (org-table-previous-field))
1047 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1048 (user-error "No more table fields before the current")
1049 (goto-char (match-end 0))
1050 (and (looking-at " ") (forward-char 1)))
1051 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1053 (defun org-table-end-of-field (&optional n
)
1054 "Move to the beginning of the current table field.
1055 If already at or before the beginning, move to the beginning of the
1057 With numeric argument N, move N-1 fields backward first."
1059 (let ((pos (point)))
1062 (org-table-next-field))
1063 (when (re-search-forward "|" (point-at-eol 1) t
)
1065 (skip-chars-backward " ")
1066 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1068 (if (<= (point) pos
) (org-table-end-of-field 2))))
1071 (defun org-table-next-row ()
1072 "Go to the next row (same column) in the current table.
1073 Before doing so, re-align the table if necessary."
1075 (org-table-maybe-eval-formula)
1076 (org-table-maybe-recalculate-line)
1077 (if (or (looking-at "[ \t]*$")
1078 (save-excursion (skip-chars-backward " \t") (bolp)))
1080 (if (and org-table-automatic-realign
1081 org-table-may-need-update
)
1083 (let ((col (org-table-current-column)))
1084 (beginning-of-line 2)
1085 (if (or (not (org-at-table-p))
1086 (org-at-table-hline-p))
1088 (beginning-of-line 0)
1089 (org-table-insert-row 'below
)))
1090 (org-table-goto-column col
)
1091 (skip-chars-backward "^|\n\r")
1092 (if (looking-at " ") (forward-char 1)))))
1095 (defun org-table-copy-down (n)
1096 "Copy a field down in the current column.
1097 If the field at the cursor is empty, copy into it the content of
1098 the nearest non-empty field above. With argument N, use the Nth
1099 non-empty field. If the current field is not empty, it is copied
1100 down to the next row, and the cursor is moved with it.
1101 Therefore, repeating this command causes the column to be filled
1103 If the variable `org-table-copy-increment' is non-nil and the
1104 field is an integer or a timestamp, it will be incremented while
1105 copying. In the case of a timestamp, increment by one day."
1107 (let* ((colpos (org-table-current-column))
1108 (col (current-column))
1109 (field (save-excursion (org-table-get-field)))
1110 (non-empty (string-match "[^ \t]" field
))
1111 (beg (org-table-begin))
1114 (org-table-check-inside-data-field)
1117 (setq txt
(org-trim field
))
1118 (org-table-next-row)
1119 (org-table-blank-field))
1123 (while (progn (beginning-of-line 1)
1124 (re-search-backward org-table-dataline-regexp
1126 (org-table-goto-column colpos t
)
1127 (if (and (looking-at
1128 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1129 (<= (setq n
(1- n
)) 0))
1130 (throw 'exit
(match-string 1))))))))
1133 (if (and org-table-copy-increment
1134 (not (equal orig-n
0))
1135 (string-match "^[0-9]+$" txt
)
1136 (< (string-to-number txt
) 100000000))
1137 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1139 (org-move-to-column col
)
1140 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1141 (org-timestamp-up-day)
1142 (org-table-maybe-recalculate-line))
1144 (org-move-to-column col
))
1145 (user-error "No non-empty field found"))))
1147 (defun org-table-check-inside-data-field (&optional noerror
)
1148 "Is point inside a table data field?
1149 I.e. not on a hline or before the first or after the last column?
1150 This actually throws an error, so it aborts the current command."
1151 (if (or (not (org-at-table-p))
1152 (= (org-table-current-column) 0)
1153 (org-at-table-hline-p)
1154 (looking-at "[ \t]*$"))
1157 (user-error "Not in table data field"))
1160 (defvar org-table-clip nil
1161 "Clipboard for table regions.")
1163 (defun org-table-get (line column
)
1164 "Get the field in table line LINE, column COLUMN.
1165 If LINE is larger than the number of data lines in the table, the function
1166 returns nil. However, if COLUMN is too large, we will simply return an
1168 If LINE is nil, use the current line.
1169 If column is nil, use the current column."
1170 (setq column
(or column
(org-table-current-column)))
1172 (and (or (not line
) (org-table-goto-line line
))
1173 (org-trim (org-table-get-field column
)))))
1175 (defun org-table-put (line column value
&optional align
)
1176 "Put VALUE into line LINE, column COLUMN.
1177 When ALIGN is set, also realign the table."
1178 (setq column
(or column
(org-table-current-column)))
1179 (prog1 (save-excursion
1180 (and (or (not line
) (org-table-goto-line line
))
1181 (progn (org-table-goto-column column nil
'force
) t
)
1182 (org-table-get-field column value
)))
1183 (and align
(org-table-align))))
1185 (defun org-table-current-line ()
1186 "Return the index of the current data line."
1187 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1189 (goto-char (org-table-begin))
1190 (while (and (re-search-forward org-table-dataline-regexp end t
)
1192 (< (point-at-eol) pos
))))
1195 (defun org-table-goto-line (N)
1196 "Go to the Nth data line in the current table.
1197 Return t when the line exists, nil if it does not exist."
1198 (goto-char (org-table-begin))
1199 (let ((end (org-table-end)) (cnt 0))
1200 (while (and (re-search-forward org-table-dataline-regexp end t
)
1201 (< (setq cnt
(1+ cnt
)) N
)))
1205 (defun org-table-blank-field ()
1206 "Blank the current table field or active region."
1208 (org-table-check-inside-data-field)
1209 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1210 (let (org-table-clip)
1211 (org-table-cut-region (region-beginning) (region-end)))
1212 (skip-chars-backward "^|")
1214 (if (looking-at "|[^|\n]+")
1215 (let* ((pos (match-beginning 0))
1216 (match (match-string 0))
1217 (len (org-string-width match
)))
1218 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1219 (goto-char (+ 2 pos
))
1220 (substring match
1)))))
1222 (defun org-table-get-field (&optional n replace
)
1223 "Return the value of the field in column N of current row.
1224 N defaults to current field.
1225 If REPLACE is a string, replace field with this value. The return value
1226 is always the old value."
1227 (and n
(org-table-goto-column n
))
1228 (skip-chars-backward "^|\n")
1230 (if (looking-at "|[^|\r\n]*")
1231 (let* ((pos (match-beginning 0))
1232 (val (buffer-substring (1+ pos
) (match-end 0))))
1234 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1236 (goto-char (min (point-at-eol) (+ 2 pos
)))
1238 (forward-char 1) ""))
1241 (defun org-table-field-info (arg)
1242 "Show info about the current field, and highlight any reference at point."
1244 (org-table-get-specials)
1246 (let* ((pos (point))
1247 (col (org-table-current-column))
1248 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1249 (name (car (rassoc (list (org-current-line) col
)
1250 org-table-named-field-locations
)))
1251 (eql (org-table-expand-lhs-ranges
1254 (cons (org-table-formula-handle-first/last-rc
1256 (org-table-get-stored-formulas))))
1257 (dline (org-table-current-dline))
1258 (ref (format "@%d$%d" dline col
))
1259 (ref1 (org-table-convert-refs-to-an ref
))
1260 (fequation (or (assoc name eql
) (assoc ref eql
)))
1261 (cequation (assoc (int-to-string col
) eql
))
1262 (eqn (or fequation cequation
)))
1263 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1264 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1267 (org-table-show-reference 'local
)
1269 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1271 (if cname
(concat " or $" cname
) "")
1273 (if name
(concat " or $" name
) "")
1274 ;; FIXME: formula info not correct if special table line
1276 (concat ", formula: "
1277 (org-table-formula-to-user
1279 (if (string-match "^[$@]"(car eqn
)) "" "$")
1280 (car eqn
) "=" (cdr eqn
))))
1283 (defun org-table-current-column ()
1284 "Find out which column we are in."
1286 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1288 (let ((cnt 0) (pos (point)))
1289 (beginning-of-line 1)
1290 (while (search-forward "|" pos t
)
1291 (setq cnt
(1+ cnt
)))
1292 (when (org-called-interactively-p 'interactive
)
1293 (message "In table column %d" cnt
))
1297 (defun org-table-current-dline ()
1298 "Find out what table data line we are in.
1299 Only data lines count for this."
1301 (when (org-called-interactively-p 'any
)
1302 (org-table-check-inside-data-field))
1304 (let ((cnt 0) (pos (point)))
1305 (goto-char (org-table-begin))
1306 (while (<= (point) pos
)
1307 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1308 (beginning-of-line 2))
1309 (when (org-called-interactively-p 'any
)
1310 (message "This is table line %d" cnt
))
1314 (defun org-table-goto-column (n &optional on-delim force
)
1315 "Move the cursor to the Nth column in the current table line.
1316 With optional argument ON-DELIM, stop with point before the left delimiter
1318 If there are less than N fields, just go to after the last delimiter.
1319 However, when FORCE is non-nil, create new columns if necessary."
1321 (beginning-of-line 1)
1323 (while (and (> (setq n
(1- n
)) -
1)
1324 (or (search-forward "|" (point-at-eol) t
)
1326 (progn (end-of-line 1)
1327 (skip-chars-backward "^|")
1330 (when (and force
(not (looking-at ".*|")))
1331 (save-excursion (end-of-line 1) (insert " | ")))
1334 (if (looking-at " ") (forward-char 1)))))
1337 (defun org-table-insert-column ()
1338 "Insert a new column into the table."
1340 (if (not (org-at-table-p))
1341 (user-error "Not at a table"))
1342 (org-table-find-dataline)
1343 (let* ((col (max 1 (org-table-current-column)))
1344 (beg (org-table-begin))
1345 (end (org-table-end))
1346 ;; Current cursor position
1347 (linepos (org-current-line))
1350 (while (< (point) end
)
1351 (if (org-at-table-hline-p)
1353 (org-table-goto-column col t
)
1355 (beginning-of-line 2))
1356 (move-marker end nil
)
1357 (org-goto-line linepos
)
1358 (org-table-goto-column colpos
)
1360 (when (or (not org-table-fix-formulas-confirm
)
1361 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1362 (org-table-fix-formulas "$" nil
(1- col
) 1)
1363 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1365 (defun org-table-find-dataline ()
1366 "Find a data line in the current table, which is needed for column commands."
1367 (if (and (org-at-table-p)
1368 (not (org-at-table-hline-p)))
1370 (let ((col (current-column))
1371 (end (org-table-end)))
1372 (org-move-to-column col
)
1373 (while (and (< (point) end
)
1374 (or (not (= (current-column) col
))
1375 (org-at-table-hline-p)))
1376 (beginning-of-line 2)
1377 (org-move-to-column col
))
1378 (if (and (org-at-table-p)
1379 (not (org-at-table-hline-p)))
1382 "Please position cursor in a data line for column operations")))))
1384 (defun org-table-line-to-dline (line &optional above
)
1385 "Turn a buffer line number into a data line number.
1386 If there is no data line in this line, return nil.
1387 If there is no matching dline (most likely te reference was a hline), the
1388 first dline below it is used. When ABOVE is non-nil, the one above is used."
1390 (let ((ll (length org-table-dlines
))
1396 (if (<= (aref org-table-dlines i
) line
)
1401 (if (>= (aref org-table-dlines i
) line
)
1407 (defun org-table-delete-column ()
1408 "Delete a column from the table."
1410 (if (not (org-at-table-p))
1411 (user-error "Not at a table"))
1412 (org-table-find-dataline)
1413 (org-table-check-inside-data-field)
1414 (let* ((col (org-table-current-column))
1415 (beg (org-table-begin))
1416 (end (org-table-end))
1417 ;; Current cursor position
1418 (linepos (org-current-line))
1421 (while (< (point) end
)
1422 (if (org-at-table-hline-p)
1424 (org-table-goto-column col t
)
1425 (and (looking-at "|[^|\n]+|")
1426 (replace-match "|")))
1427 (beginning-of-line 2))
1428 (move-marker end nil
)
1429 (org-goto-line linepos
)
1430 (org-table-goto-column colpos
)
1432 (when (or (not org-table-fix-formulas-confirm
)
1433 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1434 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1436 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1440 (defun org-table-move-column-right ()
1441 "Move column to the right."
1443 (org-table-move-column nil
))
1445 (defun org-table-move-column-left ()
1446 "Move column to the left."
1448 (org-table-move-column 'left
))
1451 (defun org-table-move-column (&optional left
)
1452 "Move the current column to the right. With arg LEFT, move to the left."
1454 (if (not (org-at-table-p))
1455 (user-error "Not at a table"))
1456 (org-table-find-dataline)
1457 (org-table-check-inside-data-field)
1458 (let* ((col (org-table-current-column))
1459 (col1 (if left
(1- col
) col
))
1460 (beg (org-table-begin))
1461 (end (org-table-end))
1462 ;; Current cursor position
1463 (linepos (org-current-line))
1464 (colpos (if left
(1- col
) (1+ col
))))
1465 (if (and left
(= col
1))
1466 (user-error "Cannot move column further left"))
1467 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1468 (user-error "Cannot move column further right"))
1470 (while (< (point) end
)
1471 (if (org-at-table-hline-p)
1473 (org-table-goto-column col1 t
)
1474 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1475 (replace-match "|\\2|\\1|")))
1476 (beginning-of-line 2))
1477 (move-marker end nil
)
1478 (org-goto-line linepos
)
1479 (org-table-goto-column colpos
)
1481 (when (or (not org-table-fix-formulas-confirm
)
1482 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1483 (org-table-fix-formulas
1484 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1485 (cons (number-to-string colpos
) (number-to-string col
))))
1486 (org-table-fix-formulas
1487 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1488 (cons (number-to-string colpos
) (number-to-string col
)))))))
1491 (defun org-table-move-row-down ()
1492 "Move table row down."
1494 (org-table-move-row nil
))
1496 (defun org-table-move-row-up ()
1497 "Move table row up."
1499 (org-table-move-row 'up
))
1502 (defun org-table-move-row (&optional up
)
1503 "Move the current table line down. With arg UP, move it up."
1505 (let* ((col (current-column))
1507 (hline1p (save-excursion (beginning-of-line 1)
1508 (looking-at org-table-hline-regexp
)))
1509 (dline1 (org-table-current-dline))
1510 (dline2 (+ dline1
(if up -
1 1)))
1513 (beginning-of-line tonew
)
1514 (unless (org-at-table-p)
1516 (user-error "Cannot move row further"))
1517 (setq hline2p
(looking-at org-table-hline-regexp
))
1519 (beginning-of-line 1)
1521 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1522 (delete-region (point) (1+ (point-at-eol)))
1523 (beginning-of-line tonew
)
1525 (beginning-of-line 0)
1526 (org-move-to-column col
)
1527 (unless (or hline1p hline2p
1528 (not (or (not org-table-fix-formulas-confirm
)
1529 (funcall org-table-fix-formulas-confirm
1530 "Fix formulas? "))))
1531 (org-table-fix-formulas
1532 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1533 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1536 (defun org-table-insert-row (&optional arg
)
1537 "Insert a new row above the current line into the table.
1538 With prefix ARG, insert below the current line."
1540 (if (not (org-at-table-p))
1541 (user-error "Not at a table"))
1542 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1543 (new (org-table-clean-line line
)))
1544 ;; Fix the first field if necessary
1545 (if (string-match "^[ \t]*| *[#$] *|" line
)
1546 (setq new
(replace-match (match-string 0 line
) t t new
)))
1547 (beginning-of-line (if arg
2 1))
1548 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1549 (beginning-of-line 0)
1550 (re-search-forward "| ?" (point-at-eol) t
)
1551 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1553 (when (or (not org-table-fix-formulas-confirm
)
1554 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1555 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1558 (defun org-table-insert-hline (&optional above
)
1559 "Insert a horizontal-line below the current line into the table.
1560 With prefix ABOVE, insert above the current line."
1562 (if (not (org-at-table-p))
1563 (user-error "Not at a table"))
1564 (when (eobp) (insert "\n") (backward-char 1))
1565 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1567 (let ((line (org-table-clean-line
1568 (buffer-substring (point-at-bol) (point-at-eol))))
1569 (col (current-column)))
1570 (while (string-match "|\\( +\\)|" line
)
1571 (setq line
(replace-match
1572 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1573 ?-
) "|") t t line
)))
1574 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1575 (beginning-of-line (if above
1 2))
1577 (beginning-of-line (if above
1 -
1))
1578 (org-move-to-column col
)
1579 (and org-table-overlay-coordinates
(org-table-align))))
1582 (defun org-table-hline-and-move (&optional same-column
)
1583 "Insert a hline and move to the row below that line."
1585 (let ((col (org-table-current-column)))
1586 (org-table-maybe-eval-formula)
1587 (org-table-maybe-recalculate-line)
1588 (org-table-insert-hline)
1590 (if (looking-at "\n[ \t]*|-")
1591 (progn (insert "\n|") (org-table-align))
1592 (org-table-next-field))
1593 (if same-column
(org-table-goto-column col
))))
1595 (defun org-table-clean-line (s)
1596 "Convert a table line S into a string with only \"|\" and space.
1597 In particular, this does handle wide and invisible characters."
1598 (if (string-match "^[ \t]*|-" s
)
1599 ;; It's a hline, just map the characters
1600 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1601 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1602 (setq s
(replace-match
1603 (concat "|" (make-string (org-string-width (match-string 1 s
))
1609 (defun org-table-kill-row ()
1610 "Delete the current row or horizontal line from the table."
1612 (if (not (org-at-table-p))
1613 (user-error "Not at a table"))
1614 (let ((col (current-column))
1615 (dline (org-table-current-dline)))
1616 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1617 (if (not (org-at-table-p)) (beginning-of-line 0))
1618 (org-move-to-column col
)
1619 (when (or (not org-table-fix-formulas-confirm
)
1620 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1621 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1625 (defun org-table-sort-lines (with-case &optional sorting-type
)
1626 "Sort table lines according to the column at point.
1628 The position of point indicates the column to be used for
1629 sorting, and the range of lines is the range between the nearest
1630 horizontal separator lines, or the entire table of no such lines
1631 exist. If point is before the first column, you will be prompted
1632 for the sorting column. If there is an active region, the mark
1633 specifies the first line and the sorting column, while point
1634 should be in the last line to be included into the sorting.
1636 The command then prompts for the sorting type which can be
1637 alphabetically, numerically, or by time (as given in a time stamp
1638 in the field). Sorting in reverse order is also possible.
1640 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1642 If SORTING-TYPE is specified when this function is called from a Lisp
1643 program, no prompting will take place. SORTING-TYPE must be a character,
1644 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1645 should be done in reverse order."
1647 (let* ((thisline (org-current-line))
1648 (thiscol (org-table-current-column))
1649 (otc org-table-overlay-coordinates
)
1650 beg end bcol ecol tend tbeg column lns pos
)
1651 (when (equal thiscol
0)
1652 (if (org-called-interactively-p 'any
)
1655 (read-string "Use column N for sorting: ")))
1657 (org-table-goto-column thiscol
))
1658 (org-table-check-inside-data-field)
1659 (if (org-region-active-p)
1661 (setq beg
(region-beginning) end
(region-end))
1663 (setq column
(org-table-current-column)
1666 (setq end
(point-at-bol 2)))
1667 (setq column
(org-table-current-column)
1669 tbeg
(org-table-begin)
1670 tend
(org-table-end))
1671 (if (re-search-backward org-table-hline-regexp tbeg t
)
1672 (setq beg
(point-at-bol 2))
1674 (setq beg
(point-at-bol 1)))
1676 (if (re-search-forward org-table-hline-regexp tend t
)
1677 (setq end
(point-at-bol 1))
1679 (setq end
(point-at-bol))))
1680 (setq beg
(move-marker (make-marker) beg
)
1681 end
(move-marker (make-marker) end
))
1684 (org-table-goto-column column
)
1685 (skip-chars-backward "^|")
1686 (setq bcol
(current-column))
1687 (org-table-goto-column (1+ column
))
1688 (skip-chars-backward "^|")
1689 (setq ecol
(1- (current-column)))
1690 (org-table-goto-column column
)
1691 (setq lns
(mapcar (lambda(x) (cons
1692 (org-sort-remove-invisible
1694 (org-split-string x
"[ \t]*|[ \t]*")))
1696 (org-split-string (buffer-substring beg end
) "\n")))
1697 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1698 (when org-table-overlay-coordinates
1699 (org-table-toggle-coordinate-overlays))
1700 (delete-region beg end
)
1701 (move-marker beg nil
)
1702 (move-marker end nil
)
1703 (insert (mapconcat 'cdr lns
"\n") "\n")
1704 (org-goto-line thisline
)
1705 (org-table-goto-column thiscol
)
1706 (when otc
(org-table-toggle-coordinate-overlays))
1707 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1710 (defun org-table-cut-region (beg end
)
1711 "Copy region in table to the clipboard and blank all relevant fields.
1712 If there is no active region, use just the field at point."
1714 (if (org-region-active-p) (region-beginning) (point))
1715 (if (org-region-active-p) (region-end) (point))))
1716 (org-table-copy-region beg end
'cut
))
1719 (defun org-table-copy-region (beg end
&optional cut
)
1720 "Copy rectangular region in table to clipboard.
1721 A special clipboard is used which can only be accessed
1722 with `org-table-paste-rectangle'."
1724 (if (org-region-active-p) (region-beginning) (point))
1725 (if (org-region-active-p) (region-end) (point))
1726 current-prefix-arg
))
1727 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1729 (rpl (if cut
" " nil
)))
1731 (org-table-check-inside-data-field)
1732 (setq l01
(org-current-line)
1733 c01
(org-table-current-column))
1735 (org-table-check-inside-data-field)
1736 (setq l02
(org-current-line)
1737 c02
(org-table-current-column))
1738 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1739 c1
(min c01 c02
) c2
(max c01 c02
))
1743 (if (> l1 l2
) (throw 'exit t
))
1745 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1746 (setq cols nil ic1 c1 ic2 c2
)
1747 (while (< ic1
(1+ ic2
))
1748 (push (org-table-get-field ic1 rpl
) cols
)
1749 (setq ic1
(1+ ic1
)))
1750 (push (nreverse cols
) region
)
1751 (setq l1
(1+ l1
)))))
1752 (setq org-table-clip
(nreverse region
))
1753 (if cut
(org-table-align))
1757 (defun org-table-paste-rectangle ()
1758 "Paste a rectangular region into a table.
1759 The upper right corner ends up in the current field. All involved fields
1760 will be overwritten. If the rectangle does not fit into the present table,
1761 the table is enlarged as needed. The process ignores horizontal separator
1764 (unless (and org-table-clip
(listp org-table-clip
))
1765 (user-error "First cut/copy a region to paste!"))
1766 (org-table-check-inside-data-field)
1767 (let* ((clip org-table-clip
)
1768 (line (org-current-line))
1769 (col (org-table-current-column))
1770 (org-enable-table-editor t
)
1771 (org-table-automatic-realign nil
)
1773 (while (setq cols
(pop clip
))
1774 (while (org-at-table-hline-p) (beginning-of-line 2))
1775 (if (not (org-at-table-p))
1776 (progn (end-of-line 0) (org-table-next-field)))
1778 (while (setq field
(pop cols
))
1779 (org-table-goto-column c nil
'force
)
1780 (org-table-get-field nil field
)
1782 (beginning-of-line 2))
1783 (org-goto-line line
)
1784 (org-table-goto-column col
)
1788 (defun org-table-convert ()
1789 "Convert from `org-mode' table to table.el and back.
1790 Obviously, this only works within limits. When an Org-mode table is
1791 converted to table.el, all horizontal separator lines get lost, because
1792 table.el uses these as cell boundaries and has no notion of horizontal lines.
1793 A table.el table can be converted to an Org-mode table only if it does not
1794 do row or column spanning. Multiline cells will become multiple cells.
1795 Beware, Org-mode does not test if the table can be successfully converted - it
1796 blindly applies a recipe that works for simple tables."
1799 (if (org-at-table.el-p
)
1800 ;; convert to Org-mode table
1801 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1802 (end (move-marker (make-marker) (org-table-end t
))))
1803 (table-unrecognize-region beg end
)
1805 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1808 (if (org-at-table-p)
1809 ;; convert to table.el table
1810 (let ((beg (move-marker (make-marker) (org-table-begin)))
1811 (end (move-marker (make-marker) (org-table-end))))
1812 ;; first, get rid of all horizontal lines
1814 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1816 ;; insert a hline before first
1818 (org-table-insert-hline 'above
)
1819 (beginning-of-line -
1)
1820 ;; insert a hline after each line
1821 (while (progn (beginning-of-line 3) (< (point) end
))
1822 (org-table-insert-hline))
1824 (setq end
(move-marker end
(org-table-end)))
1825 ;; replace "+" at beginning and ending of hlines
1826 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1827 (replace-match "\\1+-"))
1829 (while (re-search-forward "-|[ \t]*$" end t
)
1830 (replace-match "-+"))
1833 (defun org-table-transpose-table-at-point ()
1834 "Transpose orgmode table at point and eliminate hlines.
1842 will be transposed as
1849 Note that horizontal lines disappeared."
1851 (let* ((table (delete 'hline
(org-table-to-lisp)))
1852 (contents (mapcar (lambda (p)
1858 (setq tp
(cdr tp
))))
1861 (delete-region (org-table-begin) (org-table-end))
1862 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1867 (defun org-table-wrap-region (arg)
1868 "Wrap several fields in a column like a paragraph.
1869 This is useful if you'd like to spread the contents of a field over several
1870 lines, in order to keep the table compact.
1872 If there is an active region, and both point and mark are in the same column,
1873 the text in the column is wrapped to minimum width for the given number of
1874 lines. Generally, this makes the table more compact. A prefix ARG may be
1875 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1876 formats the selected text to two lines. If the region was longer than two
1877 lines, the remaining lines remain empty. A negative prefix argument reduces
1878 the current number of lines by that amount. The wrapped text is pasted back
1879 into the table. If you formatted it to more lines than it was before, fields
1880 further down in the table get overwritten - so you might need to make space in
1883 If there is no region, the current field is split at the cursor position and
1884 the text fragment to the right of the cursor is prepended to the field one
1887 If there is no region, but you specify a prefix ARG, the current field gets
1888 blank, and the content is appended to the field above."
1890 (org-table-check-inside-data-field)
1891 (if (org-region-active-p)
1892 ;; There is a region: fill as a paragraph
1893 (let* ((beg (region-beginning))
1894 (cline (save-excursion (goto-char beg
) (org-current-line)))
1895 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1897 (org-table-cut-region (region-beginning) (region-end))
1898 (if (> (length (car org-table-clip
)) 1)
1899 (user-error "Region must be limited to single column"))
1900 (setq nlines
(if arg
1902 (+ (length org-table-clip
) arg
)
1904 (length org-table-clip
)))
1905 (setq org-table-clip
1906 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1908 (org-goto-line cline
)
1909 (org-table-goto-column ccol
)
1910 (org-table-paste-rectangle))
1911 ;; No region, split the current field at point
1912 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1913 (skip-chars-forward "^\r\n|"))
1915 ;; combine with field above
1916 (let ((s (org-table-blank-field))
1917 (col (org-table-current-column)))
1918 (beginning-of-line 0)
1919 (while (org-at-table-hline-p) (beginning-of-line 0))
1920 (org-table-goto-column col
)
1921 (skip-chars-forward "^|")
1922 (skip-chars-backward " ")
1923 (insert " " (org-trim s
))
1926 (if (looking-at "\\([^|]+\\)+|")
1927 (let ((s (match-string 1)))
1928 (replace-match " |")
1929 (goto-char (match-beginning 0))
1930 (org-table-next-row)
1931 (insert (org-trim s
) " ")
1933 (org-table-next-row)))))
1935 (defvar org-field-marker nil
)
1938 (defun org-table-edit-field (arg)
1939 "Edit table field in a different window.
1940 This is mainly useful for fields that contain hidden parts.
1941 When called with a \\[universal-argument] prefix, just make the full field visible so that
1942 it can be edited in place."
1946 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1948 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1949 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1950 (remove-text-properties b e
'(org-cwidth t invisible t
1951 display t intangible t
))
1952 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1953 (font-lock-fontify-block))))
1955 (let ((pos (point-marker))
1957 (if (eq org-table-use-standard-references t
)
1958 (concat (org-number-to-letters (org-table-current-column))
1959 (int-to-string (org-table-current-dline)))
1960 (concat "@" (int-to-string (org-table-current-dline))
1961 "$" (int-to-string (org-table-current-column)))))
1962 (field (org-table-get-field))
1963 (cw (current-window-configuration))
1966 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1967 (when (and (local-variable-p 'org-field-marker
)
1968 (markerp org-field-marker
))
1969 (move-marker org-field-marker nil
))
1971 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1972 (let ((org-inhibit-startup t
)) (org-mode))
1974 (setq truncate-lines nil
)
1976 (goto-char (setq p
(point-max)))
1977 (insert (org-trim field
))
1978 (remove-text-properties p
(point-max)
1979 '(invisible t org-cwidth t display t
1982 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1983 (org-set-local 'org-window-configuration cw
)
1984 (org-set-local 'org-field-marker pos
)
1985 (message "Edit and finish with C-c C-c")))))
1987 (defun org-table-finish-edit-field ()
1988 "Finish editing a table data field.
1989 Remove all newline characters, insert the result into the table, realign
1990 the table and kill the editing buffer."
1991 (let ((pos org-field-marker
)
1992 (cw org-window-configuration
)
1993 (cb (current-buffer))
1995 (goto-char (point-min))
1996 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1997 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1998 (replace-match " "))
1999 (setq text
(org-trim (buffer-string)))
2000 (set-window-configuration cw
)
2002 (select-window (get-buffer-window (marker-buffer pos
)))
2004 (move-marker pos nil
)
2005 (org-table-check-inside-data-field)
2006 (org-table-get-field nil text
)
2008 (message "New field value inserted")))
2010 (define-minor-mode org-table-follow-field-mode
2011 "Minor mode to make the table field editor window follow the cursor.
2012 When this mode is active, the field editor window will always show the
2013 current field. The mode exits automatically when the cursor leaves the
2014 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2015 nil
" TblFollow" nil
2016 (if org-table-follow-field-mode
2017 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2019 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2020 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2021 (win (and buf
(get-buffer-window buf
))))
2022 (when win
(delete-window win
))
2024 (with-current-buffer buf
2025 (move-marker org-field-marker nil
))
2026 (kill-buffer buf
)))))
2028 (defun org-table-follow-fields-with-editor ()
2029 (if (and org-table-exit-follow-field-mode-when-leaving-table
2030 (not (org-at-table-p)))
2031 ;; We have left the table, exit the follow mode
2032 (org-table-follow-field-mode -
1)
2033 (when (org-table-check-inside-data-field 'noerror
)
2034 (let ((win (selected-window)))
2035 (org-table-edit-field nil
)
2036 (org-fit-window-to-buffer)
2037 (select-window win
)))))
2039 (defvar org-timecnt
) ; dynamically scoped parameter
2042 (defun org-table-sum (&optional beg end nlast
)
2043 "Sum numbers in region of current table column.
2044 The result will be displayed in the echo area, and will be available
2045 as kill to be inserted with \\[yank].
2047 If there is an active region, it is interpreted as a rectangle and all
2048 numbers in that rectangle will be summed. If there is no active
2049 region and point is located in a table column, sum all numbers in that
2052 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2053 numbers are assumed to be times as well (in decimal hours) and the
2054 numbers are added as such.
2056 If NLAST is a number, only the NLAST fields will actually be summed."
2059 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2061 ((and beg end
)) ; beg and end given explicitly
2062 ((org-region-active-p)
2063 (setq beg
(region-beginning) end
(region-end)))
2065 (setq col
(org-table-current-column))
2066 (goto-char (org-table-begin))
2067 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2068 (user-error "No table data"))
2069 (org-table-goto-column col
)
2071 (goto-char (org-table-end))
2072 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2073 (user-error "No table data"))
2074 (org-table-goto-column col
)
2075 (setq end
(point))))
2076 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2077 (items1 (cond ((not nlast
) items
)
2078 ((>= nlast
(length items
)) items
)
2079 (t (setq items
(reverse items
))
2080 (setcdr (nthcdr (1- nlast
) items
) nil
)
2082 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2084 (res (apply '+ numbers
))
2085 (sres (if (= org-timecnt
0)
2086 (number-to-string res
)
2087 (setq diff
(* 3600 res
)
2088 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2089 m
(floor (/ diff
60)) diff
(mod diff
60)
2091 (format "%.0f:%02.0f:%02.0f" h m s
))))
2093 (if (org-called-interactively-p 'interactive
)
2095 (substitute-command-keys
2096 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2097 (length numbers
) sres
))))
2100 (defun org-table-get-number-for-summing (s)
2102 (if (string-match "^ *|? *" s
)
2103 (setq s
(replace-match "" nil nil s
)))
2104 (if (string-match " *|? *$" s
)
2105 (setq s
(replace-match "" nil nil s
)))
2106 (setq n
(string-to-number s
))
2108 ((and (string-match "0" s
)
2109 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2110 ((string-match "\\`[ \t]+\\'" s
) nil
)
2111 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2112 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2113 (m (string-to-number (or (match-string 2 s
) "0")))
2114 (s (string-to-number (or (match-string 4 s
) "0"))))
2115 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2116 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2120 (defun org-table-current-field-formula (&optional key noerror
)
2121 "Return the formula active for the current field.
2122 Assumes that specials are in place.
2123 If KEY is given, return the key to this formula.
2124 Otherwise return the formula preceded with \"=\" or \":=\"."
2125 (let* ((name (car (rassoc (list (org-current-line)
2126 (org-table-current-column))
2127 org-table-named-field-locations
)))
2128 (col (org-table-current-column))
2129 (scol (int-to-string col
))
2130 (ref (format "@%d$%d" (org-table-current-dline) col
))
2131 (stored-list (org-table-get-stored-formulas noerror
))
2132 (ass (or (assoc name stored-list
)
2133 (assoc ref stored-list
)
2134 (assoc scol stored-list
))))
2137 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2140 (defun org-table-get-formula (&optional equation named
)
2141 "Read a formula from the minibuffer, offer stored formula as default.
2142 When NAMED is non-nil, look for a named equation."
2143 (let* ((stored-list (org-table-get-stored-formulas))
2144 (name (car (rassoc (list (org-current-line)
2145 (org-table-current-column))
2146 org-table-named-field-locations
)))
2147 (ref (format "@%d$%d" (org-table-current-dline)
2148 (org-table-current-column)))
2149 (refass (assoc ref stored-list
))
2150 (nameass (assoc name stored-list
))
2152 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2155 (int-to-string (org-table-current-column))))
2156 (dummy (and (or nameass refass
) (not named
)
2157 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2158 (message "Formula not replaced")))
2159 (name (or name ref
))
2160 (org-table-may-need-update nil
)
2161 (stored (cdr (assoc scol stored-list
)))
2163 ((and stored equation
(string-match "^ *=? *$" equation
))
2167 (t (org-table-formula-from-user
2169 (org-table-formula-to-user
2170 (format "%s formula %s%s="
2171 (if named
"Field" "Column")
2172 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2174 (if stored
(org-table-formula-to-user stored
) "")
2175 'org-table-formula-history
2178 (when (not (string-match "\\S-" eq
))
2180 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2181 (org-table-store-formulas stored-list
)
2182 (user-error "Formula removed"))
2183 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2184 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2185 (if (and name
(not named
))
2186 ;; We set the column equation, delete the named one.
2187 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2190 (setcdr (assoc scol stored-list
) eq
)
2191 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2192 (if (or mustsave
(not (equal stored eq
)))
2193 (org-table-store-formulas stored-list
))
2196 (defun org-table-store-formulas (alist)
2197 "Store the list of formulas below the current table."
2198 (setq alist
(sort alist
'org-table-formula-less-p
))
2199 (let ((case-fold-search t
))
2201 (goto-char (org-table-end))
2202 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2204 ;; don't overwrite TBLFM, we might use text properties to store stuff
2205 (goto-char (match-beginning 3))
2206 (delete-region (match-beginning 3) (match-end 0)))
2208 (insert (or (match-string 2) "#+TBLFM:")))
2210 (mapconcat (lambda (x)
2212 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2213 (car x
) "=" (cdr x
)))
2217 (defsubst org-table-formula-make-cmp-string
(a)
2218 (when (string-match "\\`$[<>]" a
)
2219 (let ((arrow (string-to-char (substring a
1))))
2220 ;; Fake a high number to make sure this is sorted at the end.
2221 (setq a
(org-table-formula-handle-first/last-rc a
))
2222 (setq a
(format "$%d" (+ 10000
2223 (if (= arrow ?
<) -
1000 0)
2224 (string-to-number (substring a
1)))))))
2226 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2230 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2232 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2234 (concat "@@" (match-string 5 a
))))))
2236 (defun org-table-formula-less-p (a b
)
2237 "Compare two formulas for sorting."
2238 (let ((as (org-table-formula-make-cmp-string (car a
)))
2239 (bs (org-table-formula-make-cmp-string (car b
))))
2240 (and as bs
(string< as bs
))))
2243 (defun org-table-get-stored-formulas (&optional noerror
)
2244 "Return an alist with the stored formulas directly after current table."
2245 (interactive) ;; FIXME interactive?
2246 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2248 (goto-char (org-table-end))
2249 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2250 (setq strings
(org-split-string (org-match-string-no-properties 2)
2252 (while (setq string
(pop strings
))
2253 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2254 (setq scol
(if (match-end 2)
2255 (match-string 2 string
)
2256 (match-string 1 string
))
2257 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2258 (concat "$" scol
) scol
)
2259 eq
(match-string 3 string
)
2260 eq-alist
(cons (cons scol eq
) eq-alist
))
2261 (if (member scol seen
)
2264 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2267 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2268 (push scol seen
))))))
2269 (nreverse eq-alist
)))
2271 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2272 "Modify the equations after the table structure has been edited.
2273 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2274 For all numbers larger than LIMIT, shift them by DELTA."
2276 (goto-char (org-table-end))
2277 (let ((case-fold-search t
)
2278 (s-end (save-excursion (re-search-forward "^\\S-*$\\|\\'" nil t
))))
2279 (while (re-search-forward "[ \t]*#\\+tblfm:" s-end t
)
2280 (let ((msg "The formulas in #+TBLFM have been updated")
2281 (re (concat key
"\\([0-9]+\\)"))
2284 (if (or (equal key
"$") (equal key
"$LR"))
2285 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2286 (regexp-quote key
) remove
)
2287 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2290 (while (re-search-forward re2
(point-at-eol) t
)
2291 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2292 (if (equal (char-before (match-beginning 0)) ?.
)
2293 (user-error "Change makes TBLFM term %s invalid, use undo to recover"
2295 (replace-match "")))))
2296 (while (re-search-forward re
(point-at-eol) t
)
2297 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2298 (setq s
(match-string 1) n
(string-to-number s
))
2300 ((setq a
(assoc s replace
))
2301 (replace-match (concat key
(cdr a
)) t t
)
2303 ((and limit
(> n limit
))
2304 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2305 (message msg
))))))))))
2307 (defun org-table-get-specials ()
2308 "Get the column names and local parameters for this table."
2310 (let ((beg (org-table-begin)) (end (org-table-end))
2311 names name fields fields1 field cnt
2312 c v l line col types dlines hlines last-dline
)
2313 (setq org-table-column-names nil
2314 org-table-local-parameters nil
2315 org-table-named-field-locations nil
2316 org-table-current-begin-line nil
2317 org-table-current-begin-pos nil
2318 org-table-current-line-types nil
2319 org-table-current-ncol
0)
2321 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2322 (setq names
(org-split-string (match-string 1) " *| *")
2324 (while (setq name
(pop names
))
2326 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2327 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2328 (setq org-table-column-names
(nreverse org-table-column-names
))
2329 (setq org-table-column-name-regexp
2330 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2332 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2333 (setq fields
(org-split-string (match-string 1) " *| *"))
2334 (while (setq field
(pop fields
))
2335 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2336 (push (cons (match-string 1 field
) (match-string 2 field
))
2337 org-table-local-parameters
))))
2339 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2340 (setq c
(match-string 1)
2341 fields
(org-split-string (match-string 2) " *| *"))
2343 (beginning-of-line (if (equal c
"_") 2 0))
2344 (setq line
(org-current-line) col
1)
2345 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2346 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2347 (while (and fields1
(setq field
(pop fields
)))
2348 (setq v
(pop fields1
) col
(1+ col
))
2349 (when (and (stringp field
) (stringp v
)
2350 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2351 (push (cons field v
) org-table-local-parameters
)
2352 (push (list field line col
) org-table-named-field-locations
))))
2353 ;; Analyse the line types
2355 (setq org-table-current-begin-line
(org-current-line)
2356 org-table-current-begin-pos
(point)
2357 l org-table-current-begin-line
)
2358 (while (looking-at "[ \t]*|\\(-\\)?")
2359 (push (if (match-end 1) 'hline
'dline
) types
)
2360 (if (match-end 1) (push l hlines
) (push l dlines
))
2361 (beginning-of-line 2)
2363 (push 'hline types
) ;; add an imaginary extra hline to the end
2364 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2365 last-dline
(car dlines
)
2366 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2367 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2368 (org-goto-line last-dline
)
2369 (let* ((l last-dline
)
2370 (fields (org-split-string
2371 (buffer-substring (point-at-bol) (point-at-eol))
2373 (nfields (length fields
))
2375 (setq org-table-current-ncol nfields
)
2376 (loop for i from
1 to nfields do
2377 (push (list (format "LR%d" i
) l i
) al
)
2378 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2379 (setq org-table-named-field-locations
2380 (append org-table-named-field-locations al
))
2381 (setq org-table-local-parameters
2382 (append org-table-local-parameters al2
))))))
2385 (defun org-table-maybe-eval-formula ()
2386 "Check if the current field starts with \"=\" or \":=\".
2387 If yes, store the formula and apply it."
2388 ;; We already know we are in a table. Get field will only return a formula
2389 ;; when appropriate. It might return a separator line, but no problem.
2390 (when org-table-formula-evaluate-inline
2391 (let* ((field (org-trim (or (org-table-get-field) "")))
2393 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2394 (setq named
(equal (string-to-char field
) ?
:)
2395 eq
(match-string 1 field
))
2396 (if (or (fboundp 'calc-eval
)
2397 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2398 (org-table-eval-formula (if named
'(4) nil
)
2399 (org-table-formula-from-user eq
))
2400 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2402 (defvar org-recalc-commands nil
2403 "List of commands triggering the recalculation of a line.
2404 Will be filled automatically during use.")
2406 (defvar org-recalc-marks
2407 '((" " .
"Unmarked: no special line, no automatic recalculation")
2408 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2409 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2410 ("!" .
"Column name definition line. Reference in formula as $name.")
2411 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2412 ("_" .
"Names for values in row below this one.")
2413 ("^" .
"Names for values in row above this one.")))
2416 (defun org-table-rotate-recalc-marks (&optional newchar
)
2417 "Rotate the recalculation mark in the first column.
2418 If in any row, the first field is not consistent with a mark,
2419 insert a new column for the markers.
2420 When there is an active region, change all the lines in the region,
2421 after prompting for the marking character.
2422 After each change, a message will be displayed indicating the meaning
2425 (unless (org-at-table-p) (user-error "Not at a table"))
2426 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2427 (beg (org-table-begin))
2428 (end (org-table-end))
2429 (l (org-current-line))
2430 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2431 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2435 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2436 (col (org-table-current-column))
2437 (forcenew (car (assoc newchar org-recalc-marks
)))
2440 (message "Change region to what mark? Type # * ! $ or SPC: ")
2441 (setq newchar
(char-to-string (read-char-exclusive))
2442 forcenew
(car (assoc newchar org-recalc-marks
))))
2443 (if (and newchar
(not forcenew
))
2444 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2446 (if l1
(org-goto-line l1
))
2448 (beginning-of-line 1)
2449 (unless (looking-at org-table-dataline-regexp
)
2450 (user-error "Not at a table data line")))
2452 (org-table-goto-column 1)
2453 (org-table-insert-column)
2454 (org-table-goto-column (1+ col
)))
2455 (setq epos
(point-at-eol))
2457 (beginning-of-line 1)
2458 (org-table-get-field
2459 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2461 (setq new
(or forcenew
2462 (cadr (member (match-string 1) marks
))))
2468 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2469 (and (looking-at org-table-dataline-regexp
)
2470 (org-table-get-field 1 (concat " " new
" "))))
2471 (org-goto-line l1
)))
2472 (if (not (= epos
(point-at-eol))) (org-table-align))
2474 (and (org-called-interactively-p 'interactive
)
2475 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2478 (defun org-table-maybe-recalculate-line ()
2479 "Recompute the current line if marked for it, and if we haven't just done it."
2481 (and org-table-allow-automatic-line-recalculation
2482 (not (and (memq last-command org-recalc-commands
)
2483 (equal org-last-recalc-line
(org-current-line))))
2484 (save-excursion (beginning-of-line 1)
2485 (looking-at org-table-auto-recalculate-regexp
))
2486 (org-table-recalculate) t
))
2488 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2489 (defsubst org-set-calc-mode
(var &optional value
)
2491 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2492 ("R" calc-angle-mode rad
)
2493 ("F" calc-prefer-frac t
)
2494 ("S" calc-symbolic-mode t
)))
2495 value
(nth 2 var
) var
(nth 1 var
)))
2496 (if (memq var org-tbl-calc-modes
)
2497 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2498 (cons var
(cons value org-tbl-calc-modes
)))
2502 (defun org-table-eval-formula (&optional arg equation
2503 suppress-align suppress-const
2504 suppress-store suppress-analysis
)
2505 "Replace the table field value at the cursor by the result of a calculation.
2507 This function makes use of Dave Gillespie's Calc package, in my view the
2508 most exciting program ever written for GNU Emacs. So you need to have Calc
2509 installed in order to use this function.
2511 In a table, this command replaces the value in the current field with the
2512 result of a formula. It also installs the formula as the \"current\" column
2513 formula, by storing it in a special line below the table. When called
2514 with a `C-u' prefix, the current field must be a named field, and the
2515 formula is installed as valid in only this specific field.
2517 When called with two `C-u' prefixes, insert the active equation
2518 for the field back into the current field, so that it can be
2519 edited there. This is useful in order to use \\[org-table-show-reference]
2520 to check the referenced fields.
2522 When called, the command first prompts for a formula, which is read in
2523 the minibuffer. Previously entered formulas are available through the
2524 history list, and the last used formula is offered as a default.
2525 These stored formulas are adapted correctly when moving, inserting, or
2526 deleting columns with the corresponding commands.
2528 The formula can be any algebraic expression understood by the Calc package.
2529 For details, see the Org-mode manual.
2531 This function can also be called from Lisp programs and offers
2532 additional arguments: EQUATION can be the formula to apply. If this
2533 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2534 used to speed-up recursive calls by by-passing unnecessary aligns.
2535 SUPPRESS-CONST suppresses the interpretation of constants in the
2536 formula, assuming that this has been done already outside the function.
2537 SUPPRESS-STORE means the formula should not be stored, either because
2538 it is already stored, or because it is a modified equation that should
2539 not overwrite the stored one."
2541 (org-table-check-inside-data-field)
2542 (or suppress-analysis
(org-table-get-specials))
2543 (if (equal arg
'(16))
2544 (let ((eq (org-table-current-field-formula)))
2545 (or eq
(user-error "No equation active for current field"))
2546 (org-table-get-field nil eq
)
2548 (setq org-table-may-need-update t
))
2550 (ndown (if (integerp arg
) arg
1))
2551 (org-table-automatic-realign nil
)
2552 (case-fold-search nil
)
2554 (formula (if (and equation suppress-store
)
2556 (org-table-get-formula equation
(equal arg
'(4)))))
2557 (n0 (org-table-current-column))
2558 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2559 (numbers nil
) ; was a variable, now fixed default
2561 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2562 duration duration-output-format
)
2563 ;; Parse the format string. Since we have a lot of modes, this is
2564 ;; a lot of work. However, I think calc still uses most of the time.
2565 (if (string-match ";" formula
)
2566 (let ((tmp (org-split-string formula
";")))
2567 (setq formula
(car tmp
)
2568 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2570 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2571 (setq c
(string-to-char (match-string 1 fmt
))
2572 n
(string-to-number (match-string 2 fmt
)))
2574 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2575 (setq org-tbl-calc-modes
2578 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2579 (?s . sci
) (?e . eng
))))
2581 (setq fmt
(replace-match "" t t fmt
)))
2582 (if (string-match "T" fmt
)
2583 (setq duration t numbers t
2584 duration-output-format nil
2585 fmt
(replace-match "" t t fmt
)))
2586 (if (string-match "t" fmt
)
2588 duration-output-format org-table-duration-custom-format
2590 fmt
(replace-match "" t t fmt
)))
2591 (if (string-match "N" fmt
)
2593 fmt
(replace-match "" t t fmt
)))
2594 (if (string-match "L" fmt
)
2596 fmt
(replace-match "" t t fmt
)))
2597 (if (string-match "E" fmt
)
2599 fmt
(replace-match "" t t fmt
)))
2600 (while (string-match "[DRFS]" fmt
)
2601 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2602 (setq fmt
(replace-match "" t t fmt
)))
2603 (unless (string-match "\\S-" fmt
)
2605 (if (and (not suppress-const
) org-table-formula-use-constants
)
2606 (setq formula
(org-table-formula-substitute-names formula
)))
2607 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2609 (setq fields
(org-split-string
2610 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2612 ;; replace fields with duration values if relevant
2615 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2618 (setq fields
(mapcar
2620 (if (string-match "\\S-" x
)
2621 (number-to-string (string-to-number x
))
2624 (setq ndown
(1- ndown
))
2625 (setq form
(copy-sequence formula
)
2626 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2627 (if (and lispp literal
) (setq lispp
'literal
))
2629 ;; Insert row and column number of formula result field
2630 (while (string-match "[@$]#" form
)
2635 (if (equal (substring form
(match-beginning 0)
2636 (1+ (match-beginning 0)))
2638 (org-table-current-dline)
2639 (org-table-current-column))))
2642 ;; Check for old vertical references
2643 (setq form
(org-table-rewrite-old-row-references form
))
2644 ;; Insert remote references
2645 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2649 (org-table-make-reference
2650 (let ((rmtrng (org-table-get-remote-range
2651 (match-string 1 form
) (match-string 2 form
))))
2654 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2655 (org-table-time-string-to-seconds rmtrng
))
2657 keep-empty numbers lispp
))
2659 ;; Insert complex ranges
2660 (while (and (string-match org-table-range-regexp form
)
2661 (> (length (match-string 0 form
)) 1))
2662 (setq formrg
(save-match-data
2663 (org-table-get-range (match-string 0 form
) nil n0
)))
2666 (org-table-make-reference
2667 ;; possibly handle durations
2670 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2671 (org-table-time-string-to-seconds formrg
))
2673 keep-empty numbers lispp
)))
2674 (if (not (save-match-data
2675 (string-match (regexp-quote form
) formrpl
)))
2676 (setq form
(replace-match formrpl t t form
))
2677 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2678 ;; Insert simple ranges
2679 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2683 (org-table-make-reference
2685 fields
(string-to-number (match-string 1 form
))
2686 (string-to-number (match-string 2 form
)))
2687 keep-empty numbers lispp
))
2690 ;; Insert the references to fields in same row
2691 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2692 (setq n
(+ (string-to-number (match-string 1 form
))
2693 (if (match-end 2) n0
0))
2694 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2695 (unless x
(user-error "Invalid field specifier \"%s\""
2696 (match-string 0 form
)))
2697 (setq form
(replace-match
2699 (org-table-make-reference
2700 x keep-empty numbers lispp
))
2704 (setq ev
(condition-case nil
2705 (eval (eval (read form
)))
2707 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2708 ev
(if duration
(org-table-time-seconds-to-string
2709 (string-to-number ev
)
2710 duration-output-format
) ev
))
2711 (or (fboundp 'calc-eval
)
2712 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2713 ;; Use <...> time-stamps so that Calc can handle them
2714 (setq form
(replace-regexp-in-string org-ts-regexp3
"<\\1>" form
))
2715 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2716 (when (string-match org-ts-regexp2 form
)
2717 (let* ((ts (match-string 0 form
))
2718 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2719 (system-time-locale "C")
2720 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2721 (cdr org-time-stamp-formats
))
2722 (car org-time-stamp-formats
))))
2723 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2725 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2727 (calc-eval (cons form org-tbl-calc-modes
)
2728 (when (and (not keep-empty
) numbers
) 'num
)))
2729 ev
(if duration
(org-table-time-seconds-to-string
2730 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2731 (string-to-number (org-table-time-string-to-seconds ev
))
2732 (string-to-number ev
))
2733 duration-output-format
)
2736 (when org-table-formula-debug
2737 (with-output-to-temp-buffer "*Substitution History*"
2738 (princ (format "Substitution history of formula
2742 $1-> %s\n" orig formula form0 form
))
2744 (princ (format " %s^\nError: %s"
2745 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2746 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2748 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2749 (setq bw
(get-buffer-window "*Substitution History*"))
2750 (org-fit-window-to-buffer bw
)
2751 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2752 (unless (let (inhibit-redisplay)
2753 (y-or-n-p "Debugging Formula. Continue to next? "))
2755 (user-error "Abort"))
2758 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2759 (org-table-justify-field-maybe
2760 (format org-table-formula-field-format
2761 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2762 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2763 (call-interactively 'org-return
)
2765 (and down
(org-table-maybe-recalculate-line))
2766 (or suppress-align
(and org-table-may-need-update
2767 (org-table-align))))))
2769 (defun org-table-put-field-property (prop value
)
2771 (put-text-property (progn (skip-chars-backward "^|") (point))
2772 (progn (skip-chars-forward "^|") (point))
2775 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2776 "Get a calc vector from a column, according to descriptor DESC.
2777 Optional arguments TBEG and COL can give the beginning of the table and
2778 the current column, to avoid unnecessary parsing.
2780 HIGHLIGHT means just highlight the range.
2782 When CORNERS-ONLY is set, only return the corners of the range as
2783 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2784 in the buffer and column1 and column2 are table column numbers."
2785 (if (not (equal (string-to-char desc
) ?
@))
2786 (setq desc
(concat "@" desc
)))
2788 (or tbeg
(setq tbeg
(org-table-begin)))
2789 (or col
(setq col
(org-table-current-column)))
2790 (let ((thisline (org-current-line))
2791 beg end c1 c2 r1 r2 rangep tmp
)
2792 (unless (string-match org-table-range-regexp desc
)
2793 (user-error "Invalid table range specifier `%s'" desc
))
2794 (setq rangep
(match-end 3)
2795 r1
(and (match-end 1) (match-string 1 desc
))
2796 r2
(and (match-end 4) (match-string 4 desc
))
2797 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2798 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2800 (and c1
(setq c1
(+ (string-to-number c1
)
2801 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2802 (and c2
(setq c2
(+ (string-to-number c2
)
2803 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2804 (if (equal r1
"") (setq r1 nil
))
2805 (if (equal r2
"") (setq r2 nil
))
2806 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2807 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2808 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2809 (if (not r1
) (setq r1 thisline
))
2810 (if (not r2
) (setq r2 thisline
))
2811 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2812 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2813 (if (and (not corners-only
)
2814 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2818 (while (not (looking-at org-table-dataline-regexp
))
2819 (beginning-of-line 2))
2820 (prog1 (org-trim (org-table-get-field c1
))
2821 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2822 ;; A range, return a vector
2823 ;; First sort the numbers to get a regular rectangle
2824 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2825 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2827 ;; Only return the corners of the range
2829 ;; Copy the range values into a list
2831 (while (not (looking-at org-table-dataline-regexp
))
2832 (beginning-of-line 2))
2833 (org-table-goto-column c1
)
2836 (while (not (looking-at org-table-dataline-regexp
))
2837 (beginning-of-line 0))
2838 (org-table-goto-column c2
)
2841 (org-table-highlight-rectangle
2842 beg
(progn (skip-chars-forward "^|\n") (point))))
2843 ;; return string representation of calc vector
2845 (apply 'append
(org-table-copy-region beg end
))))))))
2847 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2848 "Analyze descriptor DESC and retrieve the corresponding line number.
2849 The cursor is currently in line CLINE, the table begins in line BLINE,
2850 and TABLE is a vector with line types."
2851 (if (string-match "^[0-9]+$" desc
)
2852 (aref org-table-dlines
(string-to-number desc
))
2853 (setq cline
(or cline
(org-current-line))
2854 bline
(or bline org-table-current-begin-line
)
2855 table
(or table org-table-current-line-types
))
2857 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2859 (and (not (match-end 3)) (not (match-end 6)))
2860 (and (match-end 3) (match-end 6) (not (match-end 5))))
2861 (user-error "Invalid row descriptor `%s'" desc
))
2862 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2863 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2864 (odir (and (match-end 5) (match-string 5 desc
)))
2865 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2867 (rel (and (match-end 6)
2868 (or (and (match-end 1) (not (match-end 3)))
2870 (if (and hn
(not hdir
))
2873 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2874 (if (and (not hn
) on
(not odir
))
2875 (user-error "Should never happen");;(aref org-table-dlines on)
2876 (if (and hn
(> hn
0))
2877 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2878 nil hn cline desc
)))
2880 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2881 rel on cline desc
)))
2884 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2885 "FIXME: Needs more documentation."
2886 (let ((l (length table
)))
2888 (while (and (setq i
(+ i
(if backwards -
1 1)))
2890 (not (eq (aref table i
) type
))
2891 (if (and relative
(eq (aref table i
) 'hline
))
2893 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2894 ((eq org-table-relative-ref-may-cross-hline
'error
)
2895 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2896 (t (setq i
(- i
(if backwards -
1 1))
2901 (if (or (< i
0) (>= i l
))
2902 (user-error "Row descriptor %s used in line %d leads outside table"
2906 (defun org-table-rewrite-old-row-references (s)
2907 (if (string-match "&[-+0-9I]" s
)
2908 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2911 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2912 "Convert list ELEMENTS to something appropriate to insert into formula.
2913 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2914 NUMBERS indicates that everything should be converted to numbers.
2915 LISPP non-nil means to return something appropriate for a Lisp
2916 list, 'literal is for the format specifier L."
2917 ;; Calc nan (not a number) is used for the conversion of the empty
2918 ;; field to a reference for several reasons: (i) It is accepted in a
2919 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2920 ;; (ii) In a single field (not in range) it can be distinguished
2921 ;; from "(nan)" which is the reference made from a single field
2922 ;; containing "nan".
2923 (if (stringp elements
)
2926 (if (eq lispp
'literal
)
2928 (if (and (eq elements
"") (not keep-empty
))
2931 (if numbers
(string-to-number elements
) elements
))))
2932 (if (string-match "\\S-" elements
)
2934 (when numbers
(setq elements
(number-to-string
2935 (string-to-number elements
))))
2936 (concat "(" elements
")"))
2937 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2942 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2944 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
2948 (if (eq lispp
'literal
)
2950 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2952 (concat "[" (mapconcat
2954 (if (string-match "\\S-" x
)
2956 (number-to-string (string-to-number x
))
2958 (if (or (not keep-empty
) numbers
) "0" "nan")))
2963 (defun org-table-set-constants ()
2964 "Set `org-table-formula-constants-local' in the current buffer."
2965 (let (cst consts const-str
)
2967 (goto-char (point-min))
2968 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
2969 (setq const-str
(substring-no-properties (match-string 1)))
2970 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
2973 (while (setq e
(pop consts
))
2974 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
2975 (if (assoc-string (match-string 1 e
) cst
)
2976 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
2977 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
2978 (setq org-table-formula-constants-local cst
)))))))
2981 (defun org-table-recalculate (&optional all noalign
)
2982 "Recalculate the current table line by applying all stored formulas.
2983 With prefix arg ALL, do this for all lines in the table.
2984 With the prefix argument ALL is `(16)' \
2985 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2986 it is the symbol `iterate', recompute the table until it no longer changes.
2987 If NOALIGN is not nil, do not re-align the table after the computations
2988 are done. This is typically used internally to save time, if it is
2989 known that the table will be realigned a little later anyway."
2991 (or (memq this-command org-recalc-commands
)
2992 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2993 (unless (org-at-table-p) (user-error "Not at a table"))
2994 (if (or (eq all
'iterate
) (equal all
'(16)))
2996 (org-table-get-specials)
2997 (let* ((eqlist (sort (org-table-get-stored-formulas)
2998 (lambda (a b
) (string< (car a
) (car b
)))))
2999 (eqlist1 (copy-sequence eqlist
))
3000 (inhibit-redisplay (not debug-on-error
))
3001 (line-re org-table-dataline-regexp
)
3002 (thisline (org-current-line))
3003 (thiscol (org-table-current-column))
3005 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3006 ;; Insert constants in all formulas
3009 (when (string-match "\\`$[<>]" (car x
))
3011 (setq x
(cons (substring
3012 (org-table-formula-handle-first/last-rc
3015 (if (assoc (car x
) eqlist1
)
3016 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3019 (org-table-formula-handle-first/last-rc
(car x
))
3020 (org-table-formula-substitute-names
3021 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3023 ;; Split the equation list
3024 (while (setq eq
(pop eqlist
))
3025 (if (<= (string-to-char (car eq
)) ?
9)
3028 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3029 ;; Expand ranges in lhs of formulas
3030 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3032 ;; Get the correct line range to process
3035 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3036 (goto-char (setq beg
(org-table-begin)))
3037 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3038 ;; This is a table with marked lines, compute selected lines
3039 (setq line-re org-table-recalculate-regexp
)
3040 ;; Move forward to the first non-header line
3041 (if (and (re-search-forward org-table-dataline-regexp end t
)
3042 (re-search-forward org-table-hline-regexp end t
)
3043 (re-search-forward org-table-dataline-regexp end t
))
3044 (setq beg
(match-beginning 0))
3045 nil
))) ;; just leave beg where it is
3046 (setq beg
(point-at-bol)
3047 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3049 (and all
(message "Re-applying formulas to full table..."))
3051 ;; First find the named fields, and mark them untouchable.
3052 ;; Also check if several field/range formulas try to set the same field.
3053 (remove-text-properties beg end
'(org-untouchable t
))
3054 (while (setq eq
(pop eqlname
))
3056 a
(assoc name org-table-named-field-locations
))
3058 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3060 (when (member name1 seen-fields
)
3061 (user-error "Several field/range formulas try to set %s" name1
))
3062 (push name1 seen-fields
)
3065 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3068 (aref org-table-dlines
3069 (string-to-number (match-string 1 name
)))
3070 (error (user-error "Invalid row number in %s"
3072 (string-to-number (match-string 2 name
)))))
3073 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3074 (message "Re-applying formula to field: %s" name
)
3075 (org-goto-line (nth 1 a
))
3076 (org-table-goto-column (nth 2 a
))
3077 (push (append a
(list (cdr eq
))) eqlname1
)
3078 (org-table-put-field-property :org-untouchable t
)))
3079 (setq eqlname1
(nreverse eqlname1
))
3081 ;; Now evaluate the column formulas, but skip fields covered by
3084 (while (re-search-forward line-re end t
)
3085 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3086 ;; Unprotected line, recalculate
3087 (and all
(message "Re-applying formulas to full table...(line %d)"
3088 (setq cnt
(1+ cnt
))))
3089 (setq org-last-recalc-line
(org-current-line))
3091 (while (setq entry
(pop eql
))
3092 (org-goto-line org-last-recalc-line
)
3093 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3094 (unless (get-text-property (point) :org-untouchable
)
3095 (org-table-eval-formula nil
(cdr entry
)
3096 'noalign
'nocst
'nostore
'noanalysis
)))))
3098 ;; Now evaluate the field formulas
3099 (while (setq eq
(pop eqlname1
))
3100 (message "Re-applying formula to field: %s" (car eq
))
3101 (org-goto-line (nth 1 eq
))
3102 (org-table-goto-column (nth 2 eq
))
3103 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3104 'nostore
'noanalysis
))
3106 (org-goto-line thisline
)
3107 (org-table-goto-column thiscol
)
3108 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3109 (or noalign
(and org-table-may-need-update
(org-table-align))
3110 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3112 ;; back to initial position
3113 (message "Re-applying formulas...done")
3114 (org-goto-line thisline
)
3115 (org-table-goto-column thiscol
)
3116 (or noalign
(and org-table-may-need-update
(org-table-align))
3117 (and all
(message "Re-applying formulas...done"))))))
3120 (defun org-table-iterate (&optional arg
)
3121 "Recalculate the table until it does not change anymore.
3122 The maximum number of iterations is 10, but you can choose a different value
3123 with the prefix ARG."
3125 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3127 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3132 (org-table-recalculate 'all
)
3133 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3134 (if (not (string= lasttbl thistbl
))
3135 (setq lasttbl thistbl
)
3137 (message "Convergence after %d iterations" i
)
3138 (message "Table was already stable"))
3140 (user-error "No convergence after %d iterations" i
))))
3143 (defun org-table-recalculate-buffer-tables ()
3144 "Recalculate all tables in the current buffer."
3149 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3152 (defun org-table-iterate-buffer-tables ()
3153 "Iterate all tables in the buffer, to converge inter-table dependencies."
3157 (checksum (md5 (buffer-string)))
3165 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3166 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3168 (message "Convergence after %d iterations" (- imax i
))
3170 (setq checksum c1
)))
3171 (user-error "No convergence after %d iterations" imax
))))))
3173 (defun org-table-calc-current-TBLFM (&optional arg
)
3174 "Apply the #+TBLFM in the line at point to the table."
3176 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3177 (let ((formula (buffer-substring
3182 ;; Insert a temporary formula at right after the table
3183 (goto-char (org-table-TBLFM-begin))
3184 (setq s
(set-marker (make-marker) (point)))
3185 (insert (concat formula
"\n"))
3186 (setq e
(set-marker (make-marker) (point)))
3187 ;; Recalculate the table
3188 (beginning-of-line 0) ; move to the inserted line
3189 (skip-chars-backward " \r\n\t")
3190 (if (org-at-table-p)
3192 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3193 ;; delete the formula inserted temporarily
3194 (delete-region s e
))))))
3196 (defun org-table-TBLFM-begin ()
3197 "Find the beginning of the TBLFM lines and return its position.
3198 Return nil when the beginning of TBLFM line was not found."
3200 (when (progn (forward-line 1)
3202 org-table-TBLFM-begin-regexp
3206 (defun org-table-expand-lhs-ranges (equations)
3207 "Expand list of formulas.
3208 If some of the RHS in the formulas are ranges or a row reference, expand
3209 them to individual field equations for each field."
3210 (let (e res lhs rhs range r1 r2 c1 c2
)
3211 (while (setq e
(pop equations
))
3212 (setq lhs
(car e
) rhs
(cdr e
))
3214 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3215 ;; This just refers to one fixed field
3217 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3218 ;; This just refers to one fixed named field
3220 ((string-match "^@[0-9]+$" lhs
)
3221 (loop for ic from
1 to org-table-current-ncol do
3222 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3223 (put-text-property 0 (length (caar res
))
3224 :orig-eqn e
(caar res
))))
3226 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3228 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3229 r2
(nth 2 range
) c2
(nth 3 range
))
3230 (setq r1
(org-table-line-to-dline r1
))
3231 (setq r2
(org-table-line-to-dline r2
'above
))
3232 (loop for ir from r1 to r2 do
3233 (loop for ic from c1 to c2 do
3234 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3235 (put-text-property 0 (length (caar res
))
3236 :orig-eqn e
(caar res
)))))))
3239 (defun org-table-formula-handle-first/last-rc
(s)
3240 "Replace @<, @>, $<, $> with first/last row/column of the table.
3241 So @< and $< will always be replaced with @1 and $1, respectively.
3242 The advantage of these special markers are that structure editing of
3243 the table will not change them, while @1 and $1 will be modified
3244 when a line/row is swapped out of that privileged position. So for
3245 formulas that use a range of rows or columns, it may often be better
3246 to anchor the formula with \"I\" row markers, or to offset from the
3247 borders of the table using the @< @> $< $> makers."
3248 (let (n nmax len char
(start 0))
3249 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3252 (setq start
(match-end 3))
3253 (setq nmax
(if (equal (match-string 1 s
) "@")
3254 (1- (length org-table-dlines
))
3255 org-table-current-ncol
)
3256 len
(- (match-end 2) (match-beginning 2))
3257 char
(string-to-char (match-string 2 s
))
3261 (if (or (< n
1) (> n nmax
))
3262 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3263 (match-string 0 s
) s
))
3264 (setq start
(match-beginning 0))
3265 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3268 (defun org-table-formula-substitute-names (f)
3269 "Replace $const with values in string F."
3270 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3271 ;; First, check for column names
3272 (while (setq start
(string-match org-table-column-name-regexp f start
))
3273 (setq start
(1+ start
))
3274 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3275 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3276 ;; Parameters and constants
3278 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3280 (setq start
(match-end 2))
3281 (setq start
(1+ start
))
3282 (if (setq a
(save-match-data
3283 (org-table-get-constant (match-string 1 f
))))
3284 (setq f
(replace-match
3285 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3286 (if org-table-formula-debug
3287 (put-text-property 0 (length f
) :orig-formula f1 f
))
3290 (defun org-table-get-constant (const)
3291 "Find the value for a parameter or constant in a formula.
3292 Parameters get priority."
3293 (or (cdr (assoc const org-table-local-parameters
))
3294 (cdr (assoc const org-table-formula-constants-local
))
3295 (cdr (assoc const org-table-formula-constants
))
3296 (and (fboundp 'constants-get
) (constants-get const
))
3297 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3298 (org-entry-get nil
(substring const
5) 'inherit
))
3301 (defvar org-table-fedit-map
3302 (let ((map (make-sparse-keymap)))
3303 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3304 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3305 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3306 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3307 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3308 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3309 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3310 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3311 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3312 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3313 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3314 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3315 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3316 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3317 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3318 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3319 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3320 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3321 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3322 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3325 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3327 ["Finish and Install" org-table-fedit-finish t
]
3328 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3329 ["Abort" org-table-fedit-abort t
]
3331 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3332 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3334 "Shift Reference at Point"
3335 ["Up" org-table-fedit-ref-up t
]
3336 ["Down" org-table-fedit-ref-down t
]
3337 ["Left" org-table-fedit-ref-left t
]
3338 ["Right" org-table-fedit-ref-right t
]
3340 "Change Test Row for Column Formulas"
3341 ["Up" org-table-fedit-line-up t
]
3342 ["Down" org-table-fedit-line-down t
]
3344 ["Scroll Table Window" org-table-fedit-scroll t
]
3345 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3346 ["Show Table Grid" org-table-fedit-toggle-coordinates
3347 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3348 org-table-overlay-coordinates
)]
3350 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3351 :style toggle
:selected org-table-buffer-is-an
]))
3356 (defun org-table-edit-formulas ()
3357 "Edit the formulas of the current table in a separate buffer."
3359 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3360 (beginning-of-line 0))
3361 (unless (org-at-table-p) (user-error "Not at a table"))
3362 (org-table-get-specials)
3363 (let ((key (org-table-current-field-formula 'key
'noerror
))
3364 (eql (sort (org-table-get-stored-formulas 'noerror
)
3365 'org-table-formula-less-p
))
3366 (pos (point-marker))
3368 (wc (current-window-configuration))
3369 (sel-win (selected-window))
3370 (titles '((column .
"# Column Formulas\n")
3371 (field .
"# Field and Range Formulas\n")
3372 (named .
"# Named Field Formulas\n")))
3374 (org-switch-to-buffer-other-window "*Edit Formulas*")
3376 ;; Keep global-font-lock-mode from turning on font-lock-mode
3377 (let ((font-lock-global-modes '(not fundamental-mode
)))
3379 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3380 (org-set-local 'org-pos pos
)
3381 (org-set-local 'org-window-configuration wc
)
3382 (org-set-local 'org-selected-window sel-win
)
3383 (use-local-map org-table-fedit-map
)
3384 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3385 (easy-menu-add org-table-fedit-menu
)
3386 (setq startline
(org-current-line))
3387 (while (setq entry
(pop eql
))
3389 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3390 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3391 ((string-match "^[0-9]" (car entry
)) 'column
)
3393 (when (setq title
(assq type titles
))
3394 (or (bobp) (insert "\n"))
3395 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3396 (setq titles
(remove title titles
)))
3397 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3398 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3399 (car entry
) " = " (cdr entry
) "\n"))
3400 (remove-text-properties 0 (length s
) '(face nil
) s
)
3402 (if (eq org-table-use-standard-references t
)
3403 (org-table-fedit-toggle-ref-type))
3404 (org-goto-line startline
)
3405 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3407 (defun org-table-fedit-post-command ()
3408 (when (not (memq this-command
'(lisp-complete-symbol)))
3409 (let ((win (selected-window)))
3412 (org-table-show-reference)
3414 (select-window win
)))))
3416 (defun org-table-formula-to-user (s)
3417 "Convert a formula from internal to user representation."
3418 (if (eq org-table-use-standard-references t
)
3419 (org-table-convert-refs-to-an s
)
3422 (defun org-table-formula-from-user (s)
3423 "Convert a formula from user to internal representation."
3424 (if org-table-use-standard-references
3425 (org-table-convert-refs-to-rc s
)
3428 (defun org-table-convert-refs-to-rc (s)
3429 "Convert spreadsheet references from A7 to @7$28.
3430 Works for single references, but also for entire formulas and even the
3433 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3436 ;; format match, just advance
3437 (setq start
(match-end 0)))
3438 ((and (> (match-beginning 0) 0)
3439 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3440 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3441 ;; 3.e5 or something like this.
3442 (setq start
(match-end 0)))
3443 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3444 ;; (member (match-string 1 s)
3445 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3447 ;; function name, just advance
3448 (setq start
(match-end 0)))
3450 (setq start
(match-beginning 0)
3452 (if (equal (match-string 2 s
) "&")
3453 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3455 (string-to-number (match-string 2 s
))
3456 (org-letters-to-number (match-string 1 s
))))
3460 (defun org-table-convert-refs-to-an (s)
3461 "Convert spreadsheet references from to @7$28 to AB7.
3462 Works for single references, but also for entire formulas and even the
3464 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3465 (setq s
(replace-match
3467 (org-number-to-letters
3468 (string-to-number (match-string 2 s
)))
3469 (string-to-number (match-string 1 s
)))
3471 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3472 (setq s
(replace-match (concat "\\1"
3473 (org-number-to-letters
3474 (string-to-number (match-string 2 s
))) "&")
3478 (defun org-letters-to-number (s)
3479 "Convert a base 26 number represented by letters into an integer.
3480 For example: AB -> 28."
3483 (while (> (length s
) 0)
3484 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3488 (defun org-number-to-letters (n)
3489 "Convert an integer into a base 26 number represented by letters.
3490 For example: 28 -> AB."
3493 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3497 (defun org-table-time-string-to-seconds (s)
3498 "Convert a time string into numerical duration in seconds.
3499 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3500 If S is a string representing a number, keep this number."
3503 (let (hour minus min sec res
)
3505 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3506 (setq minus
(< 0 (length (match-string 1 s
)))
3507 hour
(string-to-number (match-string 2 s
))
3508 min
(string-to-number (match-string 3 s
))
3509 sec
(string-to-number (match-string 4 s
)))
3511 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3512 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3513 ((and (not (string-match org-ts-regexp-both s
))
3514 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3515 (setq minus
(< 0 (length (match-string 1 s
)))
3516 hour
(string-to-number (match-string 2 s
))
3517 min
(string-to-number (match-string 3 s
)))
3519 (setq res
(- (+ (* hour
3600) (* min
60))))
3520 (setq res
(+ (* hour
3600) (* min
60)))))
3521 (t (setq res
(string-to-number s
))))
3522 (number-to-string res
))))
3524 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3525 "Convert a number of seconds to a time string.
3526 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3527 minutes or seconds."
3528 (let* ((secs0 (abs secs
))
3530 (cond ((eq output-format
'days
)
3531 (format "%.3f" (/ (float secs0
) 86400)))
3532 ((eq output-format
'hours
)
3533 (format "%.2f" (/ (float secs0
) 3600)))
3534 ((eq output-format
'minutes
)
3535 (format "%.1f" (/ (float secs0
) 60)))
3536 ((eq output-format
'seconds
)
3537 (format "%d" secs0
))
3538 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3539 (if (< secs
0) (concat "-" res
) res
)))
3541 (defun org-table-fedit-convert-buffer (function)
3542 "Convert all references in this buffer, using FUNCTION."
3543 (let ((line (org-current-line)))
3544 (goto-char (point-min))
3546 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3547 (delete-region (point) (point-at-eol))
3548 (or (eobp) (forward-char 1)))
3549 (org-goto-line line
)))
3551 (defun org-table-fedit-toggle-ref-type ()
3552 "Convert all references in the buffer from B3 to @3$2 and back."
3554 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3555 (org-table-fedit-convert-buffer
3556 (if org-table-buffer-is-an
3557 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3558 (message "Reference type switched to %s"
3559 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3561 (defun org-table-fedit-ref-up ()
3562 "Shift the reference at point one row/hline up."
3564 (org-table-fedit-shift-reference 'up
))
3565 (defun org-table-fedit-ref-down ()
3566 "Shift the reference at point one row/hline down."
3568 (org-table-fedit-shift-reference 'down
))
3569 (defun org-table-fedit-ref-left ()
3570 "Shift the reference at point one field to the left."
3572 (org-table-fedit-shift-reference 'left
))
3573 (defun org-table-fedit-ref-right ()
3574 "Shift the reference at point one field to the right."
3576 (org-table-fedit-shift-reference 'right
))
3578 (defun org-table-fedit-shift-reference (dir)
3580 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3581 (if (memq dir
'(left right
))
3582 (org-rematch-and-replace 1 (eq dir
'left
))
3583 (user-error "Cannot shift reference in this direction")))
3584 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3585 ;; A B3-like reference
3586 (if (memq dir
'(up down
))
3587 (org-rematch-and-replace 2 (eq dir
'up
))
3588 (org-rematch-and-replace 1 (eq dir
'left
))))
3590 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3591 ;; An internal reference
3592 (if (memq dir
'(up down
))
3593 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3594 (org-rematch-and-replace 5 (eq dir
'left
))))))
3596 (defun org-rematch-and-replace (n &optional decr hline
)
3597 "Re-match the group N, and replace it with the shifted reference."
3598 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3599 (goto-char (match-beginning n
))
3600 (and (looking-at (regexp-quote (match-string n
)))
3601 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3604 (defun org-table-shift-refpart (ref &optional decr hline
)
3605 "Shift a reference part REF.
3606 If DECR is set, decrease the references row/column, else increase.
3607 If HLINE is set, this may be a hline reference, it certainly is not
3608 a translation reference."
3610 (let* ((sign (string-match "^[-+]" ref
)) n
)
3612 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3614 ((and hline
(string-match "^I+" ref
))
3615 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3616 (setq n
(+ n
(if decr -
1 1)))
3617 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3619 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3621 (concat sign
(make-string n ?I
)))
3623 ((string-match "^[0-9]+" ref
)
3624 (setq n
(string-to-number (concat sign ref
)))
3625 (setq n
(+ n
(if decr -
1 1)))
3627 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3628 (number-to-string (max 1 n
))))
3630 ((string-match "^[a-zA-Z]+" ref
)
3631 (org-number-to-letters
3632 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3634 (t (user-error "Cannot shift reference"))))))
3636 (defun org-table-fedit-toggle-coordinates ()
3637 "Toggle the display of coordinates in the referenced table."
3639 (let ((pos (marker-position org-pos
)))
3640 (with-current-buffer (marker-buffer org-pos
)
3643 (org-table-toggle-coordinate-overlays)))))
3645 (defun org-table-fedit-finish (&optional arg
)
3646 "Parse the buffer for formula definitions and install them.
3647 With prefix ARG, apply the new formulas to the table."
3649 (org-table-remove-rectangle-highlight)
3650 (if org-table-use-standard-references
3652 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3653 (setq org-table-buffer-is-an nil
)))
3654 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3655 (goto-char (point-min))
3656 (while (re-search-forward
3657 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3659 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3660 form
(match-string 3))
3661 (setq form
(org-trim form
))
3662 (when (not (equal form
""))
3663 (while (string-match "[ \t]*\n[ \t]*" form
)
3664 (setq form
(replace-match " " t t form
)))
3665 (when (assoc var eql
)
3666 (user-error "Double formulas for %s" var
))
3667 (push (cons var form
) eql
)))
3669 (set-window-configuration org-window-configuration
)
3670 (select-window sel-win
)
3672 (unless (org-at-table-p)
3673 (user-error "Lost table position - cannot install formulas"))
3674 (org-table-store-formulas eql
)
3675 (move-marker pos nil
)
3676 (kill-buffer "*Edit Formulas*")
3678 (org-table-recalculate 'all
)
3679 (message "New formulas installed - press C-u C-c C-c to apply."))))
3681 (defun org-table-fedit-abort ()
3682 "Abort editing formulas, without installing the changes."
3684 (org-table-remove-rectangle-highlight)
3685 (let ((pos org-pos
) (sel-win org-selected-window
))
3686 (set-window-configuration org-window-configuration
)
3687 (select-window sel-win
)
3689 (move-marker pos nil
)
3690 (message "Formula editing aborted without installing changes")))
3692 (defun org-table-fedit-lisp-indent ()
3693 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3695 (let ((pos (point)) beg end ind
)
3696 (beginning-of-line 1)
3698 ((looking-at "[ \t]")
3700 (call-interactively 'lisp-indent-line
))
3701 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3702 ((not (fboundp 'pp-buffer
))
3703 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3704 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3705 (goto-char (- (match-end 0) 2))
3707 (setq ind
(make-string (current-column) ?\
))
3708 (condition-case nil
(forward-sexp 1)
3710 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3713 (narrow-to-region beg end
)
3714 (if (eq last-command this-command
)
3716 (goto-char (point-min))
3717 (setq this-command nil
)
3718 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3719 (replace-match " ")))
3721 (untabify (point-min) (point-max))
3722 (goto-char (1+ (point-min)))
3723 (while (re-search-forward "^." nil t
)
3724 (beginning-of-line 1)
3726 (goto-char (point-max))
3727 (org-delete-backward-char 1)))
3731 (defvar org-show-positions nil
)
3733 (defun org-table-show-reference (&optional local
)
3734 "Show the location/value of the $ expression at point."
3736 (org-table-remove-rectangle-highlight)
3738 (let ((pos (if local
(point) org-pos
))
3740 (org-inhibit-highlight-removal t
)
3741 (win (selected-window))
3742 (org-show-positions nil
)
3743 var name e what match dest
)
3744 (if local
(org-table-get-specials))
3746 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3747 (setq match
(concat (substring (match-string 0) 0 -
1)
3749 (substring (match-string 0) 0 -
1)
3752 ((or (org-at-regexp-p org-table-range-regexp2
)
3753 (org-at-regexp-p org-table-translate-regexp
)
3754 (org-at-regexp-p org-table-range-regexp
))
3757 (org-table-convert-refs-to-rc (match-string 0))))
3759 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3760 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3762 (t (user-error "No reference at point")))
3763 match
(and what
(or match
(match-string 0))))
3764 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3765 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3766 'secondary-selection
))
3767 (org-add-hook 'before-change-functions
3768 'org-table-remove-rectangle-highlight
)
3769 (if (eq what
'name
) (setq var
(substring match
1)))
3770 (when (eq what
'range
)
3771 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3772 (setq match
(org-table-formula-substitute-names match
)))
3776 (re-search-backward "^\\S-" nil t
)
3777 (beginning-of-line 1)
3778 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3781 (org-table-convert-refs-to-rc (match-string 1))))
3782 (org-table-add-rectangle-overlay
3783 (match-beginning 1) (match-end 1) face2
))))
3784 (if (and (markerp pos
) (marker-buffer pos
))
3785 (if (get-buffer-window (marker-buffer pos
))
3786 (select-window (get-buffer-window (marker-buffer pos
)))
3787 (org-switch-to-buffer-other-window (get-buffer-window
3788 (marker-buffer pos
)))))
3790 (org-table-force-dataline)
3792 (setq name
(substring dest
1))
3794 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3795 (setq e
(assoc name org-table-named-field-locations
))
3796 (org-goto-line (nth 1 e
))
3797 (org-table-goto-column (nth 2 e
)))
3798 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3799 (let ((l (string-to-number (match-string 1 dest
)))
3800 (c (string-to-number (match-string 2 dest
))))
3801 (org-goto-line (aref org-table-dlines l
))
3802 (org-table-goto-column c
)))
3803 (t (org-table-goto-column (string-to-number name
))))
3804 (move-marker pos
(point))
3805 (org-table-highlight-rectangle nil nil face2
))
3807 ((equal dest match
))
3812 (org-table-get-range match nil nil
'highlight
))
3814 ((setq e
(assoc var org-table-named-field-locations
))
3815 (org-goto-line (nth 1 e
))
3816 (org-table-goto-column (nth 2 e
))
3817 (org-table-highlight-rectangle (point) (point))
3818 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3819 ((setq e
(assoc var org-table-column-names
))
3820 (org-table-goto-column (string-to-number (cdr e
)))
3821 (org-table-highlight-rectangle (point) (point))
3822 (goto-char (org-table-begin))
3823 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3826 (goto-char (match-beginning 1))
3827 (org-table-highlight-rectangle)
3828 (message "Named column (column %s)" (cdr e
)))
3829 (user-error "Column name not found")))
3832 (org-table-goto-column (string-to-number (substring match
1)))
3833 (org-table-highlight-rectangle (point) (point))
3834 (message "Column %s" (substring match
1)))
3835 ((setq e
(assoc var org-table-local-parameters
))
3836 (goto-char (org-table-begin))
3837 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3839 (goto-char (match-beginning 1))
3840 (org-table-highlight-rectangle)
3841 (message "Local parameter."))
3842 (user-error "Parameter not found")))
3845 ((not var
) (user-error "No reference at point"))
3846 ((setq e
(assoc var org-table-formula-constants-local
))
3847 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3849 ((setq e
(assoc var org-table-formula-constants
))
3850 (message "Constant: $%s=%s in `org-table-formula-constants'."
3852 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3853 (message "Constant: $%s=%s, from `constants.el'%s."
3854 var e
(format " (%s units)" constants-unit-system
)))
3855 (t (user-error "Undefined name $%s" var
)))))
3857 (when (and org-show-positions
3858 (not (memq this-command
'(org-table-fedit-scroll
3859 org-table-fedit-scroll-down
))))
3860 (push pos org-show-positions
)
3861 (push org-table-current-begin-pos org-show-positions
)
3862 (let ((min (apply 'min org-show-positions
))
3863 (max (apply 'max org-show-positions
)))
3864 (goto-char min
) (recenter 0)
3866 (or (pos-visible-in-window-p max
) (recenter -
1))))
3867 (select-window win
))))
3869 (defun org-table-force-dataline ()
3870 "Make sure the cursor is in a dataline in a table."
3871 (unless (save-excursion
3872 (beginning-of-line 1)
3873 (looking-at org-table-dataline-regexp
))
3874 (let* ((re org-table-dataline-regexp
)
3875 (p1 (save-excursion (re-search-forward re nil
'move
)))
3876 (p2 (save-excursion (re-search-backward re nil
'move
))))
3878 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3880 ((or p1 p2
) (goto-char (or p1 p2
)))
3881 (t (user-error "No table dataline around here"))))))
3883 (defun org-table-fedit-line-up ()
3884 "Move cursor one line up in the window showing the table."
3886 (org-table-fedit-move 'previous-line
))
3888 (defun org-table-fedit-line-down ()
3889 "Move cursor one line down in the window showing the table."
3891 (org-table-fedit-move 'next-line
))
3893 (defun org-table-fedit-move (command)
3894 "Move the cursor in the window showing the table.
3895 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3896 (let ((org-table-allow-automatic-line-recalculation nil
)
3897 (pos org-pos
) (win (selected-window)) p
)
3898 (select-window (get-buffer-window (marker-buffer org-pos
)))
3900 (call-interactively command
)
3901 (while (and (org-at-table-p)
3902 (org-at-table-hline-p))
3903 (call-interactively command
))
3904 (or (org-at-table-p) (goto-char p
))
3905 (move-marker pos
(point))
3906 (select-window win
)))
3908 (defun org-table-fedit-scroll (N)
3910 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3911 (scroll-other-window N
)))
3913 (defun org-table-fedit-scroll-down (N)
3915 (org-table-fedit-scroll (- N
)))
3917 (defvar org-table-rectangle-overlays nil
)
3919 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3920 "Add a new overlay."
3921 (let ((ov (make-overlay beg end
)))
3922 (overlay-put ov
'face
(or face
'secondary-selection
))
3923 (push ov org-table-rectangle-overlays
)))
3925 (defun org-table-highlight-rectangle (&optional beg end face
)
3926 "Highlight rectangular region in a table."
3927 (setq beg
(or beg
(point)) end
(or end
(point)))
3928 (let ((b (min beg end
))
3931 (and (boundp 'org-show-positions
)
3932 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3933 (goto-char (min beg end
))
3934 (setq l1
(org-current-line)
3935 c1
(org-table-current-column))
3936 (goto-char (max beg end
))
3937 (setq l2
(org-current-line)
3938 c2
(org-table-current-column))
3939 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3941 (beginning-of-line 1)
3942 (loop for line from l1 to l2 do
3943 (when (looking-at org-table-dataline-regexp
)
3944 (org-table-goto-column c1
)
3945 (skip-chars-backward "^|\n") (setq beg
(point))
3946 (org-table-goto-column c2
)
3947 (skip-chars-forward "^|\n") (setq end
(point))
3948 (org-table-add-rectangle-overlay beg end face
))
3949 (beginning-of-line 2))
3951 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3953 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3954 "Remove the rectangle overlays."
3955 (unless org-inhibit-highlight-removal
3956 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3957 (mapc 'delete-overlay org-table-rectangle-overlays
)
3958 (setq org-table-rectangle-overlays nil
)))
3960 (defvar org-table-coordinate-overlays nil
3961 "Collects the coordinate grid overlays, so that they can be removed.")
3962 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3964 (defun org-table-overlay-coordinates ()
3965 "Add overlays to the table at point, to show row/column coordinates."
3967 (mapc 'delete-overlay org-table-coordinate-overlays
)
3968 (setq org-table-coordinate-overlays nil
)
3970 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3971 (goto-char (org-table-begin))
3972 (while (org-at-table-p)
3973 (setq eol
(point-at-eol))
3974 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3975 (push ov org-table-coordinate-overlays
)
3976 (setq hline
(looking-at org-table-hline-regexp
))
3977 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3978 (format "%4d" (setq id
(1+ id
)))))
3979 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3982 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3983 (setq beg
(1+ (match-beginning 0))
3985 s1
(concat "$" (int-to-string ic
))
3986 s2
(org-number-to-letters ic
)
3987 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3988 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3989 (push ov org-table-coordinate-overlays
)
3990 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3991 (beginning-of-line 2)))))
3994 (defun org-table-toggle-coordinate-overlays ()
3995 "Toggle the display of Row/Column numbers in tables."
3997 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3998 (message "Tables Row/Column numbers display turned %s"
3999 (if org-table-overlay-coordinates
"on" "off"))
4000 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4002 (unless org-table-overlay-coordinates
4003 (mapc 'delete-overlay org-table-coordinate-overlays
)
4004 (setq org-table-coordinate-overlays nil
)))
4007 (defun org-table-toggle-formula-debugger ()
4008 "Toggle the formula debugger in tables."
4010 (setq org-table-formula-debug
(not org-table-formula-debug
))
4011 (message "Formula debugging has been turned %s"
4012 (if org-table-formula-debug
"on" "off")))
4014 ;;; The orgtbl minor mode
4016 ;; Define a minor mode which can be used in other modes in order to
4017 ;; integrate the org-mode table editor.
4019 ;; This is really a hack, because the org-mode table editor uses several
4020 ;; keys which normally belong to the major mode, for example the TAB and
4021 ;; RET keys. Here is how it works: The minor mode defines all the keys
4022 ;; necessary to operate the table editor, but wraps the commands into a
4023 ;; function which tests if the cursor is currently inside a table. If that
4024 ;; is the case, the table editor command is executed. However, when any of
4025 ;; those keys is used outside a table, the function uses `key-binding' to
4026 ;; look up if the key has an associated command in another currently active
4027 ;; keymap (minor modes, major mode, global), and executes that command.
4028 ;; There might be problems if any of the keys used by the table editor is
4029 ;; otherwise used as a prefix key.
4031 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4032 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4033 ;; addresses this by checking explicitly for both bindings.
4035 ;; The optimized version (see variable `orgtbl-optimized') takes over
4036 ;; all keys which are bound to `self-insert-command' in the *global map*.
4037 ;; Some modes bind other commands to simple characters, for example
4038 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4039 ;; active, this binding is ignored inside tables and replaced with a
4040 ;; modified self-insert.
4043 (defvar orgtbl-mode-map
(make-keymap)
4044 "Keymap for `orgtbl-mode'.")
4046 (defvar org-old-auto-fill-inhibit-regexp nil
4047 "Local variable used by `orgtbl-mode'.")
4049 (defconst orgtbl-line-start-regexp
4050 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4051 "Matches a line belonging to an orgtbl.")
4053 (defconst orgtbl-extra-font-lock-keywords
4054 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4055 0 (quote 'org-table
) 'prepend
))
4056 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4058 ;; Install it as a minor mode.
4059 (put 'orgtbl-mode
:included t
)
4060 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4063 (define-minor-mode orgtbl-mode
4064 "The `org-mode' table editor as a minor mode for use in other modes."
4065 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4066 (org-load-modules-maybe)
4068 ((derived-mode-p 'org-mode
)
4069 ;; Exit without error, in case some hook functions calls this
4070 ;; by accident in org-mode.
4071 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4073 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4074 ;; Make sure we are first in minor-mode-map-alist
4075 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4076 ;; FIXME: maybe it should use emulation-mode-map-alists?
4077 (and c
(setq minor-mode-map-alist
4078 (cons c
(delq c minor-mode-map-alist
)))))
4079 (org-set-local (quote org-table-may-need-update
) t
)
4080 (org-add-hook 'before-change-functions
'org-before-change-function
4082 (org-set-local 'org-old-auto-fill-inhibit-regexp
4083 auto-fill-inhibit-regexp
)
4084 (org-set-local 'auto-fill-inhibit-regexp
4085 (if auto-fill-inhibit-regexp
4086 (concat orgtbl-line-start-regexp
"\\|"
4087 auto-fill-inhibit-regexp
)
4088 orgtbl-line-start-regexp
))
4089 (add-to-invisibility-spec '(org-cwidth))
4090 (when (fboundp 'font-lock-add-keywords
)
4091 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4092 (org-restart-font-lock))
4093 (easy-menu-add orgtbl-mode-menu
))
4095 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4096 (org-table-cleanup-narrow-column-properties)
4097 (org-remove-from-invisibility-spec '(org-cwidth))
4098 (remove-hook 'before-change-functions
'org-before-change-function t
)
4099 (when (fboundp 'font-lock-remove-keywords
)
4100 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4101 (org-restart-font-lock))
4102 (easy-menu-remove orgtbl-mode-menu
)
4103 (force-mode-line-update 'all
))))
4105 (defun org-table-cleanup-narrow-column-properties ()
4106 "Remove all properties related to narrow-column invisibility."
4107 (let ((s (point-min)))
4108 (while (setq s
(text-property-any s
(point-max)
4109 'display org-narrow-column-arrow
))
4110 (remove-text-properties s
(1+ s
) '(display t
)))
4111 (setq s
(point-min))
4112 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4113 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4114 (setq s
(point-min))
4115 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4116 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4118 (defun orgtbl-make-binding (fun n
&rest keys
)
4119 "Create a function for binding in the table minor mode.
4120 FUN is the command to call inside a table. N is used to create a unique
4121 command name. KEYS are keys that should be checked in for a command
4122 to execute outside of tables."
4125 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4127 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4128 "Outside of tables, run the binding of `"
4129 (mapconcat #'key-description keys
"' or `")
4134 (list 'call-interactively
(list 'quote fun
))
4135 (list 'let
'(orgtbl-mode)
4136 (list 'call-interactively
4139 (list 'key-binding k
))
4141 '('orgtbl-error
))))))))
4143 (defun orgtbl-error ()
4144 "Error when there is no default binding for a table key."
4146 (user-error "This key has no function outside tables"))
4148 (defun orgtbl-setup ()
4149 "Setup orgtbl keymaps."
4152 '(([(meta shift left
)] org-table-delete-column
)
4153 ([(meta left
)] org-table-move-column-left
)
4154 ([(meta right
)] org-table-move-column-right
)
4155 ([(meta shift right
)] org-table-insert-column
)
4156 ([(meta shift up
)] org-table-kill-row
)
4157 ([(meta shift down
)] org-table-insert-row
)
4158 ([(meta up
)] org-table-move-row-up
)
4159 ([(meta down
)] org-table-move-row-down
)
4160 ("\C-c\C-w" org-table-cut-region
)
4161 ("\C-c\M-w" org-table-copy-region
)
4162 ("\C-c\C-y" org-table-paste-rectangle
)
4163 ("\C-c\C-w" org-table-wrap-region
)
4164 ("\C-c-" org-table-insert-hline
)
4165 ("\C-c}" org-table-toggle-coordinate-overlays
)
4166 ("\C-c{" org-table-toggle-formula-debugger
)
4167 ("\C-m" org-table-next-row
)
4168 ([(shift return
)] org-table-copy-down
)
4169 ("\C-c?" org-table-field-info
)
4170 ("\C-c " org-table-blank-field
)
4171 ("\C-c+" org-table-sum
)
4172 ("\C-c=" org-table-eval-formula
)
4173 ("\C-c'" org-table-edit-formulas
)
4174 ("\C-c`" org-table-edit-field
)
4175 ("\C-c*" org-table-recalculate
)
4176 ("\C-c^" org-table-sort-lines
)
4177 ("\M-a" org-table-beginning-of-field
)
4178 ("\M-e" org-table-end-of-field
)
4179 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4181 (while (setq elt
(pop bindings
))
4182 (setq nfunc
(1+ nfunc
))
4183 (setq key
(org-key (car elt
))
4185 cmd
(orgtbl-make-binding fun nfunc key
))
4186 (org-defkey orgtbl-mode-map key cmd
))
4188 ;; Special treatment needed for TAB and RET
4189 (org-defkey orgtbl-mode-map
[(return)]
4190 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4191 (org-defkey orgtbl-mode-map
"\C-m"
4192 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4194 (org-defkey orgtbl-mode-map
[(tab)]
4195 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4196 (org-defkey orgtbl-mode-map
"\C-i"
4197 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4199 (org-defkey orgtbl-mode-map
[(shift tab
)]
4200 (orgtbl-make-binding 'org-table-previous-field
104
4201 [(shift tab
)] [(tab)] "\C-i"))
4204 (unless (featurep 'xemacs
)
4205 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4206 (orgtbl-make-binding 'org-table-previous-field
107
4207 [S-iso-lefttab
] [backtab] [(shift tab)]
4210 (org-defkey orgtbl-mode-map [backtab]
4211 (orgtbl-make-binding 'org-table-previous-field
108
4212 [backtab] [S-iso-lefttab] [(shift tab)]
4215 (org-defkey orgtbl-mode-map "\M-\C-m"
4216 (orgtbl-make-binding 'org-table-wrap-region 105
4217 "\M-\C-m" [(meta return)]))
4218 (org-defkey orgtbl-mode-map [(meta return)]
4219 (orgtbl-make-binding 'org-table-wrap-region 106
4220 [(meta return)] "\M-\C-m"))
4222 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4223 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4225 (when orgtbl-optimized
4226 ;; If the user wants maximum table support, we need to hijack
4227 ;; some standard editing functions
4228 (org-remap orgtbl-mode-map
4229 'self-insert-command 'orgtbl-self-insert-command
4230 'delete-char 'org-delete-char
4231 'delete-backward-char 'org-delete-backward-char)
4232 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4233 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4235 ["Create or convert" org-table-create-or-convert-from-region
4236 :active (not (org-at-table-p)) :keys "C-c |" ]
4238 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4239 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4240 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4241 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4243 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4244 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4245 ["Copy Field from Above"
4246 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4249 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4250 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4251 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4252 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4254 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4255 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4256 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4257 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4258 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4260 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4262 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4263 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4264 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4265 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4268 ["Insert table template" orgtbl-insert-radio-table
4269 (assq major-mode orgtbl-radio-table-templates)]
4270 ["Comment/uncomment table" orgtbl-toggle-comment t])
4272 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4273 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4274 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4275 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4276 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4277 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4278 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4279 ["Sum Column/Rectangle" org-table-sum
4280 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4281 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4283 org-table-toggle-formula-debugger :active (org-at-table-p)
4285 :style toggle :selected org-table-formula-debug]
4286 ["Show Col/Row Numbers"
4287 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4289 :style toggle :selected org-table-overlay-coordinates]
4293 (defun orgtbl-ctrl-c-ctrl-c (arg)
4294 "If the cursor is inside a table, realign the table.
4295 If it is a table to be sent away to a receiver, do it.
4296 With prefix arg, also recompute table."
4298 (let ((case-fold-search t) (pos (point)) action)
4300 (beginning-of-line 1)
4302 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4303 ((looking-at "[ \t]*|") pos)
4304 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4308 (org-table-maybe-eval-formula)
4310 (call-interactively 'org-table-recalculate)
4311 (org-table-maybe-recalculate-line))
4312 (call-interactively 'org-table-align)
4313 (when (orgtbl-send-table 'maybe)
4314 (run-hooks 'orgtbl-after-send-table-hook)))
4315 ((eq action 'recalc)
4316 (org-table-set-constants)
4318 (beginning-of-line 1)
4319 (skip-chars-backward " \r\n\t")
4320 (if (org-at-table-p)
4321 (org-call-with-arg 'org-table-recalculate t))))
4322 (t (let (orgtbl-mode)
4323 (call-interactively (key-binding "\C-c\C-c")))))))
4325 (defun orgtbl-create-or-convert-from-region (arg)
4326 "Create table or convert region to table, if no conflicting binding.
4327 This installs the table binding `C-c |', but only if there is no
4328 conflicting binding to this key outside orgtbl-mode."
4330 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4332 (call-interactively cmd)
4333 (call-interactively 'org-table-create-or-convert-from-region))))
4335 (defun orgtbl-tab (arg)
4336 "Justification and field motion for `orgtbl-mode'."
4338 (if arg (org-table-edit-field t)
4339 (org-table-justify-field-maybe)
4340 (org-table-next-field)))
4342 (defun orgtbl-ret ()
4343 "Justification and field motion for `orgtbl-mode'."
4347 (org-table-justify-field-maybe)
4348 (org-table-next-row)))
4350 (defun orgtbl-self-insert-command (N)
4351 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4352 If the cursor is in a table looking at whitespace, the whitespace is
4353 overwritten, and the table is not marked as requiring realignment."
4355 (if (and (org-at-table-p)
4357 (and org-table-auto-blank-field
4358 (member last-command
4359 '(orgtbl-hijacker-command-100
4360 orgtbl-hijacker-command-101
4361 orgtbl-hijacker-command-102
4362 orgtbl-hijacker-command-103
4363 orgtbl-hijacker-command-104
4364 orgtbl-hijacker-command-105
4366 (org-table-blank-field))
4369 (looking-at "[^|\n]* +|"))
4370 (let (org-table-may-need-update)
4371 (goto-char (1- (match-end 0)))
4372 (org-delete-backward-char 1)
4373 (goto-char (match-beginning 0))
4374 (self-insert-command N))
4375 (setq org-table-may-need-update t)
4378 (cmd (or (key-binding
4379 (or (and (listp function-key-map)
4380 (setq a (assoc last-input-event function-key-map))
4382 (vector last-input-event)))
4383 'self-insert-command)))
4384 (call-interactively cmd)
4385 (if (and org-self-insert-cluster-for-undo
4386 (eq cmd 'self-insert-command))
4387 (if (not (eq last-command 'orgtbl-self-insert-command))
4388 (setq org-self-insert-command-undo-counter 1)
4389 (if (>= org-self-insert-command-undo-counter 20)
4390 (setq org-self-insert-command-undo-counter 1)
4391 (and (> org-self-insert-command-undo-counter 0)
4393 (not (cadr buffer-undo-list)) ; remove nil entry
4394 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4395 (setq org-self-insert-command-undo-counter
4396 (1+ org-self-insert-command-undo-counter))))))))
4398 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4399 "Regular expression matching exponentials as produced by calc.")
4401 (defun orgtbl-gather-send-defs ()
4402 "Gather a plist of :name, :transform, :params for each destination before
4405 (goto-char (org-table-begin))
4407 (beginning-of-line 0)
4408 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4409 (let ((name (org-no-properties (match-string 1)))
4410 (transform (intern (match-string 2)))
4411 (params (if (match-end 3)
4412 (read (concat "(" (match-string 3) ")")))))
4413 (push (list :name name :transform transform :params params)
4415 (beginning-of-line 0)))
4418 (defun orgtbl-send-replace-tbl (name txt)
4419 "Find and replace table NAME with TXT."
4421 (goto-char (point-min))
4422 (unless (re-search-forward
4423 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4424 (user-error "Don't know where to insert translated table"))
4425 (goto-char (match-beginning 0))
4426 (beginning-of-line 2)
4428 (let ((beg (point)))
4429 (unless (re-search-forward
4430 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4431 (user-error "Cannot find end of insertion region"))
4432 (beginning-of-line 1)
4433 (delete-region beg (point))))
4437 (defun org-table-to-lisp (&optional txt)
4438 "Convert the table at point to a Lisp structure.
4439 The structure will be a list. Each item is either the symbol `hline'
4440 for a horizontal separator line, or a list of field values as strings.
4441 The table is taken from the parameter TXT, or from the buffer at point."
4443 (unless (org-at-table-p)
4444 (user-error "No table at point")))
4446 (buffer-substring-no-properties (org-table-begin)
4448 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4452 (if (string-match org-table-hline-regexp x)
4454 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4457 (defun orgtbl-send-table (&optional maybe)
4458 "Send a transformed version of this table to the receiver position.
4459 With argument MAYBE, fail quietly if no transformation is defined for
4463 (unless (org-at-table-p) (user-error "Not at a table"))
4464 ;; when non-interactive, we assume align has just happened.
4465 (when (org-called-interactively-p 'any) (org-table-align))
4466 (let ((dests (orgtbl-gather-send-defs))
4467 (txt (buffer-substring-no-properties (org-table-begin)
4470 (unless dests (if maybe (throw 'exit nil)
4471 (user-error "Don't know how to transform this table")))
4472 (dolist (dest dests)
4473 (let* ((name (plist-get dest :name))
4474 (transform (plist-get dest :transform))
4475 (params (plist-get dest :params))
4476 (skip (plist-get params :skip))
4477 (skipcols (plist-get params :skipcols))
4478 (no-escape (plist-get params :no-escape))
4480 (lines (org-table-clean-before-export
4482 (org-split-string txt "[ \t]*\n[ \t]*"))))
4483 (i0 (if org-table-clean-did-remove-column 2 1))
4484 (lines (if no-escape lines
4485 (mapcar (lambda(l) (replace-regexp-in-string
4486 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4489 (if (string-match org-table-hline-regexp x)
4491 (org-remove-by-index
4492 (org-split-string (org-trim x) "\\s-*|\\s-*")
4495 (fun (if (= i0 2) 'cdr 'identity))
4496 (org-table-last-alignment
4497 (org-remove-by-index (funcall fun org-table-last-alignment)
4499 (org-table-last-column-widths
4500 (org-remove-by-index (funcall fun org-table-last-column-widths)
4502 (txt (if (fboundp transform)
4503 (funcall transform table params)
4504 (user-error "No such transformation function %s" transform))))
4505 (orgtbl-send-replace-tbl name txt))
4506 (setq ntbl (1+ ntbl)))
4507 (message "Table converted and installed at %d receiver location%s"
4508 ntbl (if (> ntbl 1) "s" ""))
4513 (defun org-remove-by-index (list indices &optional i0)
4514 "Remove the elements in LIST with indices in INDICES.
4515 First element has index 0, or I0 if given."
4518 (if (integerp indices) (setq indices (list indices)))
4519 (setq i0 (1- (or i0 0)))
4520 (delq :rm (mapcar (lambda (x)
4522 (if (memq i0 indices) :rm x))
4525 (defun orgtbl-toggle-comment ()
4526 "Comment or uncomment the orgtbl at point."
4528 (let* ((case-fold-search t)
4529 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4530 (re2 (concat "^" orgtbl-line-start-regexp))
4531 (commented (save-excursion (beginning-of-line 1)
4532 (cond ((looking-at re1) t)
4533 ((looking-at re2) nil)
4534 (t (user-error "Not at an org table")))))
4535 (re (if commented re1 re2))
4538 (beginning-of-line 1)
4539 (while (looking-at re) (beginning-of-line 0))
4540 (beginning-of-line 2)
4542 (while (looking-at re) (beginning-of-line 2))
4544 (comment-region beg end (if commented '(4) nil))))
4546 (defun orgtbl-insert-radio-table ()
4547 "Insert a radio table template appropriate for this major mode."
4549 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4552 (unless e (user-error "No radio table setup defined for %s" major-mode))
4553 (setq name (read-string "Table name: "))
4554 (while (string-match "%n" txt)
4555 (setq txt (replace-match name t t txt)))
4556 (or (bolp) (insert "\n"))
4561 ;; Dynamically bound input and output for table formatting.
4562 (defvar *orgtbl-table* nil
4563 "Carries the current table through formatting routines.")
4564 (defvar *orgtbl-rtn* nil
4565 "Formatting routines push the output lines here.")
4566 ;; Formatting parameters for the current table section.
4567 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4568 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4569 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4570 (defvar *orgtbl-fmt* nil "Format for each entry.")
4571 (defvar *orgtbl-efmt* nil "Format for numbers.")
4572 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4573 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4574 (defvar *orgtbl-lstart* nil "Text starting a row.")
4575 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4576 (defvar *orgtbl-lend* nil "Text ending a row.")
4577 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4579 (defsubst orgtbl-get-fmt (fmt i)
4580 "Retrieve the format from FMT corresponding to the Ith column."
4581 (if (and (not (functionp fmt)) (consp fmt))
4585 (defsubst orgtbl-apply-fmt (fmt &rest args)
4586 "Apply format FMT to arguments ARGS.
4587 When FMT is nil, return the first argument from ARGS."
4588 (cond ((functionp fmt) (apply fmt args))
4589 (fmt (apply 'format fmt args))
4593 (defsubst orgtbl-eval-str (str)
4594 "If STR is a function, evaluate it with no arguments."
4599 (defun orgtbl-format-line (line)
4600 "Format LINE as a table row."
4601 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4607 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4608 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4609 (orgtbl-apply-fmt efmt (match-string 1 f)
4612 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4613 *orgtbl-default-fmt*)
4616 (push (if *orgtbl-lfmt*
4617 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4618 (concat (orgtbl-eval-str *orgtbl-lstart*)
4619 (mapconcat 'identity line *orgtbl-sep*)
4620 (orgtbl-eval-str *orgtbl-lend*)))
4623 (defun orgtbl-format-section (section-stopper)
4624 "Format lines until the first occurrence of SECTION-STOPPER."
4627 (while (not (eq (car *orgtbl-table*) section-stopper))
4628 (if prevline (orgtbl-format-line prevline))
4629 (setq prevline (pop *orgtbl-table*)))
4630 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4631 (*orgtbl-lend* *orgtbl-llend*)
4632 (*orgtbl-lfmt* *orgtbl-llfmt*))
4633 (orgtbl-format-line prevline))))))
4636 (defun orgtbl-to-generic (table params &optional backend)
4637 "Convert the orgtbl-mode TABLE to some other format.
4638 This generic routine can be used for many standard cases.
4639 TABLE is a list, each entry either the symbol `hline' for a horizontal
4640 separator line, or a list of fields for that line.
4641 PARAMS is a property list of parameters that can influence the conversion.
4642 A third optional argument BACKEND can be used to convert the content of
4643 the cells using a specific export back-end.
4645 For the generic converter, some parameters are obligatory: you need to
4646 specify either :lfmt, or all of (:lstart :lend :sep).
4648 Valid parameters are:
4650 :splice When set to t, return only table body lines, don't wrap
4651 them into :tstart and :tend. Default is nil. When :splice
4652 is non-nil, this also means that the exporter should not look
4653 for and interpret header and footer sections.
4655 :hline String to be inserted on horizontal separation lines.
4656 May be nil to ignore hlines.
4658 :sep Separator between two fields
4659 :remove-nil-lines Do not include lines that evaluate to nil.
4661 Each in the following group may be either a string or a function
4662 of no arguments returning a string:
4664 :tstart String to start the table. Ignored when :splice is t.
4665 :tend String to end the table. Ignored when :splice is t.
4666 :lstart String to start a new table line.
4667 :llstart String to start the last table line, defaults to :lstart.
4668 :lend String to end a table line
4669 :llend String to end the last table line, defaults to :lend.
4671 Each in the following group may be a string, a function of one
4672 argument (the field or line) returning a string, or a plist
4673 mapping columns to either of the above:
4675 :lfmt Format for entire line, with enough %s to capture all fields.
4676 If this is present, :lstart, :lend, and :sep are ignored.
4677 :llfmt Format for the entire last line, defaults to :lfmt.
4678 :fmt A format to be used to wrap the field, should contain
4679 %s for the original field value. For example, to wrap
4680 everything in dollars, you could use :fmt \"$%s$\".
4681 This may also be a property list with column numbers and
4682 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4683 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4684 Same as above, specific for the header lines in the table.
4685 All lines before the first hline are treated as header.
4686 If any of these is not present, the data line value is used.
4688 This may be either a string or a function of two arguments:
4690 :efmt Use this format to print numbers with exponentials.
4691 The format should have %s twice for inserting mantissa
4692 and exponent, for example \"%s\\\\times10^{%s}\". This
4693 may also be a property list with column numbers and
4694 formats. :fmt will still be applied after :efmt.
4696 In addition to this, the parameters :skip and :skipcols are always handled
4697 directly by `orgtbl-send-table'. See manual."
4698 (let* ((splicep (plist-get params :splice))
4699 (hline (plist-get params :hline))
4700 (skipheadrule (plist-get params :skipheadrule))
4701 (remove-nil-linesp (plist-get params :remove-nil-lines))
4702 (remove-newlines (plist-get params :remove-newlines))
4703 (*orgtbl-hline* hline)
4704 (*orgtbl-table* table)
4705 (*orgtbl-sep* (plist-get params :sep))
4706 (*orgtbl-efmt* (plist-get params :efmt))
4707 (*orgtbl-lstart* (plist-get params :lstart))
4708 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4709 (*orgtbl-lend* (plist-get params :lend))
4710 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4711 (*orgtbl-lfmt* (plist-get params :lfmt))
4712 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4713 (*orgtbl-fmt* (plist-get params :fmt))
4715 ;; Convert cells content to backend BACKEND
4717 (setq *orgtbl-table*
4723 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4729 (when (plist-member params :tstart)
4730 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4731 (if tstart (push tstart *orgtbl-rtn*)))))
4732 ;; If we have a heading, format it and handle the trailing hline.
4733 (if (and (not splicep)
4734 (or (consp (car *orgtbl-table*))
4735 (consp (nth 1 *orgtbl-table*)))
4736 (memq 'hline (cdr *orgtbl-table*)))
4738 (when (eq 'hline (car *orgtbl-table*))
4739 ;; There is a hline before the first data line
4740 (and hline (push hline *orgtbl-rtn*))
4741 (pop *orgtbl-table*))
4742 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4744 (*orgtbl-llstart* (or (plist-get params :hllstart)
4746 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4747 (*orgtbl-llend* (or (plist-get params :hllend)
4748 (plist-get params :hlend) *orgtbl-llend*))
4749 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4750 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4751 (plist-get params :hlfmt) *orgtbl-llfmt*))
4752 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4753 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4754 (orgtbl-format-section 'hline))
4755 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4756 (pop *orgtbl-table*)))
4757 ;; Now format the main section.
4758 (orgtbl-format-section nil)
4760 (when (plist-member params :tend)
4761 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4762 (if tend (push tend *orgtbl-rtn*)))))
4763 (mapconcat (if remove-newlines
4765 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4767 (nreverse (if remove-nil-linesp
4768 (remq nil *orgtbl-rtn*)
4769 *orgtbl-rtn*)) "\n")))
4772 (defun orgtbl-to-tsv (table params)
4773 "Convert the orgtbl-mode table to TAB separated material."
4774 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4776 (defun orgtbl-to-csv (table params)
4777 "Convert the orgtbl-mode table to CSV material.
4778 This does take care of the proper quoting of fields with comma or quotes."
4779 (orgtbl-to-generic table (org-combine-plists
4780 '(:sep "," :fmt org-quote-csv-field)
4784 (defun orgtbl-to-latex (table params)
4785 "Convert the orgtbl-mode TABLE to LaTeX.
4786 TABLE is a list, each entry either the symbol `hline' for a horizontal
4787 separator line, or a list of fields for that line.
4788 PARAMS is a property list of parameters that can influence the conversion.
4789 Supports all parameters from `orgtbl-to-generic'. Most important for
4792 :splice When set to t, return only table body lines, don't wrap
4793 them into a tabular environment. Default is nil.
4795 :fmt A format to be used to wrap the field, should contain %s for the
4796 original field value. For example, to wrap everything in dollars,
4797 use :fmt \"$%s$\". This may also be a property list with column
4798 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4799 The format may also be a function that formats its one argument.
4801 :efmt Format for transforming numbers with exponentials. The format
4802 should have %s twice for inserting mantissa and exponent, for
4803 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4804 This may also be a property list with column numbers and formats.
4805 The format may also be a function that formats its two arguments.
4807 :llend If you find too much space below the last line of a table,
4808 pass a value of \"\" for :llend to suppress the final \\\\.
4810 The general parameters :skip and :skipcols have already been applied when
4811 this function is called."
4812 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4813 org-table-last-alignment ""))
4816 :tstart (concat "\\begin{tabular}{" alignment "}")
4817 :tend "\\end{tabular}"
4818 :lstart "" :lend " \\\\" :sep " & "
4819 :efmt "%s\\,(%s)" :hline "\\hline")))
4821 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4824 (defun orgtbl-to-html (table params)
4825 "Convert the orgtbl-mode TABLE to HTML.
4826 TABLE is a list, each entry either the symbol `hline' for a horizontal
4827 separator line, or a list of fields for that line.
4828 PARAMS is a property list of parameters that can influence the conversion.
4829 Currently this function recognizes the following parameters:
4831 :splice When set to t, return only table body lines, don't wrap
4832 them into a <table> environment. Default is nil.
4834 The general parameters :skip and :skipcols have already been applied when
4835 this function is called. The function does *not* use `orgtbl-to-generic',
4836 so you cannot specify parameters for it."
4838 (let ((output (org-export-string-as
4839 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4840 (if (not (plist-get params :splice)) output
4842 (replace-regexp-in-string
4843 "\\`<table .*>\n" ""
4844 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4847 (defun orgtbl-to-texinfo (table params)
4848 "Convert the orgtbl-mode TABLE to TeXInfo.
4849 TABLE is a list, each entry either the symbol `hline' for a horizontal
4850 separator line, or a list of fields for that line.
4851 PARAMS is a property list of parameters that can influence the conversion.
4852 Supports all parameters from `orgtbl-to-generic'. Most important for
4855 :splice nil/t When set to t, return only table body lines, don't wrap
4856 them into a multitable environment. Default is nil.
4858 :fmt fmt A format to be used to wrap the field, should contain
4859 %s for the original field value. For example, to wrap
4860 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4861 This may also be a property list with column numbers and
4862 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4863 Each format also may be a function that formats its one
4866 :cf \"f1 f2..\" The column fractions for the table. By default these
4867 are computed automatically from the width of the columns
4870 The general parameters :skip and :skipcols have already been applied when
4871 this function is called."
4872 (let* ((total (float (apply '+ org-table-last-column-widths)))
4873 (colfrac (or (plist-get params :cf)
4875 (lambda (x) (format "%.3f" (/ (float x) total)))
4876 org-table-last-column-widths " ")))
4879 :tstart (concat "@multitable @columnfractions " colfrac)
4880 :tend "@end multitable"
4881 :lstart "@item " :lend "" :sep " @tab "
4882 :hlstart "@headitem ")))
4883 (require 'ox-texinfo)
4884 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4887 (defun orgtbl-to-orgtbl (table params)
4888 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4889 Useful when slicing one table into many. The :hline, :sep,
4890 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4891 and :tend suppress strings without splicing; they can be set to
4892 provide ORGTBL directives for the generated table."
4896 :tstart nil :tend nil
4901 (params (org-combine-plists params2 params)))
4903 (insert (orgtbl-to-generic table params))
4904 (goto-char (point-min))
4905 (while (re-search-forward org-table-hline-regexp nil t)
4907 (buffer-substring 1 (buffer-size)))))
4909 (defun orgtbl-to-table.el (table params)
4910 "Convert the orgtbl-mode TABLE into a table.el table."
4912 (insert (orgtbl-to-orgtbl table params))
4914 (replace-regexp-in-string
4916 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4918 (defun orgtbl-to-unicode (table params)
4919 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4920 You need the ascii-art-to-unicode.el package for this. You can download
4921 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4923 (insert (orgtbl-to-table.el table params))
4924 (goto-char (point-min))
4925 (if (or (featurep 'ascii-art-to-unicode)
4926 (require 'ascii-art-to-unicode nil t))
4928 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4929 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4930 "Link to ascii-art-to-unicode.el") org-stored-links))
4931 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4934 (defun org-table-get-remote-range (name-or-id form)
4935 "Get a field value or a list of values in a range from table at ID.
4937 NAME-OR-ID may be the name of a table in the current file as set
4938 by a \"#+NAME:\" directive. The first table following this line
4939 will then be used. Alternatively, it may be an ID referring to
4940 any entry, also in a different file. In this case, the first
4941 table in that entry will be referenced.
4942 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4943 \"@I$2..@II$2\". All the references must be absolute, not relative.
4945 The return value is either a single string for a single field, or a
4946 list of the fields in the rectangle."
4948 (let ((case-fold-search t) (id-loc nil)
4949 ;; Protect a bunch of variables from being overwritten
4950 ;; by the context of the remote table
4951 org-table-column-names org-table-column-name-regexp
4952 org-table-local-parameters org-table-named-field-locations
4953 org-table-current-line-types org-table-current-begin-line
4954 org-table-current-begin-pos org-table-dlines
4955 org-table-current-ncol
4956 org-table-hlines org-table-last-alignment
4957 org-table-last-column-widths org-table-last-alignment
4958 org-table-last-column-widths tbeg
4960 (setq form (org-table-convert-refs-to-rc form))
4965 (goto-char (point-min))
4966 (if (re-search-forward
4967 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
4968 (regexp-quote name-or-id) "[ \t]*$")
4970 (setq buffer (current-buffer) loc (match-beginning 0))
4971 (setq id-loc (org-id-find name-or-id 'marker))
4972 (unless (and id-loc (markerp id-loc))
4973 (user-error "Can't find remote table \"%s\"" name-or-id))
4974 (setq buffer (marker-buffer id-loc)
4975 loc (marker-position id-loc))
4976 (move-marker id-loc nil)))
4977 (with-current-buffer buffer
4983 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4984 (not (match-beginning 1)))
4985 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
4986 (setq tbeg (point-at-bol))
4987 (org-table-get-specials)
4988 (setq form (org-table-formula-substitute-names
4989 (org-table-formula-handle-first/last-rc form)))
4990 (if (and (string-match org-table-range-regexp form)
4991 (> (length (match-string 0 form)) 1))
4993 (org-table-get-range (match-string 0 form) tbeg 1))
4996 (defmacro org-define-lookup-function (mode)
4997 (let ((mode-str (symbol-name mode))
4998 (first-p (equal mode 'first))
4999 (all-p (equal mode 'all)))
5000 (let ((plural-str (if all-p "s" "")))
5001 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5002 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5003 If R-LIST is nil, return matching element%s of S-LIST.
5004 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5005 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5006 This function is generated by a call to the macro `org-define-lookup-function'."
5007 mode-str plural-str plural-str plural-str)
5008 (let ,(let ((lvars '((p (or predicate 'equal))
5010 (rl (or r-list s-list))
5012 (if first-p (add-to-list 'lvars '(match-p nil)))
5014 (while ,(if first-p '(and (not match-p) sl) 'sl)
5016 (if (funcall p val (car sl))
5018 ,(if first-p '(setq match-p t))
5019 (let ((rval (car rl)))
5020 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5021 (setq sl (cdr sl) rl (cdr rl))))
5024 (org-define-lookup-function first)
5025 (org-define-lookup-function last)
5026 (org-define-lookup-function all)
5028 (provide 'org-table)
5031 ;; generated-autoload-file: "org-loaddefs.el"
5034 ;;; org-table.el ends here