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
)
918 (defun org-table-begin (&optional table-type
)
919 "Find the beginning of the table and return its position.
920 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
922 (if (not (re-search-backward
923 (if table-type org-table-any-border-regexp
924 org-table-border-regexp
)
926 (progn (goto-char (point-min)) (point))
927 (goto-char (match-beginning 0))
928 (beginning-of-line 2)
931 (defun org-table-end (&optional table-type
)
932 "Find the end of the table and return its position.
933 With argument TABLE-TYPE, go to the end of a table.el-type table."
935 (if (not (re-search-forward
936 (if table-type org-table-any-border-regexp
937 org-table-border-regexp
)
939 (goto-char (point-max))
940 (goto-char (match-beginning 0)))
944 (defun org-table-justify-field-maybe (&optional new
)
945 "Justify the current field, text to left, number to right.
946 Optional argument NEW may specify text to replace the current field content."
948 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
949 ((org-at-table-hline-p))
951 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
953 (< (point) org-table-aligned-begin-marker
)
954 (>= (point) org-table-aligned-end-marker
)))
955 ;; This is not the same table, force a full re-align
956 (setq org-table-may-need-update t
))
957 (t ;; realign the current field, based on previous full realign
958 (let* ((pos (point)) s
959 (col (org-table-current-column))
960 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
963 (skip-chars-backward "^|\n")
964 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
966 (setq s
(match-string 1)
968 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
969 e
(not (= (match-beginning 2) (match-end 2))))
970 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
971 l
(if e
"|" (setq org-table-may-need-update t
) ""))
974 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
975 (setq n
(format f new
))
976 (setq n
(concat new
"|") org-table-may-need-update t
)))
977 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
979 (let (org-table-may-need-update)
980 (replace-match n t t
))))
981 (setq org-table-may-need-update t
))
985 (defun org-table-next-field ()
986 "Go to the next field in the current table, creating new lines as needed.
987 Before doing so, re-align the table if necessary."
989 (org-table-maybe-eval-formula)
990 (org-table-maybe-recalculate-line)
991 (if (and org-table-automatic-realign
992 org-table-may-need-update
)
994 (let ((end (org-table-end)))
995 (if (org-at-table-hline-p)
999 (re-search-forward "|" end
)
1000 (if (looking-at "[ \t]*$")
1001 (re-search-forward "|" end
))
1002 (if (and (looking-at "-")
1003 org-table-tab-jumps-over-hlines
1004 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1005 (goto-char (match-beginning 1)))
1006 (if (looking-at "-")
1008 (beginning-of-line 0)
1009 (org-table-insert-row 'below
))
1010 (if (looking-at " ") (forward-char 1))))
1012 (org-table-insert-row 'below
)))))
1015 (defun org-table-previous-field ()
1016 "Go to the previous field in the table.
1017 Before doing so, re-align the table if necessary."
1019 (org-table-justify-field-maybe)
1020 (org-table-maybe-recalculate-line)
1021 (if (and org-table-automatic-realign
1022 org-table-may-need-update
)
1024 (if (org-at-table-hline-p)
1028 (re-search-backward "|" (org-table-begin))
1029 (re-search-backward "|" (org-table-begin)))
1030 (error (user-error "Cannot move to previous table field")))
1031 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1032 (re-search-backward "|" (org-table-begin)))
1033 (if (looking-at "| ?")
1034 (goto-char (match-end 0))))
1036 (defun org-table-beginning-of-field (&optional n
)
1037 "Move to the end of the current table field.
1038 If already at or after the end, move to the end of the next table field.
1039 With numeric argument N, move N-1 fields forward first."
1041 (let ((pos (point)))
1044 (org-table-previous-field))
1045 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1046 (user-error "No more table fields before the current")
1047 (goto-char (match-end 0))
1048 (and (looking-at " ") (forward-char 1)))
1049 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1051 (defun org-table-end-of-field (&optional n
)
1052 "Move to the beginning of the current table field.
1053 If already at or before the beginning, move to the beginning of the
1055 With numeric argument N, move N-1 fields backward first."
1057 (let ((pos (point)))
1060 (org-table-next-field))
1061 (when (re-search-forward "|" (point-at-eol 1) t
)
1063 (skip-chars-backward " ")
1064 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1066 (if (<= (point) pos
) (org-table-end-of-field 2))))
1069 (defun org-table-next-row ()
1070 "Go to the next row (same column) in the current table.
1071 Before doing so, re-align the table if necessary."
1073 (org-table-maybe-eval-formula)
1074 (org-table-maybe-recalculate-line)
1075 (if (or (looking-at "[ \t]*$")
1076 (save-excursion (skip-chars-backward " \t") (bolp)))
1078 (if (and org-table-automatic-realign
1079 org-table-may-need-update
)
1081 (let ((col (org-table-current-column)))
1082 (beginning-of-line 2)
1083 (if (or (not (org-at-table-p))
1084 (org-at-table-hline-p))
1086 (beginning-of-line 0)
1087 (org-table-insert-row 'below
)))
1088 (org-table-goto-column col
)
1089 (skip-chars-backward "^|\n\r")
1090 (if (looking-at " ") (forward-char 1)))))
1093 (defun org-table-copy-down (n)
1094 "Copy a field down in the current column.
1095 If the field at the cursor is empty, copy into it the content of
1096 the nearest non-empty field above. With argument N, use the Nth
1097 non-empty field. If the current field is not empty, it is copied
1098 down to the next row, and the cursor is moved with it.
1099 Therefore, repeating this command causes the column to be filled
1101 If the variable `org-table-copy-increment' is non-nil and the
1102 field is an integer or a timestamp, it will be incremented while
1103 copying. In the case of a timestamp, increment by one day."
1105 (let* ((colpos (org-table-current-column))
1106 (col (current-column))
1107 (field (save-excursion (org-table-get-field)))
1108 (non-empty (string-match "[^ \t]" field
))
1109 (beg (org-table-begin))
1112 (org-table-check-inside-data-field)
1115 (setq txt
(org-trim field
))
1116 (org-table-next-row)
1117 (org-table-blank-field))
1121 (while (progn (beginning-of-line 1)
1122 (re-search-backward org-table-dataline-regexp
1124 (org-table-goto-column colpos t
)
1125 (if (and (looking-at
1126 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1127 (<= (setq n
(1- n
)) 0))
1128 (throw 'exit
(match-string 1))))))))
1131 (if (and org-table-copy-increment
1132 (not (equal orig-n
0))
1133 (string-match "^[0-9]+$" txt
)
1134 (< (string-to-number txt
) 100000000))
1135 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1137 (org-move-to-column col
)
1138 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1139 (org-timestamp-up-day)
1140 (org-table-maybe-recalculate-line))
1142 (org-move-to-column col
))
1143 (user-error "No non-empty field found"))))
1145 (defun org-table-check-inside-data-field (&optional noerror
)
1146 "Is point inside a table data field?
1147 I.e. not on a hline or before the first or after the last column?
1148 This actually throws an error, so it aborts the current command."
1149 (if (or (not (org-at-table-p))
1150 (= (org-table-current-column) 0)
1151 (org-at-table-hline-p)
1152 (looking-at "[ \t]*$"))
1155 (user-error "Not in table data field"))
1158 (defvar org-table-clip nil
1159 "Clipboard for table regions.")
1161 (defun org-table-get (line column
)
1162 "Get the field in table line LINE, column COLUMN.
1163 If LINE is larger than the number of data lines in the table, the function
1164 returns nil. However, if COLUMN is too large, we will simply return an
1166 If LINE is nil, use the current line.
1167 If column is nil, use the current column."
1168 (setq column
(or column
(org-table-current-column)))
1170 (and (or (not line
) (org-table-goto-line line
))
1171 (org-trim (org-table-get-field column
)))))
1173 (defun org-table-put (line column value
&optional align
)
1174 "Put VALUE into line LINE, column COLUMN.
1175 When ALIGN is set, also realign the table."
1176 (setq column
(or column
(org-table-current-column)))
1177 (prog1 (save-excursion
1178 (and (or (not line
) (org-table-goto-line line
))
1179 (progn (org-table-goto-column column nil
'force
) t
)
1180 (org-table-get-field column value
)))
1181 (and align
(org-table-align))))
1183 (defun org-table-current-line ()
1184 "Return the index of the current data line."
1185 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1187 (goto-char (org-table-begin))
1188 (while (and (re-search-forward org-table-dataline-regexp end t
)
1190 (< (point-at-eol) pos
))))
1193 (defun org-table-goto-line (N)
1194 "Go to the Nth data line in the current table.
1195 Return t when the line exists, nil if it does not exist."
1196 (goto-char (org-table-begin))
1197 (let ((end (org-table-end)) (cnt 0))
1198 (while (and (re-search-forward org-table-dataline-regexp end t
)
1199 (< (setq cnt
(1+ cnt
)) N
)))
1202 (defun org-table-blank-field ()
1203 "Blank the current table field or active region."
1205 (org-table-check-inside-data-field)
1206 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1207 (let (org-table-clip)
1208 (org-table-cut-region (region-beginning) (region-end)))
1209 (skip-chars-backward "^|")
1211 (if (looking-at "|[^|\n]+")
1212 (let* ((pos (match-beginning 0))
1213 (match (match-string 0))
1214 (len (org-string-width match
)))
1215 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1216 (goto-char (+ 2 pos
))
1217 (substring match
1)))))
1219 (defun org-table-get-field (&optional n replace
)
1220 "Return the value of the field in column N of current row.
1221 N defaults to current field.
1222 If REPLACE is a string, replace field with this value. The return value
1223 is always the old value."
1224 (and n
(org-table-goto-column n
))
1225 (skip-chars-backward "^|\n")
1227 (if (looking-at "|[^|\r\n]*")
1228 (let* ((pos (match-beginning 0))
1229 (val (buffer-substring (1+ pos
) (match-end 0))))
1231 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1233 (goto-char (min (point-at-eol) (+ 2 pos
)))
1235 (forward-char 1) ""))
1238 (defun org-table-field-info (arg)
1239 "Show info about the current field, and highlight any reference at point."
1241 (org-table-get-specials)
1243 (let* ((pos (point))
1244 (col (org-table-current-column))
1245 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1246 (name (car (rassoc (list (org-current-line) col
)
1247 org-table-named-field-locations
)))
1248 (eql (org-table-expand-lhs-ranges
1251 (cons (org-table-formula-handle-first/last-rc
1253 (org-table-get-stored-formulas))))
1254 (dline (org-table-current-dline))
1255 (ref (format "@%d$%d" dline col
))
1256 (ref1 (org-table-convert-refs-to-an ref
))
1257 (fequation (or (assoc name eql
) (assoc ref eql
)))
1258 (cequation (assoc (int-to-string col
) eql
))
1259 (eqn (or fequation cequation
)))
1260 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1261 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1264 (org-table-show-reference 'local
)
1266 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1268 (if cname
(concat " or $" cname
) "")
1270 (if name
(concat " or $" name
) "")
1271 ;; FIXME: formula info not correct if special table line
1273 (concat ", formula: "
1274 (org-table-formula-to-user
1276 (if (string-match "^[$@]"(car eqn
)) "" "$")
1277 (car eqn
) "=" (cdr eqn
))))
1280 (defun org-table-current-column ()
1281 "Find out which column we are in."
1283 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1285 (let ((cnt 0) (pos (point)))
1286 (beginning-of-line 1)
1287 (while (search-forward "|" pos t
)
1288 (setq cnt
(1+ cnt
)))
1289 (when (org-called-interactively-p 'interactive
)
1290 (message "In table column %d" cnt
))
1294 (defun org-table-current-dline ()
1295 "Find out what table data line we are in.
1296 Only data lines count for this."
1298 (when (org-called-interactively-p 'any
)
1299 (org-table-check-inside-data-field))
1301 (let ((cnt 0) (pos (point)))
1302 (goto-char (org-table-begin))
1303 (while (<= (point) pos
)
1304 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1305 (beginning-of-line 2))
1306 (when (org-called-interactively-p 'any
)
1307 (message "This is table line %d" cnt
))
1311 (defun org-table-goto-column (n &optional on-delim force
)
1312 "Move the cursor to the Nth column in the current table line.
1313 With optional argument ON-DELIM, stop with point before the left delimiter
1315 If there are less than N fields, just go to after the last delimiter.
1316 However, when FORCE is non-nil, create new columns if necessary."
1318 (beginning-of-line 1)
1320 (while (and (> (setq n
(1- n
)) -
1)
1321 (or (search-forward "|" (point-at-eol) t
)
1323 (progn (end-of-line 1)
1324 (skip-chars-backward "^|")
1327 (when (and force
(not (looking-at ".*|")))
1328 (save-excursion (end-of-line 1) (insert " | ")))
1331 (if (looking-at " ") (forward-char 1)))))
1334 (defun org-table-insert-column ()
1335 "Insert a new column into the table."
1337 (if (not (org-at-table-p))
1338 (user-error "Not at a table"))
1339 (org-table-find-dataline)
1340 (let* ((col (max 1 (org-table-current-column)))
1341 (beg (org-table-begin))
1342 (end (org-table-end))
1343 ;; Current cursor position
1344 (linepos (org-current-line))
1347 (while (< (point) end
)
1348 (if (org-at-table-hline-p)
1350 (org-table-goto-column col t
)
1352 (beginning-of-line 2))
1353 (move-marker end nil
)
1354 (org-goto-line linepos
)
1355 (org-table-goto-column colpos
)
1357 (when (or (not org-table-fix-formulas-confirm
)
1358 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1359 (org-table-fix-formulas "$" nil
(1- col
) 1)
1360 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1362 (defun org-table-find-dataline ()
1363 "Find a data line in the current table, which is needed for column commands."
1364 (if (and (org-at-table-p)
1365 (not (org-at-table-hline-p)))
1367 (let ((col (current-column))
1368 (end (org-table-end)))
1369 (org-move-to-column col
)
1370 (while (and (< (point) end
)
1371 (or (not (= (current-column) col
))
1372 (org-at-table-hline-p)))
1373 (beginning-of-line 2)
1374 (org-move-to-column col
))
1375 (if (and (org-at-table-p)
1376 (not (org-at-table-hline-p)))
1379 "Please position cursor in a data line for column operations")))))
1381 (defun org-table-line-to-dline (line &optional above
)
1382 "Turn a buffer line number into a data line number.
1383 If there is no data line in this line, return nil.
1384 If there is no matching dline (most likely te reference was a hline), the
1385 first dline below it is used. When ABOVE is non-nil, the one above is used."
1387 (let ((ll (length org-table-dlines
))
1393 (if (<= (aref org-table-dlines i
) line
)
1398 (if (>= (aref org-table-dlines i
) line
)
1404 (defun org-table-delete-column ()
1405 "Delete a column from the table."
1407 (if (not (org-at-table-p))
1408 (user-error "Not at a table"))
1409 (org-table-find-dataline)
1410 (org-table-check-inside-data-field)
1411 (let* ((col (org-table-current-column))
1412 (beg (org-table-begin))
1413 (end (org-table-end))
1414 ;; Current cursor position
1415 (linepos (org-current-line))
1418 (while (< (point) end
)
1419 (if (org-at-table-hline-p)
1421 (org-table-goto-column col t
)
1422 (and (looking-at "|[^|\n]+|")
1423 (replace-match "|")))
1424 (beginning-of-line 2))
1425 (move-marker end nil
)
1426 (org-goto-line linepos
)
1427 (org-table-goto-column colpos
)
1429 (when (or (not org-table-fix-formulas-confirm
)
1430 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1431 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1433 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1437 (defun org-table-move-column-right ()
1438 "Move column to the right."
1440 (org-table-move-column nil
))
1442 (defun org-table-move-column-left ()
1443 "Move column to the left."
1445 (org-table-move-column 'left
))
1448 (defun org-table-move-column (&optional left
)
1449 "Move the current column to the right. With arg LEFT, move to the left."
1451 (if (not (org-at-table-p))
1452 (user-error "Not at a table"))
1453 (org-table-find-dataline)
1454 (org-table-check-inside-data-field)
1455 (let* ((col (org-table-current-column))
1456 (col1 (if left
(1- col
) col
))
1457 (beg (org-table-begin))
1458 (end (org-table-end))
1459 ;; Current cursor position
1460 (linepos (org-current-line))
1461 (colpos (if left
(1- col
) (1+ col
))))
1462 (if (and left
(= col
1))
1463 (user-error "Cannot move column further left"))
1464 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1465 (user-error "Cannot move column further right"))
1467 (while (< (point) end
)
1468 (if (org-at-table-hline-p)
1470 (org-table-goto-column col1 t
)
1471 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1472 (replace-match "|\\2|\\1|")))
1473 (beginning-of-line 2))
1474 (move-marker end nil
)
1475 (org-goto-line linepos
)
1476 (org-table-goto-column colpos
)
1478 (when (or (not org-table-fix-formulas-confirm
)
1479 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1480 (org-table-fix-formulas
1481 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1482 (cons (number-to-string colpos
) (number-to-string col
))))
1483 (org-table-fix-formulas
1484 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1485 (cons (number-to-string colpos
) (number-to-string col
)))))))
1488 (defun org-table-move-row-down ()
1489 "Move table row down."
1491 (org-table-move-row nil
))
1493 (defun org-table-move-row-up ()
1494 "Move table row up."
1496 (org-table-move-row 'up
))
1499 (defun org-table-move-row (&optional up
)
1500 "Move the current table line down. With arg UP, move it up."
1502 (let* ((col (current-column))
1504 (hline1p (save-excursion (beginning-of-line 1)
1505 (looking-at org-table-hline-regexp
)))
1506 (dline1 (org-table-current-dline))
1507 (dline2 (+ dline1
(if up -
1 1)))
1510 (beginning-of-line tonew
)
1511 (unless (org-at-table-p)
1513 (user-error "Cannot move row further"))
1514 (setq hline2p
(looking-at org-table-hline-regexp
))
1516 (beginning-of-line 1)
1518 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1519 (delete-region (point) (1+ (point-at-eol)))
1520 (beginning-of-line tonew
)
1522 (beginning-of-line 0)
1523 (org-move-to-column col
)
1524 (unless (or hline1p hline2p
1525 (not (or (not org-table-fix-formulas-confirm
)
1526 (funcall org-table-fix-formulas-confirm
1527 "Fix formulas? "))))
1528 (org-table-fix-formulas
1529 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1530 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1533 (defun org-table-insert-row (&optional arg
)
1534 "Insert a new row above the current line into the table.
1535 With prefix ARG, insert below the current line."
1537 (if (not (org-at-table-p))
1538 (user-error "Not at a table"))
1539 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1540 (new (org-table-clean-line line
)))
1541 ;; Fix the first field if necessary
1542 (if (string-match "^[ \t]*| *[#$] *|" line
)
1543 (setq new
(replace-match (match-string 0 line
) t t new
)))
1544 (beginning-of-line (if arg
2 1))
1545 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1546 (beginning-of-line 0)
1547 (re-search-forward "| ?" (point-at-eol) t
)
1548 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1550 (when (or (not org-table-fix-formulas-confirm
)
1551 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1552 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1555 (defun org-table-insert-hline (&optional above
)
1556 "Insert a horizontal-line below the current line into the table.
1557 With prefix ABOVE, insert above the current line."
1559 (if (not (org-at-table-p))
1560 (user-error "Not at a table"))
1561 (when (eobp) (insert "\n") (backward-char 1))
1562 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1564 (let ((line (org-table-clean-line
1565 (buffer-substring (point-at-bol) (point-at-eol))))
1566 (col (current-column)))
1567 (while (string-match "|\\( +\\)|" line
)
1568 (setq line
(replace-match
1569 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1570 ?-
) "|") t t line
)))
1571 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1572 (beginning-of-line (if above
1 2))
1574 (beginning-of-line (if above
1 -
1))
1575 (org-move-to-column col
)
1576 (and org-table-overlay-coordinates
(org-table-align))))
1579 (defun org-table-hline-and-move (&optional same-column
)
1580 "Insert a hline and move to the row below that line."
1582 (let ((col (org-table-current-column)))
1583 (org-table-maybe-eval-formula)
1584 (org-table-maybe-recalculate-line)
1585 (org-table-insert-hline)
1587 (if (looking-at "\n[ \t]*|-")
1588 (progn (insert "\n|") (org-table-align))
1589 (org-table-next-field))
1590 (if same-column
(org-table-goto-column col
))))
1592 (defun org-table-clean-line (s)
1593 "Convert a table line S into a string with only \"|\" and space.
1594 In particular, this does handle wide and invisible characters."
1595 (if (string-match "^[ \t]*|-" s
)
1596 ;; It's a hline, just map the characters
1597 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1598 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1599 (setq s
(replace-match
1600 (concat "|" (make-string (org-string-width (match-string 1 s
))
1606 (defun org-table-kill-row ()
1607 "Delete the current row or horizontal line from the table."
1609 (if (not (org-at-table-p))
1610 (user-error "Not at a table"))
1611 (let ((col (current-column))
1612 (dline (org-table-current-dline)))
1613 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1614 (if (not (org-at-table-p)) (beginning-of-line 0))
1615 (org-move-to-column col
)
1616 (when (or (not org-table-fix-formulas-confirm
)
1617 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1618 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1622 (defun org-table-sort-lines (with-case &optional sorting-type
)
1623 "Sort table lines according to the column at point.
1625 The position of point indicates the column to be used for
1626 sorting, and the range of lines is the range between the nearest
1627 horizontal separator lines, or the entire table of no such lines
1628 exist. If point is before the first column, you will be prompted
1629 for the sorting column. If there is an active region, the mark
1630 specifies the first line and the sorting column, while point
1631 should be in the last line to be included into the sorting.
1633 The command then prompts for the sorting type which can be
1634 alphabetically, numerically, or by time (as given in a time stamp
1635 in the field). Sorting in reverse order is also possible.
1637 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1639 If SORTING-TYPE is specified when this function is called from a Lisp
1640 program, no prompting will take place. SORTING-TYPE must be a character,
1641 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1642 should be done in reverse order."
1644 (let* ((thisline (org-current-line))
1645 (thiscol (org-table-current-column))
1646 (otc org-table-overlay-coordinates
)
1647 beg end bcol ecol tend tbeg column lns pos
)
1648 (when (equal thiscol
0)
1649 (if (org-called-interactively-p 'any
)
1652 (read-string "Use column N for sorting: ")))
1654 (org-table-goto-column thiscol
))
1655 (org-table-check-inside-data-field)
1656 (if (org-region-active-p)
1658 (setq beg
(region-beginning) end
(region-end))
1660 (setq column
(org-table-current-column)
1663 (setq end
(point-at-bol 2)))
1664 (setq column
(org-table-current-column)
1666 tbeg
(org-table-begin)
1667 tend
(org-table-end))
1668 (if (re-search-backward org-table-hline-regexp tbeg t
)
1669 (setq beg
(point-at-bol 2))
1671 (setq beg
(point-at-bol 1)))
1673 (if (re-search-forward org-table-hline-regexp tend t
)
1674 (setq end
(point-at-bol 1))
1676 (setq end
(point-at-bol))))
1677 (setq beg
(move-marker (make-marker) beg
)
1678 end
(move-marker (make-marker) end
))
1681 (org-table-goto-column column
)
1682 (skip-chars-backward "^|")
1683 (setq bcol
(current-column))
1684 (org-table-goto-column (1+ column
))
1685 (skip-chars-backward "^|")
1686 (setq ecol
(1- (current-column)))
1687 (org-table-goto-column column
)
1688 (setq lns
(mapcar (lambda(x) (cons
1689 (org-sort-remove-invisible
1691 (org-split-string x
"[ \t]*|[ \t]*")))
1693 (org-split-string (buffer-substring beg end
) "\n")))
1694 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1695 (when org-table-overlay-coordinates
1696 (org-table-toggle-coordinate-overlays))
1697 (delete-region beg end
)
1698 (move-marker beg nil
)
1699 (move-marker end nil
)
1700 (insert (mapconcat 'cdr lns
"\n") "\n")
1701 (org-goto-line thisline
)
1702 (org-table-goto-column thiscol
)
1703 (when otc
(org-table-toggle-coordinate-overlays))
1704 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1707 (defun org-table-cut-region (beg end
)
1708 "Copy region in table to the clipboard and blank all relevant fields.
1709 If there is no active region, use just the field at point."
1711 (if (org-region-active-p) (region-beginning) (point))
1712 (if (org-region-active-p) (region-end) (point))))
1713 (org-table-copy-region beg end
'cut
))
1716 (defun org-table-copy-region (beg end
&optional cut
)
1717 "Copy rectangular region in table to clipboard.
1718 A special clipboard is used which can only be accessed
1719 with `org-table-paste-rectangle'."
1721 (if (org-region-active-p) (region-beginning) (point))
1722 (if (org-region-active-p) (region-end) (point))
1723 current-prefix-arg
))
1724 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1726 (rpl (if cut
" " nil
)))
1728 (org-table-check-inside-data-field)
1729 (setq l01
(org-current-line)
1730 c01
(org-table-current-column))
1732 (org-table-check-inside-data-field)
1733 (setq l02
(org-current-line)
1734 c02
(org-table-current-column))
1735 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1736 c1
(min c01 c02
) c2
(max c01 c02
))
1740 (if (> l1 l2
) (throw 'exit t
))
1742 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1743 (setq cols nil ic1 c1 ic2 c2
)
1744 (while (< ic1
(1+ ic2
))
1745 (push (org-table-get-field ic1 rpl
) cols
)
1746 (setq ic1
(1+ ic1
)))
1747 (push (nreverse cols
) region
)
1748 (setq l1
(1+ l1
)))))
1749 (setq org-table-clip
(nreverse region
))
1750 (if cut
(org-table-align))
1754 (defun org-table-paste-rectangle ()
1755 "Paste a rectangular region into a table.
1756 The upper right corner ends up in the current field. All involved fields
1757 will be overwritten. If the rectangle does not fit into the present table,
1758 the table is enlarged as needed. The process ignores horizontal separator
1761 (unless (and org-table-clip
(listp org-table-clip
))
1762 (user-error "First cut/copy a region to paste!"))
1763 (org-table-check-inside-data-field)
1764 (let* ((clip org-table-clip
)
1765 (line (org-current-line))
1766 (col (org-table-current-column))
1767 (org-enable-table-editor t
)
1768 (org-table-automatic-realign nil
)
1770 (while (setq cols
(pop clip
))
1771 (while (org-at-table-hline-p) (beginning-of-line 2))
1772 (if (not (org-at-table-p))
1773 (progn (end-of-line 0) (org-table-next-field)))
1775 (while (setq field
(pop cols
))
1776 (org-table-goto-column c nil
'force
)
1777 (org-table-get-field nil field
)
1779 (beginning-of-line 2))
1780 (org-goto-line line
)
1781 (org-table-goto-column col
)
1785 (defun org-table-convert ()
1786 "Convert from `org-mode' table to table.el and back.
1787 Obviously, this only works within limits. When an Org-mode table is
1788 converted to table.el, all horizontal separator lines get lost, because
1789 table.el uses these as cell boundaries and has no notion of horizontal lines.
1790 A table.el table can be converted to an Org-mode table only if it does not
1791 do row or column spanning. Multiline cells will become multiple cells.
1792 Beware, Org-mode does not test if the table can be successfully converted - it
1793 blindly applies a recipe that works for simple tables."
1796 (if (org-at-table.el-p
)
1797 ;; convert to Org-mode table
1798 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1799 (end (move-marker (make-marker) (org-table-end t
))))
1800 (table-unrecognize-region beg end
)
1802 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1805 (if (org-at-table-p)
1806 ;; convert to table.el table
1807 (let ((beg (move-marker (make-marker) (org-table-begin)))
1808 (end (move-marker (make-marker) (org-table-end))))
1809 ;; first, get rid of all horizontal lines
1811 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1813 ;; insert a hline before first
1815 (org-table-insert-hline 'above
)
1816 (beginning-of-line -
1)
1817 ;; insert a hline after each line
1818 (while (progn (beginning-of-line 3) (< (point) end
))
1819 (org-table-insert-hline))
1821 (setq end
(move-marker end
(org-table-end)))
1822 ;; replace "+" at beginning and ending of hlines
1823 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1824 (replace-match "\\1+-"))
1826 (while (re-search-forward "-|[ \t]*$" end t
)
1827 (replace-match "-+"))
1830 (defun org-table-transpose-table-at-point ()
1831 "Transpose orgmode table at point and eliminate hlines.
1839 will be transposed as
1846 Note that horizontal lines disappeared."
1848 (let* ((table (delete 'hline
(org-table-to-lisp)))
1849 (contents (mapcar (lambda (p)
1855 (setq tp
(cdr tp
))))
1858 (delete-region (org-table-begin) (org-table-end))
1859 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1864 (defun org-table-wrap-region (arg)
1865 "Wrap several fields in a column like a paragraph.
1866 This is useful if you'd like to spread the contents of a field over several
1867 lines, in order to keep the table compact.
1869 If there is an active region, and both point and mark are in the same column,
1870 the text in the column is wrapped to minimum width for the given number of
1871 lines. Generally, this makes the table more compact. A prefix ARG may be
1872 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1873 formats the selected text to two lines. If the region was longer than two
1874 lines, the remaining lines remain empty. A negative prefix argument reduces
1875 the current number of lines by that amount. The wrapped text is pasted back
1876 into the table. If you formatted it to more lines than it was before, fields
1877 further down in the table get overwritten - so you might need to make space in
1880 If there is no region, the current field is split at the cursor position and
1881 the text fragment to the right of the cursor is prepended to the field one
1884 If there is no region, but you specify a prefix ARG, the current field gets
1885 blank, and the content is appended to the field above."
1887 (org-table-check-inside-data-field)
1888 (if (org-region-active-p)
1889 ;; There is a region: fill as a paragraph
1890 (let* ((beg (region-beginning))
1891 (cline (save-excursion (goto-char beg
) (org-current-line)))
1892 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1894 (org-table-cut-region (region-beginning) (region-end))
1895 (if (> (length (car org-table-clip
)) 1)
1896 (user-error "Region must be limited to single column"))
1897 (setq nlines
(if arg
1899 (+ (length org-table-clip
) arg
)
1901 (length org-table-clip
)))
1902 (setq org-table-clip
1903 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1905 (org-goto-line cline
)
1906 (org-table-goto-column ccol
)
1907 (org-table-paste-rectangle))
1908 ;; No region, split the current field at point
1909 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1910 (skip-chars-forward "^\r\n|"))
1912 ;; combine with field above
1913 (let ((s (org-table-blank-field))
1914 (col (org-table-current-column)))
1915 (beginning-of-line 0)
1916 (while (org-at-table-hline-p) (beginning-of-line 0))
1917 (org-table-goto-column col
)
1918 (skip-chars-forward "^|")
1919 (skip-chars-backward " ")
1920 (insert " " (org-trim s
))
1923 (if (looking-at "\\([^|]+\\)+|")
1924 (let ((s (match-string 1)))
1925 (replace-match " |")
1926 (goto-char (match-beginning 0))
1927 (org-table-next-row)
1928 (insert (org-trim s
) " ")
1930 (org-table-next-row)))))
1932 (defvar org-field-marker nil
)
1935 (defun org-table-edit-field (arg)
1936 "Edit table field in a different window.
1937 This is mainly useful for fields that contain hidden parts.
1938 When called with a \\[universal-argument] prefix, just make the full field visible so that
1939 it can be edited in place."
1943 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1945 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1946 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1947 (remove-text-properties b e
'(org-cwidth t invisible t
1948 display t intangible t
))
1949 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1950 (font-lock-fontify-block))))
1952 (let ((pos (point-marker))
1954 (if (eq org-table-use-standard-references t
)
1955 (concat (org-number-to-letters (org-table-current-column))
1956 (int-to-string (org-table-current-dline)))
1957 (concat "@" (int-to-string (org-table-current-dline))
1958 "$" (int-to-string (org-table-current-column)))))
1959 (field (org-table-get-field))
1960 (cw (current-window-configuration))
1963 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1964 (when (and (local-variable-p 'org-field-marker
)
1965 (markerp org-field-marker
))
1966 (move-marker org-field-marker nil
))
1968 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1969 (let ((org-inhibit-startup t
)) (org-mode))
1971 (setq truncate-lines nil
)
1973 (goto-char (setq p
(point-max)))
1974 (insert (org-trim field
))
1975 (remove-text-properties p
(point-max)
1976 '(invisible t org-cwidth t display t
1979 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1980 (org-set-local 'org-window-configuration cw
)
1981 (org-set-local 'org-field-marker pos
)
1982 (message "Edit and finish with C-c C-c")))))
1984 (defun org-table-finish-edit-field ()
1985 "Finish editing a table data field.
1986 Remove all newline characters, insert the result into the table, realign
1987 the table and kill the editing buffer."
1988 (let ((pos org-field-marker
)
1989 (cw org-window-configuration
)
1990 (cb (current-buffer))
1992 (goto-char (point-min))
1993 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1994 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1995 (replace-match " "))
1996 (setq text
(org-trim (buffer-string)))
1997 (set-window-configuration cw
)
1999 (select-window (get-buffer-window (marker-buffer pos
)))
2001 (move-marker pos nil
)
2002 (org-table-check-inside-data-field)
2003 (org-table-get-field nil text
)
2005 (message "New field value inserted")))
2007 (define-minor-mode org-table-follow-field-mode
2008 "Minor mode to make the table field editor window follow the cursor.
2009 When this mode is active, the field editor window will always show the
2010 current field. The mode exits automatically when the cursor leaves the
2011 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2012 nil
" TblFollow" nil
2013 (if org-table-follow-field-mode
2014 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2016 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2017 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2018 (win (and buf
(get-buffer-window buf
))))
2019 (when win
(delete-window win
))
2021 (with-current-buffer buf
2022 (move-marker org-field-marker nil
))
2023 (kill-buffer buf
)))))
2025 (defun org-table-follow-fields-with-editor ()
2026 (if (and org-table-exit-follow-field-mode-when-leaving-table
2027 (not (org-at-table-p)))
2028 ;; We have left the table, exit the follow mode
2029 (org-table-follow-field-mode -
1)
2030 (when (org-table-check-inside-data-field 'noerror
)
2031 (let ((win (selected-window)))
2032 (org-table-edit-field nil
)
2033 (org-fit-window-to-buffer)
2034 (select-window win
)))))
2036 (defvar org-timecnt
) ; dynamically scoped parameter
2039 (defun org-table-sum (&optional beg end nlast
)
2040 "Sum numbers in region of current table column.
2041 The result will be displayed in the echo area, and will be available
2042 as kill to be inserted with \\[yank].
2044 If there is an active region, it is interpreted as a rectangle and all
2045 numbers in that rectangle will be summed. If there is no active
2046 region and point is located in a table column, sum all numbers in that
2049 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2050 numbers are assumed to be times as well (in decimal hours) and the
2051 numbers are added as such.
2053 If NLAST is a number, only the NLAST fields will actually be summed."
2056 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2058 ((and beg end
)) ; beg and end given explicitly
2059 ((org-region-active-p)
2060 (setq beg
(region-beginning) end
(region-end)))
2062 (setq col
(org-table-current-column))
2063 (goto-char (org-table-begin))
2064 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2065 (user-error "No table data"))
2066 (org-table-goto-column col
)
2068 (goto-char (org-table-end))
2069 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2070 (user-error "No table data"))
2071 (org-table-goto-column col
)
2072 (setq end
(point))))
2073 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2074 (items1 (cond ((not nlast
) items
)
2075 ((>= nlast
(length items
)) items
)
2076 (t (setq items
(reverse items
))
2077 (setcdr (nthcdr (1- nlast
) items
) nil
)
2079 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2081 (res (apply '+ numbers
))
2082 (sres (if (= org-timecnt
0)
2083 (number-to-string res
)
2084 (setq diff
(* 3600 res
)
2085 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2086 m
(floor (/ diff
60)) diff
(mod diff
60)
2088 (format "%.0f:%02.0f:%02.0f" h m s
))))
2090 (if (org-called-interactively-p 'interactive
)
2092 (substitute-command-keys
2093 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2094 (length numbers
) sres
))))
2097 (defun org-table-get-number-for-summing (s)
2099 (if (string-match "^ *|? *" s
)
2100 (setq s
(replace-match "" nil nil s
)))
2101 (if (string-match " *|? *$" s
)
2102 (setq s
(replace-match "" nil nil s
)))
2103 (setq n
(string-to-number s
))
2105 ((and (string-match "0" s
)
2106 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2107 ((string-match "\\`[ \t]+\\'" s
) nil
)
2108 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2109 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2110 (m (string-to-number (or (match-string 2 s
) "0")))
2111 (s (string-to-number (or (match-string 4 s
) "0"))))
2112 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2113 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2117 (defun org-table-current-field-formula (&optional key noerror
)
2118 "Return the formula active for the current field.
2119 Assumes that specials are in place.
2120 If KEY is given, return the key to this formula.
2121 Otherwise return the formula preceded with \"=\" or \":=\"."
2122 (let* ((name (car (rassoc (list (org-current-line)
2123 (org-table-current-column))
2124 org-table-named-field-locations
)))
2125 (col (org-table-current-column))
2126 (scol (int-to-string col
))
2127 (ref (format "@%d$%d" (org-table-current-dline) col
))
2128 (stored-list (org-table-get-stored-formulas noerror
))
2129 (ass (or (assoc name stored-list
)
2130 (assoc ref stored-list
)
2131 (assoc scol stored-list
))))
2134 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2137 (defun org-table-get-formula (&optional equation named
)
2138 "Read a formula from the minibuffer, offer stored formula as default.
2139 When NAMED is non-nil, look for a named equation."
2140 (let* ((stored-list (org-table-get-stored-formulas))
2141 (name (car (rassoc (list (org-current-line)
2142 (org-table-current-column))
2143 org-table-named-field-locations
)))
2144 (ref (format "@%d$%d" (org-table-current-dline)
2145 (org-table-current-column)))
2146 (refass (assoc ref stored-list
))
2147 (nameass (assoc name stored-list
))
2149 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2152 (int-to-string (org-table-current-column))))
2153 (dummy (and (or nameass refass
) (not named
)
2154 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2155 (message "Formula not replaced")))
2156 (name (or name ref
))
2157 (org-table-may-need-update nil
)
2158 (stored (cdr (assoc scol stored-list
)))
2160 ((and stored equation
(string-match "^ *=? *$" equation
))
2164 (t (org-table-formula-from-user
2166 (org-table-formula-to-user
2167 (format "%s formula %s%s="
2168 (if named
"Field" "Column")
2169 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2171 (if stored
(org-table-formula-to-user stored
) "")
2172 'org-table-formula-history
2175 (when (not (string-match "\\S-" eq
))
2177 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2178 (org-table-store-formulas stored-list
)
2179 (user-error "Formula removed"))
2180 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2181 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2182 (if (and name
(not named
))
2183 ;; We set the column equation, delete the named one.
2184 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2187 (setcdr (assoc scol stored-list
) eq
)
2188 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2189 (if (or mustsave
(not (equal stored eq
)))
2190 (org-table-store-formulas stored-list
))
2193 (defun org-table-store-formulas (alist)
2194 "Store the list of formulas below the current table."
2195 (setq alist
(sort alist
'org-table-formula-less-p
))
2196 (let ((case-fold-search t
))
2198 (goto-char (org-table-end))
2199 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2201 ;; don't overwrite TBLFM, we might use text properties to store stuff
2202 (goto-char (match-beginning 3))
2203 (delete-region (match-beginning 3) (match-end 0)))
2205 (insert (or (match-string 2) "#+TBLFM:")))
2207 (mapconcat (lambda (x)
2209 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2210 (car x
) "=" (cdr x
)))
2214 (defsubst org-table-formula-make-cmp-string
(a)
2215 (when (string-match "\\`$[<>]" a
)
2216 (let ((arrow (string-to-char (substring a
1))))
2217 ;; Fake a high number to make sure this is sorted at the end.
2218 (setq a
(org-table-formula-handle-first/last-rc a
))
2219 (setq a
(format "$%d" (+ 10000
2220 (if (= arrow ?
<) -
1000 0)
2221 (string-to-number (substring a
1)))))))
2223 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2227 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2229 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2231 (concat "@@" (match-string 5 a
))))))
2233 (defun org-table-formula-less-p (a b
)
2234 "Compare two formulas for sorting."
2235 (let ((as (org-table-formula-make-cmp-string (car a
)))
2236 (bs (org-table-formula-make-cmp-string (car b
))))
2237 (and as bs
(string< as bs
))))
2240 (defun org-table-get-stored-formulas (&optional noerror
)
2241 "Return an alist with the stored formulas directly after current table."
2242 (interactive) ;; FIXME interactive?
2243 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2245 (goto-char (org-table-end))
2246 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2247 (setq strings
(org-split-string (org-match-string-no-properties 2)
2249 (while (setq string
(pop strings
))
2250 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2251 (setq scol
(if (match-end 2)
2252 (match-string 2 string
)
2253 (match-string 1 string
))
2254 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2255 (concat "$" scol
) scol
)
2256 eq
(match-string 3 string
)
2257 eq-alist
(cons (cons scol eq
) eq-alist
))
2258 (if (member scol seen
)
2261 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2264 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2265 (push scol seen
))))))
2266 (nreverse eq-alist
)))
2268 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2269 "Modify the equations after the table structure has been edited.
2270 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2271 For all numbers larger than LIMIT, shift them by DELTA."
2273 (goto-char (org-table-end))
2274 (when (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2275 (let ((msg "The formulas in #+TBLFM have been updated")
2276 (re (concat key
"\\([0-9]+\\)"))
2279 (if (or (equal key
"$") (equal key
"$LR"))
2280 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2281 (regexp-quote key
) remove
)
2282 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2285 (while (re-search-forward re2
(point-at-eol) t
)
2286 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2287 (if (equal (char-before (match-beginning 0)) ?.
)
2288 (user-error "Change makes TBLFM term %s invalid, use undo to recover"
2290 (replace-match "")))))
2291 (while (re-search-forward re
(point-at-eol) t
)
2292 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2293 (setq s
(match-string 1) n
(string-to-number s
))
2295 ((setq a
(assoc s replace
))
2296 (replace-match (concat key
(cdr a
)) t t
)
2298 ((and limit
(> n limit
))
2299 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2300 (message msg
)))))))))
2302 (defun org-table-get-specials ()
2303 "Get the column names and local parameters for this table."
2305 (let ((beg (org-table-begin)) (end (org-table-end))
2306 names name fields fields1 field cnt
2307 c v l line col types dlines hlines last-dline
)
2308 (setq org-table-column-names nil
2309 org-table-local-parameters nil
2310 org-table-named-field-locations nil
2311 org-table-current-begin-line nil
2312 org-table-current-begin-pos nil
2313 org-table-current-line-types nil
2314 org-table-current-ncol
0)
2316 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2317 (setq names
(org-split-string (match-string 1) " *| *")
2319 (while (setq name
(pop names
))
2321 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2322 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2323 (setq org-table-column-names
(nreverse org-table-column-names
))
2324 (setq org-table-column-name-regexp
2325 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2327 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2328 (setq fields
(org-split-string (match-string 1) " *| *"))
2329 (while (setq field
(pop fields
))
2330 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2331 (push (cons (match-string 1 field
) (match-string 2 field
))
2332 org-table-local-parameters
))))
2334 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2335 (setq c
(match-string 1)
2336 fields
(org-split-string (match-string 2) " *| *"))
2338 (beginning-of-line (if (equal c
"_") 2 0))
2339 (setq line
(org-current-line) col
1)
2340 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2341 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2342 (while (and fields1
(setq field
(pop fields
)))
2343 (setq v
(pop fields1
) col
(1+ col
))
2344 (when (and (stringp field
) (stringp v
)
2345 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2346 (push (cons field v
) org-table-local-parameters
)
2347 (push (list field line col
) org-table-named-field-locations
))))
2348 ;; Analyse the line types
2350 (setq org-table-current-begin-line
(org-current-line)
2351 org-table-current-begin-pos
(point)
2352 l org-table-current-begin-line
)
2353 (while (looking-at "[ \t]*|\\(-\\)?")
2354 (push (if (match-end 1) 'hline
'dline
) types
)
2355 (if (match-end 1) (push l hlines
) (push l dlines
))
2356 (beginning-of-line 2)
2358 (push 'hline types
) ;; add an imaginary extra hline to the end
2359 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2360 last-dline
(car dlines
)
2361 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2362 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2363 (org-goto-line last-dline
)
2364 (let* ((l last-dline
)
2365 (fields (org-split-string
2366 (buffer-substring (point-at-bol) (point-at-eol))
2368 (nfields (length fields
))
2370 (setq org-table-current-ncol nfields
)
2371 (loop for i from
1 to nfields do
2372 (push (list (format "LR%d" i
) l i
) al
)
2373 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2374 (setq org-table-named-field-locations
2375 (append org-table-named-field-locations al
))
2376 (setq org-table-local-parameters
2377 (append org-table-local-parameters al2
))))))
2380 (defun org-table-maybe-eval-formula ()
2381 "Check if the current field starts with \"=\" or \":=\".
2382 If yes, store the formula and apply it."
2383 ;; We already know we are in a table. Get field will only return a formula
2384 ;; when appropriate. It might return a separator line, but no problem.
2385 (when org-table-formula-evaluate-inline
2386 (let* ((field (org-trim (or (org-table-get-field) "")))
2388 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2389 (setq named
(equal (string-to-char field
) ?
:)
2390 eq
(match-string 1 field
))
2391 (if (or (fboundp 'calc-eval
)
2392 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2393 (org-table-eval-formula (if named
'(4) nil
)
2394 (org-table-formula-from-user eq
))
2395 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2397 (defvar org-recalc-commands nil
2398 "List of commands triggering the recalculation of a line.
2399 Will be filled automatically during use.")
2401 (defvar org-recalc-marks
2402 '((" " .
"Unmarked: no special line, no automatic recalculation")
2403 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2404 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2405 ("!" .
"Column name definition line. Reference in formula as $name.")
2406 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2407 ("_" .
"Names for values in row below this one.")
2408 ("^" .
"Names for values in row above this one.")))
2411 (defun org-table-rotate-recalc-marks (&optional newchar
)
2412 "Rotate the recalculation mark in the first column.
2413 If in any row, the first field is not consistent with a mark,
2414 insert a new column for the markers.
2415 When there is an active region, change all the lines in the region,
2416 after prompting for the marking character.
2417 After each change, a message will be displayed indicating the meaning
2420 (unless (org-at-table-p) (user-error "Not at a table"))
2421 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2422 (beg (org-table-begin))
2423 (end (org-table-end))
2424 (l (org-current-line))
2425 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2426 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2430 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2431 (col (org-table-current-column))
2432 (forcenew (car (assoc newchar org-recalc-marks
)))
2435 (message "Change region to what mark? Type # * ! $ or SPC: ")
2436 (setq newchar
(char-to-string (read-char-exclusive))
2437 forcenew
(car (assoc newchar org-recalc-marks
))))
2438 (if (and newchar
(not forcenew
))
2439 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2441 (if l1
(org-goto-line l1
))
2443 (beginning-of-line 1)
2444 (unless (looking-at org-table-dataline-regexp
)
2445 (user-error "Not at a table data line")))
2447 (org-table-goto-column 1)
2448 (org-table-insert-column)
2449 (org-table-goto-column (1+ col
)))
2450 (setq epos
(point-at-eol))
2452 (beginning-of-line 1)
2453 (org-table-get-field
2454 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2456 (setq new
(or forcenew
2457 (cadr (member (match-string 1) marks
))))
2463 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2464 (and (looking-at org-table-dataline-regexp
)
2465 (org-table-get-field 1 (concat " " new
" "))))
2466 (org-goto-line l1
)))
2467 (if (not (= epos
(point-at-eol))) (org-table-align))
2469 (and (org-called-interactively-p 'interactive
)
2470 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2473 (defun org-table-maybe-recalculate-line ()
2474 "Recompute the current line if marked for it, and if we haven't just done it."
2476 (and org-table-allow-automatic-line-recalculation
2477 (not (and (memq last-command org-recalc-commands
)
2478 (equal org-last-recalc-line
(org-current-line))))
2479 (save-excursion (beginning-of-line 1)
2480 (looking-at org-table-auto-recalculate-regexp
))
2481 (org-table-recalculate) t
))
2483 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2484 (defsubst org-set-calc-mode
(var &optional value
)
2486 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2487 ("R" calc-angle-mode rad
)
2488 ("F" calc-prefer-frac t
)
2489 ("S" calc-symbolic-mode t
)))
2490 value
(nth 2 var
) var
(nth 1 var
)))
2491 (if (memq var org-tbl-calc-modes
)
2492 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2493 (cons var
(cons value org-tbl-calc-modes
)))
2497 (defun org-table-eval-formula (&optional arg equation
2498 suppress-align suppress-const
2499 suppress-store suppress-analysis
)
2500 "Replace the table field value at the cursor by the result of a calculation.
2502 This function makes use of Dave Gillespie's Calc package, in my view the
2503 most exciting program ever written for GNU Emacs. So you need to have Calc
2504 installed in order to use this function.
2506 In a table, this command replaces the value in the current field with the
2507 result of a formula. It also installs the formula as the \"current\" column
2508 formula, by storing it in a special line below the table. When called
2509 with a `C-u' prefix, the current field must be a named field, and the
2510 formula is installed as valid in only this specific field.
2512 When called with two `C-u' prefixes, insert the active equation
2513 for the field back into the current field, so that it can be
2514 edited there. This is useful in order to use \\[org-table-show-reference]
2515 to check the referenced fields.
2517 When called, the command first prompts for a formula, which is read in
2518 the minibuffer. Previously entered formulas are available through the
2519 history list, and the last used formula is offered as a default.
2520 These stored formulas are adapted correctly when moving, inserting, or
2521 deleting columns with the corresponding commands.
2523 The formula can be any algebraic expression understood by the Calc package.
2524 For details, see the Org-mode manual.
2526 This function can also be called from Lisp programs and offers
2527 additional arguments: EQUATION can be the formula to apply. If this
2528 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2529 used to speed-up recursive calls by by-passing unnecessary aligns.
2530 SUPPRESS-CONST suppresses the interpretation of constants in the
2531 formula, assuming that this has been done already outside the function.
2532 SUPPRESS-STORE means the formula should not be stored, either because
2533 it is already stored, or because it is a modified equation that should
2534 not overwrite the stored one."
2536 (org-table-check-inside-data-field)
2537 (or suppress-analysis
(org-table-get-specials))
2538 (if (equal arg
'(16))
2539 (let ((eq (org-table-current-field-formula)))
2540 (or eq
(user-error "No equation active for current field"))
2541 (org-table-get-field nil eq
)
2543 (setq org-table-may-need-update t
))
2545 (ndown (if (integerp arg
) arg
1))
2546 (org-table-automatic-realign nil
)
2547 (case-fold-search nil
)
2549 (formula (if (and equation suppress-store
)
2551 (org-table-get-formula equation
(equal arg
'(4)))))
2552 (n0 (org-table-current-column))
2553 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2554 (numbers nil
) ; was a variable, now fixed default
2556 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2557 duration duration-output-format
)
2558 ;; Parse the format string. Since we have a lot of modes, this is
2559 ;; a lot of work. However, I think calc still uses most of the time.
2560 (if (string-match ";" formula
)
2561 (let ((tmp (org-split-string formula
";")))
2562 (setq formula
(car tmp
)
2563 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2565 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2566 (setq c
(string-to-char (match-string 1 fmt
))
2567 n
(string-to-number (match-string 2 fmt
)))
2569 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2570 (setq org-tbl-calc-modes
2573 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2574 (?s . sci
) (?e . eng
))))
2576 (setq fmt
(replace-match "" t t fmt
)))
2577 (if (string-match "T" fmt
)
2578 (setq duration t numbers t
2579 duration-output-format nil
2580 fmt
(replace-match "" t t fmt
)))
2581 (if (string-match "t" fmt
)
2583 duration-output-format org-table-duration-custom-format
2585 fmt
(replace-match "" t t fmt
)))
2586 (if (string-match "N" fmt
)
2588 fmt
(replace-match "" t t fmt
)))
2589 (if (string-match "L" fmt
)
2591 fmt
(replace-match "" t t fmt
)))
2592 (if (string-match "E" fmt
)
2594 fmt
(replace-match "" t t fmt
)))
2595 (while (string-match "[DRFS]" fmt
)
2596 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2597 (setq fmt
(replace-match "" t t fmt
)))
2598 (unless (string-match "\\S-" fmt
)
2600 (if (and (not suppress-const
) org-table-formula-use-constants
)
2601 (setq formula
(org-table-formula-substitute-names formula
)))
2602 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2604 (setq fields
(org-split-string
2605 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2607 ;; replace fields with duration values if relevant
2610 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2613 (setq fields
(mapcar
2615 (if (string-match "\\S-" x
)
2616 (number-to-string (string-to-number x
))
2619 (setq ndown
(1- ndown
))
2620 (setq form
(copy-sequence formula
)
2621 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2622 (if (and lispp literal
) (setq lispp
'literal
))
2624 ;; Insert row and column number of formula result field
2625 (while (string-match "[@$]#" form
)
2630 (if (equal (substring form
(match-beginning 0)
2631 (1+ (match-beginning 0)))
2633 (org-table-current-dline)
2634 (org-table-current-column))))
2637 ;; Check for old vertical references
2638 (setq form
(org-table-rewrite-old-row-references form
))
2639 ;; Insert remote references
2640 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2644 (org-table-make-reference
2645 (let ((rmtrng (org-table-get-remote-range
2646 (match-string 1 form
) (match-string 2 form
))))
2649 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2650 (org-table-time-string-to-seconds rmtrng
))
2652 keep-empty numbers lispp
))
2654 ;; Insert complex ranges
2655 (while (and (string-match org-table-range-regexp form
)
2656 (> (length (match-string 0 form
)) 1))
2657 (setq formrg
(save-match-data
2658 (org-table-get-range (match-string 0 form
) nil n0
)))
2661 (org-table-make-reference
2662 ;; possibly handle durations
2665 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2666 (org-table-time-string-to-seconds formrg
))
2668 keep-empty numbers lispp
)))
2669 (if (not (save-match-data
2670 (string-match (regexp-quote form
) formrpl
)))
2671 (setq form
(replace-match formrpl t t form
))
2672 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2673 ;; Insert simple ranges
2674 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2678 (org-table-make-reference
2680 fields
(string-to-number (match-string 1 form
))
2681 (string-to-number (match-string 2 form
)))
2682 keep-empty numbers lispp
))
2685 ;; Insert the references to fields in same row
2686 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2687 (setq n
(+ (string-to-number (match-string 1 form
))
2688 (if (match-end 2) n0
0))
2689 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2690 (unless x
(user-error "Invalid field specifier \"%s\""
2691 (match-string 0 form
)))
2692 (setq form
(replace-match
2694 (org-table-make-reference
2695 x keep-empty numbers lispp
))
2699 (setq ev
(condition-case nil
2700 (eval (eval (read form
)))
2702 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2703 ev
(if duration
(org-table-time-seconds-to-string
2704 (string-to-number ev
)
2705 duration-output-format
) ev
))
2706 (or (fboundp 'calc-eval
)
2707 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2708 ;; Use <...> time-stamps so that Calc can handle them
2709 (setq form
(replace-regexp-in-string org-ts-regexp3
"<\\1>" form
))
2710 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2711 (when (string-match org-ts-regexp2 form
)
2712 (let* ((ts (match-string 0 form
))
2713 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2714 (system-time-locale "C")
2715 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2716 (cdr org-time-stamp-formats
))
2717 (car org-time-stamp-formats
))))
2718 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2720 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2722 (calc-eval (cons form org-tbl-calc-modes
)
2723 (when (and (not keep-empty
) numbers
) 'num
)))
2724 ev
(if duration
(org-table-time-seconds-to-string
2725 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2726 (string-to-number (org-table-time-string-to-seconds ev
))
2727 (string-to-number ev
))
2728 duration-output-format
)
2731 (when org-table-formula-debug
2732 (with-output-to-temp-buffer "*Substitution History*"
2733 (princ (format "Substitution history of formula
2737 $1-> %s\n" orig formula form0 form
))
2739 (princ (format " %s^\nError: %s"
2740 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2741 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2743 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2744 (setq bw
(get-buffer-window "*Substitution History*"))
2745 (org-fit-window-to-buffer bw
)
2746 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2747 (unless (let (inhibit-redisplay)
2748 (y-or-n-p "Debugging Formula. Continue to next? "))
2750 (user-error "Abort"))
2753 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2754 (org-table-justify-field-maybe
2755 (format org-table-formula-field-format
2756 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2757 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2758 (call-interactively 'org-return
)
2760 (and down
(org-table-maybe-recalculate-line))
2761 (or suppress-align
(and org-table-may-need-update
2762 (org-table-align))))))
2764 (defun org-table-put-field-property (prop value
)
2766 (put-text-property (progn (skip-chars-backward "^|") (point))
2767 (progn (skip-chars-forward "^|") (point))
2770 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2771 "Get a calc vector from a column, according to descriptor DESC.
2772 Optional arguments TBEG and COL can give the beginning of the table and
2773 the current column, to avoid unnecessary parsing.
2775 HIGHLIGHT means just highlight the range.
2777 When CORNERS-ONLY is set, only return the corners of the range as
2778 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2779 in the buffer and column1 and column2 are table column numbers."
2780 (if (not (equal (string-to-char desc
) ?
@))
2781 (setq desc
(concat "@" desc
)))
2783 (or tbeg
(setq tbeg
(org-table-begin)))
2784 (or col
(setq col
(org-table-current-column)))
2785 (let ((thisline (org-current-line))
2786 beg end c1 c2 r1 r2 rangep tmp
)
2787 (unless (string-match org-table-range-regexp desc
)
2788 (user-error "Invalid table range specifier `%s'" desc
))
2789 (setq rangep
(match-end 3)
2790 r1
(and (match-end 1) (match-string 1 desc
))
2791 r2
(and (match-end 4) (match-string 4 desc
))
2792 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2793 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2795 (and c1
(setq c1
(+ (string-to-number c1
)
2796 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2797 (and c2
(setq c2
(+ (string-to-number c2
)
2798 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2799 (if (equal r1
"") (setq r1 nil
))
2800 (if (equal r2
"") (setq r2 nil
))
2801 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2802 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2803 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2804 (if (not r1
) (setq r1 thisline
))
2805 (if (not r2
) (setq r2 thisline
))
2806 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2807 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2808 (if (and (not corners-only
)
2809 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2813 (while (not (looking-at org-table-dataline-regexp
))
2814 (beginning-of-line 2))
2815 (prog1 (org-trim (org-table-get-field c1
))
2816 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2817 ;; A range, return a vector
2818 ;; First sort the numbers to get a regular rectangle
2819 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2820 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2822 ;; Only return the corners of the range
2824 ;; Copy the range values into a list
2826 (while (not (looking-at org-table-dataline-regexp
))
2827 (beginning-of-line 2))
2828 (org-table-goto-column c1
)
2831 (while (not (looking-at org-table-dataline-regexp
))
2832 (beginning-of-line 0))
2833 (org-table-goto-column c2
)
2836 (org-table-highlight-rectangle
2837 beg
(progn (skip-chars-forward "^|\n") (point))))
2838 ;; return string representation of calc vector
2840 (apply 'append
(org-table-copy-region beg end
))))))))
2842 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2843 "Analyze descriptor DESC and retrieve the corresponding line number.
2844 The cursor is currently in line CLINE, the table begins in line BLINE,
2845 and TABLE is a vector with line types."
2846 (if (string-match "^[0-9]+$" desc
)
2847 (aref org-table-dlines
(string-to-number desc
))
2848 (setq cline
(or cline
(org-current-line))
2849 bline
(or bline org-table-current-begin-line
)
2850 table
(or table org-table-current-line-types
))
2852 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2854 (and (not (match-end 3)) (not (match-end 6)))
2855 (and (match-end 3) (match-end 6) (not (match-end 5))))
2856 (user-error "Invalid row descriptor `%s'" desc
))
2857 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2858 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2859 (odir (and (match-end 5) (match-string 5 desc
)))
2860 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2862 (rel (and (match-end 6)
2863 (or (and (match-end 1) (not (match-end 3)))
2865 (if (and hn
(not hdir
))
2868 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2869 (if (and (not hn
) on
(not odir
))
2870 (user-error "Should never happen");;(aref org-table-dlines on)
2871 (if (and hn
(> hn
0))
2872 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2873 nil hn cline desc
)))
2875 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2876 rel on cline desc
)))
2879 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2880 "FIXME: Needs more documentation."
2881 (let ((l (length table
)))
2883 (while (and (setq i
(+ i
(if backwards -
1 1)))
2885 (not (eq (aref table i
) type
))
2886 (if (and relative
(eq (aref table i
) 'hline
))
2888 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2889 ((eq org-table-relative-ref-may-cross-hline
'error
)
2890 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
2891 (t (setq i
(- i
(if backwards -
1 1))
2896 (if (or (< i
0) (>= i l
))
2897 (user-error "Row descriptor %s used in line %d leads outside table"
2901 (defun org-table-rewrite-old-row-references (s)
2902 (if (string-match "&[-+0-9I]" s
)
2903 (user-error "Formula contains old &row reference, please rewrite using @-syntax")
2906 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2907 "Convert list ELEMENTS to something appropriate to insert into formula.
2908 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2909 NUMBERS indicates that everything should be converted to numbers.
2910 LISPP non-nil means to return something appropriate for a Lisp
2911 list, 'literal is for the format specifier L."
2912 ;; Calc nan (not a number) is used for the conversion of the empty
2913 ;; field to a reference for several reasons: (i) It is accepted in a
2914 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2915 ;; (ii) In a single field (not in range) it can be distinguished
2916 ;; from "(nan)" which is the reference made from a single field
2917 ;; containing "nan".
2918 (if (stringp elements
)
2921 (if (eq lispp
'literal
)
2923 (if (and (eq elements
"") (not keep-empty
))
2926 (if numbers
(string-to-number elements
) elements
))))
2927 (if (string-match "\\S-" elements
)
2929 (when numbers
(setq elements
(number-to-string
2930 (string-to-number elements
))))
2931 (concat "(" elements
")"))
2932 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2937 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2939 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
2943 (if (eq lispp
'literal
)
2945 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2947 (concat "[" (mapconcat
2949 (if (string-match "\\S-" x
)
2951 (number-to-string (string-to-number x
))
2953 (if (or (not keep-empty
) numbers
) "0" "nan")))
2958 (defun org-table-set-constants ()
2959 "Set `org-table-formula-constants-local' in the current buffer."
2960 (let (cst consts const-str
)
2962 (goto-char (point-min))
2963 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t
)
2964 (setq const-str
(substring-no-properties (match-string 1)))
2965 (setq consts
(append consts
(org-split-string const-str
"[ \t]+")))
2968 (while (setq e
(pop consts
))
2969 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
2970 (if (assoc-string (match-string 1 e
) cst
)
2971 (setq cst
(delete (assoc-string (match-string 1 e
) cst
) cst
)))
2972 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
2973 (setq org-table-formula-constants-local cst
)))))))
2976 (defun org-table-recalculate (&optional all noalign
)
2977 "Recalculate the current table line by applying all stored formulas.
2978 With prefix arg ALL, do this for all lines in the table.
2979 With the prefix argument ALL is `(16)' \
2980 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2981 it is the symbol `iterate', recompute the table until it no longer changes.
2982 If NOALIGN is not nil, do not re-align the table after the computations
2983 are done. This is typically used internally to save time, if it is
2984 known that the table will be realigned a little later anyway."
2986 (or (memq this-command org-recalc-commands
)
2987 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2988 (unless (org-at-table-p) (user-error "Not at a table"))
2989 (if (or (eq all
'iterate
) (equal all
'(16)))
2991 (org-table-get-specials)
2992 (let* ((eqlist (sort (org-table-get-stored-formulas)
2993 (lambda (a b
) (string< (car a
) (car b
)))))
2994 (eqlist1 (copy-sequence eqlist
))
2995 (inhibit-redisplay (not debug-on-error
))
2996 (line-re org-table-dataline-regexp
)
2997 (thisline (org-current-line))
2998 (thiscol (org-table-current-column))
3000 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3001 ;; Insert constants in all formulas
3004 (when (string-match "\\`$[<>]" (car x
))
3006 (setq x
(cons (substring
3007 (org-table-formula-handle-first/last-rc
3010 (if (assoc (car x
) eqlist1
)
3011 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3014 (org-table-formula-handle-first/last-rc
(car x
))
3015 (org-table-formula-substitute-names
3016 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3018 ;; Split the equation list
3019 (while (setq eq
(pop eqlist
))
3020 (if (<= (string-to-char (car eq
)) ?
9)
3023 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3024 ;; Expand ranges in lhs of formulas
3025 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3027 ;; Get the correct line range to process
3030 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3031 (goto-char (setq beg
(org-table-begin)))
3032 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3033 ;; This is a table with marked lines, compute selected lines
3034 (setq line-re org-table-recalculate-regexp
)
3035 ;; Move forward to the first non-header line
3036 (if (and (re-search-forward org-table-dataline-regexp end t
)
3037 (re-search-forward org-table-hline-regexp end t
)
3038 (re-search-forward org-table-dataline-regexp end t
))
3039 (setq beg
(match-beginning 0))
3040 nil
))) ;; just leave beg where it is
3041 (setq beg
(point-at-bol)
3042 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3044 (and all
(message "Re-applying formulas to full table..."))
3046 ;; First find the named fields, and mark them untouchable.
3047 ;; Also check if several field/range formulas try to set the same field.
3048 (remove-text-properties beg end
'(org-untouchable t
))
3049 (while (setq eq
(pop eqlname
))
3051 a
(assoc name org-table-named-field-locations
))
3053 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3055 (when (member name1 seen-fields
)
3056 (user-error "Several field/range formulas try to set %s" name1
))
3057 (push name1 seen-fields
)
3060 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3063 (aref org-table-dlines
3064 (string-to-number (match-string 1 name
)))
3065 (error (user-error "Invalid row number in %s"
3067 (string-to-number (match-string 2 name
)))))
3068 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3069 (message "Re-applying formula to field: %s" name
)
3070 (org-goto-line (nth 1 a
))
3071 (org-table-goto-column (nth 2 a
))
3072 (push (append a
(list (cdr eq
))) eqlname1
)
3073 (org-table-put-field-property :org-untouchable t
)))
3074 (setq eqlname1
(nreverse eqlname1
))
3076 ;; Now evaluate the column formulas, but skip fields covered by
3079 (while (re-search-forward line-re end t
)
3080 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3081 ;; Unprotected line, recalculate
3082 (and all
(message "Re-applying formulas to full table...(line %d)"
3083 (setq cnt
(1+ cnt
))))
3084 (setq org-last-recalc-line
(org-current-line))
3086 (while (setq entry
(pop eql
))
3087 (org-goto-line org-last-recalc-line
)
3088 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3089 (unless (get-text-property (point) :org-untouchable
)
3090 (org-table-eval-formula nil
(cdr entry
)
3091 'noalign
'nocst
'nostore
'noanalysis
)))))
3093 ;; Now evaluate the field formulas
3094 (while (setq eq
(pop eqlname1
))
3095 (message "Re-applying formula to field: %s" (car eq
))
3096 (org-goto-line (nth 1 eq
))
3097 (org-table-goto-column (nth 2 eq
))
3098 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3099 'nostore
'noanalysis
))
3101 (org-goto-line thisline
)
3102 (org-table-goto-column thiscol
)
3103 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3104 (or noalign
(and org-table-may-need-update
(org-table-align))
3105 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3107 ;; back to initial position
3108 (message "Re-applying formulas...done")
3109 (org-goto-line thisline
)
3110 (org-table-goto-column thiscol
)
3111 (or noalign
(and org-table-may-need-update
(org-table-align))
3112 (and all
(message "Re-applying formulas...done"))))))
3115 (defun org-table-iterate (&optional arg
)
3116 "Recalculate the table until it does not change anymore.
3117 The maximum number of iterations is 10, but you can choose a different value
3118 with the prefix ARG."
3120 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3122 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3127 (org-table-recalculate 'all
)
3128 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3129 (if (not (string= lasttbl thistbl
))
3130 (setq lasttbl thistbl
)
3132 (message "Convergence after %d iterations" i
)
3133 (message "Table was already stable"))
3135 (user-error "No convergence after %d iterations" i
))))
3138 (defun org-table-recalculate-buffer-tables ()
3139 "Recalculate all tables in the current buffer."
3144 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3147 (defun org-table-iterate-buffer-tables ()
3148 "Iterate all tables in the buffer, to converge inter-table dependencies."
3152 (checksum (md5 (buffer-string)))
3160 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3161 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3163 (message "Convergence after %d iterations" (- imax i
))
3165 (setq checksum c1
)))
3166 (user-error "No convergence after %d iterations" imax
))))))
3168 (defun org-table-calc-current-TBLFM (&optional arg
)
3169 "Apply the #+TBLFM in the line at point to the table."
3171 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3172 (let ((formula (buffer-substring
3177 ;; Insert a temporary formula at right after the table
3178 (goto-char (org-table-TBLFM-begin))
3179 (setq s
(set-marker (make-marker) (point)))
3180 (insert (concat formula
"\n"))
3181 (setq e
(set-marker (make-marker) (point)))
3182 ;; Recalculate the table
3183 (beginning-of-line 0) ; move to the inserted line
3184 (skip-chars-backward " \r\n\t")
3185 (if (org-at-table-p)
3187 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3188 ;; delete the formula inserted temporarily
3189 (delete-region s e
))))))
3191 (defun org-table-TBLFM-begin ()
3192 "Find the beginning of the TBLFM lines and return its position.
3193 Return nil when the beginning of TBLFM line was not found."
3195 (when (progn (forward-line 1)
3197 org-table-TBLFM-begin-regexp
3201 (defun org-table-expand-lhs-ranges (equations)
3202 "Expand list of formulas.
3203 If some of the RHS in the formulas are ranges or a row reference, expand
3204 them to individual field equations for each field."
3205 (let (e res lhs rhs range r1 r2 c1 c2
)
3206 (while (setq e
(pop equations
))
3207 (setq lhs
(car e
) rhs
(cdr e
))
3209 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3210 ;; This just refers to one fixed field
3212 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3213 ;; This just refers to one fixed named field
3215 ((string-match "^@[0-9]+$" lhs
)
3216 (loop for ic from
1 to org-table-current-ncol do
3217 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3218 (put-text-property 0 (length (caar res
))
3219 :orig-eqn e
(caar res
))))
3221 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3223 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3224 r2
(nth 2 range
) c2
(nth 3 range
))
3225 (setq r1
(org-table-line-to-dline r1
))
3226 (setq r2
(org-table-line-to-dline r2
'above
))
3227 (loop for ir from r1 to r2 do
3228 (loop for ic from c1 to c2 do
3229 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3230 (put-text-property 0 (length (caar res
))
3231 :orig-eqn e
(caar res
)))))))
3234 (defun org-table-formula-handle-first/last-rc
(s)
3235 "Replace @<, @>, $<, $> with first/last row/column of the table.
3236 So @< and $< will always be replaced with @1 and $1, respectively.
3237 The advantage of these special markers are that structure editing of
3238 the table will not change them, while @1 and $1 will be modified
3239 when a line/row is swapped out of that privileged position. So for
3240 formulas that use a range of rows or columns, it may often be better
3241 to anchor the formula with \"I\" row markers, or to offset from the
3242 borders of the table using the @< @> $< $> makers."
3243 (let (n nmax len char
(start 0))
3244 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3247 (setq start
(match-end 3))
3248 (setq nmax
(if (equal (match-string 1 s
) "@")
3249 (1- (length org-table-dlines
))
3250 org-table-current-ncol
)
3251 len
(- (match-end 2) (match-beginning 2))
3252 char
(string-to-char (match-string 2 s
))
3256 (if (or (< n
1) (> n nmax
))
3257 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3258 (match-string 0 s
) s
))
3259 (setq start
(match-beginning 0))
3260 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3263 (defun org-table-formula-substitute-names (f)
3264 "Replace $const with values in string F."
3265 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3266 ;; First, check for column names
3267 (while (setq start
(string-match org-table-column-name-regexp f start
))
3268 (setq start
(1+ start
))
3269 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3270 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3271 ;; Parameters and constants
3273 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3275 (setq start
(match-end 2))
3276 (setq start
(1+ start
))
3277 (if (setq a
(save-match-data
3278 (org-table-get-constant (match-string 1 f
))))
3279 (setq f
(replace-match
3280 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3281 (if org-table-formula-debug
3282 (put-text-property 0 (length f
) :orig-formula f1 f
))
3285 (defun org-table-get-constant (const)
3286 "Find the value for a parameter or constant in a formula.
3287 Parameters get priority."
3288 (or (cdr (assoc const org-table-local-parameters
))
3289 (cdr (assoc const org-table-formula-constants-local
))
3290 (cdr (assoc const org-table-formula-constants
))
3291 (and (fboundp 'constants-get
) (constants-get const
))
3292 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3293 (org-entry-get nil
(substring const
5) 'inherit
))
3296 (defvar org-table-fedit-map
3297 (let ((map (make-sparse-keymap)))
3298 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3299 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3300 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3301 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3302 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3303 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3304 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3305 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3306 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3307 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3308 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3309 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3310 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3311 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3312 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3313 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3314 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3315 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3316 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3317 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3320 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3322 ["Finish and Install" org-table-fedit-finish t
]
3323 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3324 ["Abort" org-table-fedit-abort t
]
3326 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3327 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3329 "Shift Reference at Point"
3330 ["Up" org-table-fedit-ref-up t
]
3331 ["Down" org-table-fedit-ref-down t
]
3332 ["Left" org-table-fedit-ref-left t
]
3333 ["Right" org-table-fedit-ref-right t
]
3335 "Change Test Row for Column Formulas"
3336 ["Up" org-table-fedit-line-up t
]
3337 ["Down" org-table-fedit-line-down t
]
3339 ["Scroll Table Window" org-table-fedit-scroll t
]
3340 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3341 ["Show Table Grid" org-table-fedit-toggle-coordinates
3342 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3343 org-table-overlay-coordinates
)]
3345 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3346 :style toggle
:selected org-table-buffer-is-an
]))
3351 (defun org-table-edit-formulas ()
3352 "Edit the formulas of the current table in a separate buffer."
3354 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3355 (beginning-of-line 0))
3356 (unless (org-at-table-p) (user-error "Not at a table"))
3357 (org-table-get-specials)
3358 (let ((key (org-table-current-field-formula 'key
'noerror
))
3359 (eql (sort (org-table-get-stored-formulas 'noerror
)
3360 'org-table-formula-less-p
))
3361 (pos (point-marker))
3363 (wc (current-window-configuration))
3364 (sel-win (selected-window))
3365 (titles '((column .
"# Column Formulas\n")
3366 (field .
"# Field and Range Formulas\n")
3367 (named .
"# Named Field Formulas\n")))
3369 (org-switch-to-buffer-other-window "*Edit Formulas*")
3371 ;; Keep global-font-lock-mode from turning on font-lock-mode
3372 (let ((font-lock-global-modes '(not fundamental-mode
)))
3374 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3375 (org-set-local 'org-pos pos
)
3376 (org-set-local 'org-window-configuration wc
)
3377 (org-set-local 'org-selected-window sel-win
)
3378 (use-local-map org-table-fedit-map
)
3379 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3380 (easy-menu-add org-table-fedit-menu
)
3381 (setq startline
(org-current-line))
3382 (while (setq entry
(pop eql
))
3384 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3385 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3386 ((string-match "^[0-9]" (car entry
)) 'column
)
3388 (when (setq title
(assq type titles
))
3389 (or (bobp) (insert "\n"))
3390 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3391 (setq titles
(remove title titles
)))
3392 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3393 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3394 (car entry
) " = " (cdr entry
) "\n"))
3395 (remove-text-properties 0 (length s
) '(face nil
) s
)
3397 (if (eq org-table-use-standard-references t
)
3398 (org-table-fedit-toggle-ref-type))
3399 (org-goto-line startline
)
3400 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3402 (defun org-table-fedit-post-command ()
3403 (when (not (memq this-command
'(lisp-complete-symbol)))
3404 (let ((win (selected-window)))
3407 (org-table-show-reference)
3409 (select-window win
)))))
3411 (defun org-table-formula-to-user (s)
3412 "Convert a formula from internal to user representation."
3413 (if (eq org-table-use-standard-references t
)
3414 (org-table-convert-refs-to-an s
)
3417 (defun org-table-formula-from-user (s)
3418 "Convert a formula from user to internal representation."
3419 (if org-table-use-standard-references
3420 (org-table-convert-refs-to-rc s
)
3423 (defun org-table-convert-refs-to-rc (s)
3424 "Convert spreadsheet references from A7 to @7$28.
3425 Works for single references, but also for entire formulas and even the
3428 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3431 ;; format match, just advance
3432 (setq start
(match-end 0)))
3433 ((and (> (match-beginning 0) 0)
3434 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3435 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3436 ;; 3.e5 or something like this.
3437 (setq start
(match-end 0)))
3438 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3439 ;; (member (match-string 1 s)
3440 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3442 ;; function name, just advance
3443 (setq start
(match-end 0)))
3445 (setq start
(match-beginning 0)
3447 (if (equal (match-string 2 s
) "&")
3448 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3450 (string-to-number (match-string 2 s
))
3451 (org-letters-to-number (match-string 1 s
))))
3455 (defun org-table-convert-refs-to-an (s)
3456 "Convert spreadsheet references from to @7$28 to AB7.
3457 Works for single references, but also for entire formulas and even the
3459 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3460 (setq s
(replace-match
3462 (org-number-to-letters
3463 (string-to-number (match-string 2 s
)))
3464 (string-to-number (match-string 1 s
)))
3466 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3467 (setq s
(replace-match (concat "\\1"
3468 (org-number-to-letters
3469 (string-to-number (match-string 2 s
))) "&")
3473 (defun org-letters-to-number (s)
3474 "Convert a base 26 number represented by letters into an integer.
3475 For example: AB -> 28."
3478 (while (> (length s
) 0)
3479 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3483 (defun org-number-to-letters (n)
3484 "Convert an integer into a base 26 number represented by letters.
3485 For example: 28 -> AB."
3488 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3492 (defun org-table-time-string-to-seconds (s)
3493 "Convert a time string into numerical duration in seconds.
3494 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3495 If S is a string representing a number, keep this number."
3498 (let (hour minus min sec res
)
3500 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3501 (setq minus
(< 0 (length (match-string 1 s
)))
3502 hour
(string-to-number (match-string 2 s
))
3503 min
(string-to-number (match-string 3 s
))
3504 sec
(string-to-number (match-string 4 s
)))
3506 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3507 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3508 ((and (not (string-match org-ts-regexp-both s
))
3509 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3510 (setq minus
(< 0 (length (match-string 1 s
)))
3511 hour
(string-to-number (match-string 2 s
))
3512 min
(string-to-number (match-string 3 s
)))
3514 (setq res
(- (+ (* hour
3600) (* min
60))))
3515 (setq res
(+ (* hour
3600) (* min
60)))))
3516 (t (setq res
(string-to-number s
))))
3517 (number-to-string res
))))
3519 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3520 "Convert a number of seconds to a time string.
3521 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3522 minutes or seconds."
3523 (let* ((secs0 (abs secs
))
3525 (cond ((eq output-format
'days
)
3526 (format "%.3f" (/ (float secs0
) 86400)))
3527 ((eq output-format
'hours
)
3528 (format "%.2f" (/ (float secs0
) 3600)))
3529 ((eq output-format
'minutes
)
3530 (format "%.1f" (/ (float secs0
) 60)))
3531 ((eq output-format
'seconds
)
3532 (format "%d" secs0
))
3533 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3534 (if (< secs
0) (concat "-" res
) res
)))
3536 (defun org-table-fedit-convert-buffer (function)
3537 "Convert all references in this buffer, using FUNCTION."
3538 (let ((line (org-current-line)))
3539 (goto-char (point-min))
3541 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3542 (delete-region (point) (point-at-eol))
3543 (or (eobp) (forward-char 1)))
3544 (org-goto-line line
)))
3546 (defun org-table-fedit-toggle-ref-type ()
3547 "Convert all references in the buffer from B3 to @3$2 and back."
3549 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3550 (org-table-fedit-convert-buffer
3551 (if org-table-buffer-is-an
3552 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3553 (message "Reference type switched to %s"
3554 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3556 (defun org-table-fedit-ref-up ()
3557 "Shift the reference at point one row/hline up."
3559 (org-table-fedit-shift-reference 'up
))
3560 (defun org-table-fedit-ref-down ()
3561 "Shift the reference at point one row/hline down."
3563 (org-table-fedit-shift-reference 'down
))
3564 (defun org-table-fedit-ref-left ()
3565 "Shift the reference at point one field to the left."
3567 (org-table-fedit-shift-reference 'left
))
3568 (defun org-table-fedit-ref-right ()
3569 "Shift the reference at point one field to the right."
3571 (org-table-fedit-shift-reference 'right
))
3573 (defun org-table-fedit-shift-reference (dir)
3575 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3576 (if (memq dir
'(left right
))
3577 (org-rematch-and-replace 1 (eq dir
'left
))
3578 (user-error "Cannot shift reference in this direction")))
3579 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3580 ;; A B3-like reference
3581 (if (memq dir
'(up down
))
3582 (org-rematch-and-replace 2 (eq dir
'up
))
3583 (org-rematch-and-replace 1 (eq dir
'left
))))
3585 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3586 ;; An internal reference
3587 (if (memq dir
'(up down
))
3588 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3589 (org-rematch-and-replace 5 (eq dir
'left
))))))
3591 (defun org-rematch-and-replace (n &optional decr hline
)
3592 "Re-match the group N, and replace it with the shifted reference."
3593 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3594 (goto-char (match-beginning n
))
3595 (and (looking-at (regexp-quote (match-string n
)))
3596 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3599 (defun org-table-shift-refpart (ref &optional decr hline
)
3600 "Shift a reference part REF.
3601 If DECR is set, decrease the references row/column, else increase.
3602 If HLINE is set, this may be a hline reference, it certainly is not
3603 a translation reference."
3605 (let* ((sign (string-match "^[-+]" ref
)) n
)
3607 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3609 ((and hline
(string-match "^I+" ref
))
3610 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3611 (setq n
(+ n
(if decr -
1 1)))
3612 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3614 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3616 (concat sign
(make-string n ?I
)))
3618 ((string-match "^[0-9]+" ref
)
3619 (setq n
(string-to-number (concat sign ref
)))
3620 (setq n
(+ n
(if decr -
1 1)))
3622 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3623 (number-to-string (max 1 n
))))
3625 ((string-match "^[a-zA-Z]+" ref
)
3626 (org-number-to-letters
3627 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3629 (t (user-error "Cannot shift reference"))))))
3631 (defun org-table-fedit-toggle-coordinates ()
3632 "Toggle the display of coordinates in the referenced table."
3634 (let ((pos (marker-position org-pos
)))
3635 (with-current-buffer (marker-buffer org-pos
)
3638 (org-table-toggle-coordinate-overlays)))))
3640 (defun org-table-fedit-finish (&optional arg
)
3641 "Parse the buffer for formula definitions and install them.
3642 With prefix ARG, apply the new formulas to the table."
3644 (org-table-remove-rectangle-highlight)
3645 (if org-table-use-standard-references
3647 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3648 (setq org-table-buffer-is-an nil
)))
3649 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3650 (goto-char (point-min))
3651 (while (re-search-forward
3652 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3654 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3655 form
(match-string 3))
3656 (setq form
(org-trim form
))
3657 (when (not (equal form
""))
3658 (while (string-match "[ \t]*\n[ \t]*" form
)
3659 (setq form
(replace-match " " t t form
)))
3660 (when (assoc var eql
)
3661 (user-error "Double formulas for %s" var
))
3662 (push (cons var form
) eql
)))
3664 (set-window-configuration org-window-configuration
)
3665 (select-window sel-win
)
3667 (unless (org-at-table-p)
3668 (user-error "Lost table position - cannot install formulas"))
3669 (org-table-store-formulas eql
)
3670 (move-marker pos nil
)
3671 (kill-buffer "*Edit Formulas*")
3673 (org-table-recalculate 'all
)
3674 (message "New formulas installed - press C-u C-c C-c to apply."))))
3676 (defun org-table-fedit-abort ()
3677 "Abort editing formulas, without installing the changes."
3679 (org-table-remove-rectangle-highlight)
3680 (let ((pos org-pos
) (sel-win org-selected-window
))
3681 (set-window-configuration org-window-configuration
)
3682 (select-window sel-win
)
3684 (move-marker pos nil
)
3685 (message "Formula editing aborted without installing changes")))
3687 (defun org-table-fedit-lisp-indent ()
3688 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3690 (let ((pos (point)) beg end ind
)
3691 (beginning-of-line 1)
3693 ((looking-at "[ \t]")
3695 (call-interactively 'lisp-indent-line
))
3696 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3697 ((not (fboundp 'pp-buffer
))
3698 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3699 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3700 (goto-char (- (match-end 0) 2))
3702 (setq ind
(make-string (current-column) ?\
))
3703 (condition-case nil
(forward-sexp 1)
3705 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3708 (narrow-to-region beg end
)
3709 (if (eq last-command this-command
)
3711 (goto-char (point-min))
3712 (setq this-command nil
)
3713 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3714 (replace-match " ")))
3716 (untabify (point-min) (point-max))
3717 (goto-char (1+ (point-min)))
3718 (while (re-search-forward "^." nil t
)
3719 (beginning-of-line 1)
3721 (goto-char (point-max))
3722 (org-delete-backward-char 1)))
3726 (defvar org-show-positions nil
)
3728 (defun org-table-show-reference (&optional local
)
3729 "Show the location/value of the $ expression at point."
3731 (org-table-remove-rectangle-highlight)
3733 (let ((pos (if local
(point) org-pos
))
3735 (org-inhibit-highlight-removal t
)
3736 (win (selected-window))
3737 (org-show-positions nil
)
3738 var name e what match dest
)
3739 (if local
(org-table-get-specials))
3741 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3742 (setq match
(concat (substring (match-string 0) 0 -
1)
3744 (substring (match-string 0) 0 -
1)
3747 ((or (org-at-regexp-p org-table-range-regexp2
)
3748 (org-at-regexp-p org-table-translate-regexp
)
3749 (org-at-regexp-p org-table-range-regexp
))
3752 (org-table-convert-refs-to-rc (match-string 0))))
3754 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3755 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3757 (t (user-error "No reference at point")))
3758 match
(and what
(or match
(match-string 0))))
3759 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3760 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3761 'secondary-selection
))
3762 (org-add-hook 'before-change-functions
3763 'org-table-remove-rectangle-highlight
)
3764 (if (eq what
'name
) (setq var
(substring match
1)))
3765 (when (eq what
'range
)
3766 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3767 (setq match
(org-table-formula-substitute-names match
)))
3771 (re-search-backward "^\\S-" nil t
)
3772 (beginning-of-line 1)
3773 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3776 (org-table-convert-refs-to-rc (match-string 1))))
3777 (org-table-add-rectangle-overlay
3778 (match-beginning 1) (match-end 1) face2
))))
3779 (if (and (markerp pos
) (marker-buffer pos
))
3780 (if (get-buffer-window (marker-buffer pos
))
3781 (select-window (get-buffer-window (marker-buffer pos
)))
3782 (org-switch-to-buffer-other-window (get-buffer-window
3783 (marker-buffer pos
)))))
3785 (org-table-force-dataline)
3787 (setq name
(substring dest
1))
3789 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3790 (setq e
(assoc name org-table-named-field-locations
))
3791 (org-goto-line (nth 1 e
))
3792 (org-table-goto-column (nth 2 e
)))
3793 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3794 (let ((l (string-to-number (match-string 1 dest
)))
3795 (c (string-to-number (match-string 2 dest
))))
3796 (org-goto-line (aref org-table-dlines l
))
3797 (org-table-goto-column c
)))
3798 (t (org-table-goto-column (string-to-number name
))))
3799 (move-marker pos
(point))
3800 (org-table-highlight-rectangle nil nil face2
))
3802 ((equal dest match
))
3807 (org-table-get-range match nil nil
'highlight
))
3809 ((setq e
(assoc var org-table-named-field-locations
))
3810 (org-goto-line (nth 1 e
))
3811 (org-table-goto-column (nth 2 e
))
3812 (org-table-highlight-rectangle (point) (point))
3813 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3814 ((setq e
(assoc var org-table-column-names
))
3815 (org-table-goto-column (string-to-number (cdr e
)))
3816 (org-table-highlight-rectangle (point) (point))
3817 (goto-char (org-table-begin))
3818 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3821 (goto-char (match-beginning 1))
3822 (org-table-highlight-rectangle)
3823 (message "Named column (column %s)" (cdr e
)))
3824 (user-error "Column name not found")))
3827 (org-table-goto-column (string-to-number (substring match
1)))
3828 (org-table-highlight-rectangle (point) (point))
3829 (message "Column %s" (substring match
1)))
3830 ((setq e
(assoc var org-table-local-parameters
))
3831 (goto-char (org-table-begin))
3832 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3834 (goto-char (match-beginning 1))
3835 (org-table-highlight-rectangle)
3836 (message "Local parameter."))
3837 (user-error "Parameter not found")))
3840 ((not var
) (user-error "No reference at point"))
3841 ((setq e
(assoc var org-table-formula-constants-local
))
3842 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3844 ((setq e
(assoc var org-table-formula-constants
))
3845 (message "Constant: $%s=%s in `org-table-formula-constants'."
3847 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3848 (message "Constant: $%s=%s, from `constants.el'%s."
3849 var e
(format " (%s units)" constants-unit-system
)))
3850 (t (user-error "Undefined name $%s" var
)))))
3852 (when (and org-show-positions
3853 (not (memq this-command
'(org-table-fedit-scroll
3854 org-table-fedit-scroll-down
))))
3855 (push pos org-show-positions
)
3856 (push org-table-current-begin-pos org-show-positions
)
3857 (let ((min (apply 'min org-show-positions
))
3858 (max (apply 'max org-show-positions
)))
3859 (goto-char min
) (recenter 0)
3861 (or (pos-visible-in-window-p max
) (recenter -
1))))
3862 (select-window win
))))
3864 (defun org-table-force-dataline ()
3865 "Make sure the cursor is in a dataline in a table."
3866 (unless (save-excursion
3867 (beginning-of-line 1)
3868 (looking-at org-table-dataline-regexp
))
3869 (let* ((re org-table-dataline-regexp
)
3870 (p1 (save-excursion (re-search-forward re nil
'move
)))
3871 (p2 (save-excursion (re-search-backward re nil
'move
))))
3873 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3875 ((or p1 p2
) (goto-char (or p1 p2
)))
3876 (t (user-error "No table dataline around here"))))))
3878 (defun org-table-fedit-line-up ()
3879 "Move cursor one line up in the window showing the table."
3881 (org-table-fedit-move 'previous-line
))
3883 (defun org-table-fedit-line-down ()
3884 "Move cursor one line down in the window showing the table."
3886 (org-table-fedit-move 'next-line
))
3888 (defun org-table-fedit-move (command)
3889 "Move the cursor in the window showing the table.
3890 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3891 (let ((org-table-allow-automatic-line-recalculation nil
)
3892 (pos org-pos
) (win (selected-window)) p
)
3893 (select-window (get-buffer-window (marker-buffer org-pos
)))
3895 (call-interactively command
)
3896 (while (and (org-at-table-p)
3897 (org-at-table-hline-p))
3898 (call-interactively command
))
3899 (or (org-at-table-p) (goto-char p
))
3900 (move-marker pos
(point))
3901 (select-window win
)))
3903 (defun org-table-fedit-scroll (N)
3905 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3906 (scroll-other-window N
)))
3908 (defun org-table-fedit-scroll-down (N)
3910 (org-table-fedit-scroll (- N
)))
3912 (defvar org-table-rectangle-overlays nil
)
3914 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3915 "Add a new overlay."
3916 (let ((ov (make-overlay beg end
)))
3917 (overlay-put ov
'face
(or face
'secondary-selection
))
3918 (push ov org-table-rectangle-overlays
)))
3920 (defun org-table-highlight-rectangle (&optional beg end face
)
3921 "Highlight rectangular region in a table."
3922 (setq beg
(or beg
(point)) end
(or end
(point)))
3923 (let ((b (min beg end
))
3926 (and (boundp 'org-show-positions
)
3927 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3928 (goto-char (min beg end
))
3929 (setq l1
(org-current-line)
3930 c1
(org-table-current-column))
3931 (goto-char (max beg end
))
3932 (setq l2
(org-current-line)
3933 c2
(org-table-current-column))
3934 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3936 (beginning-of-line 1)
3937 (loop for line from l1 to l2 do
3938 (when (looking-at org-table-dataline-regexp
)
3939 (org-table-goto-column c1
)
3940 (skip-chars-backward "^|\n") (setq beg
(point))
3941 (org-table-goto-column c2
)
3942 (skip-chars-forward "^|\n") (setq end
(point))
3943 (org-table-add-rectangle-overlay beg end face
))
3944 (beginning-of-line 2))
3946 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3948 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3949 "Remove the rectangle overlays."
3950 (unless org-inhibit-highlight-removal
3951 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3952 (mapc 'delete-overlay org-table-rectangle-overlays
)
3953 (setq org-table-rectangle-overlays nil
)))
3955 (defvar org-table-coordinate-overlays nil
3956 "Collects the coordinate grid overlays, so that they can be removed.")
3957 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3959 (defun org-table-overlay-coordinates ()
3960 "Add overlays to the table at point, to show row/column coordinates."
3962 (mapc 'delete-overlay org-table-coordinate-overlays
)
3963 (setq org-table-coordinate-overlays nil
)
3965 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3966 (goto-char (org-table-begin))
3967 (while (org-at-table-p)
3968 (setq eol
(point-at-eol))
3969 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3970 (push ov org-table-coordinate-overlays
)
3971 (setq hline
(looking-at org-table-hline-regexp
))
3972 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3973 (format "%4d" (setq id
(1+ id
)))))
3974 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3977 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3978 (setq beg
(1+ (match-beginning 0))
3980 s1
(concat "$" (int-to-string ic
))
3981 s2
(org-number-to-letters ic
)
3982 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3983 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3984 (push ov org-table-coordinate-overlays
)
3985 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3986 (beginning-of-line 2)))))
3989 (defun org-table-toggle-coordinate-overlays ()
3990 "Toggle the display of Row/Column numbers in tables."
3992 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3993 (message "Tables Row/Column numbers display turned %s"
3994 (if org-table-overlay-coordinates
"on" "off"))
3995 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3997 (unless org-table-overlay-coordinates
3998 (mapc 'delete-overlay org-table-coordinate-overlays
)
3999 (setq org-table-coordinate-overlays nil
)))
4002 (defun org-table-toggle-formula-debugger ()
4003 "Toggle the formula debugger in tables."
4005 (setq org-table-formula-debug
(not org-table-formula-debug
))
4006 (message "Formula debugging has been turned %s"
4007 (if org-table-formula-debug
"on" "off")))
4009 ;;; The orgtbl minor mode
4011 ;; Define a minor mode which can be used in other modes in order to
4012 ;; integrate the org-mode table editor.
4014 ;; This is really a hack, because the org-mode table editor uses several
4015 ;; keys which normally belong to the major mode, for example the TAB and
4016 ;; RET keys. Here is how it works: The minor mode defines all the keys
4017 ;; necessary to operate the table editor, but wraps the commands into a
4018 ;; function which tests if the cursor is currently inside a table. If that
4019 ;; is the case, the table editor command is executed. However, when any of
4020 ;; those keys is used outside a table, the function uses `key-binding' to
4021 ;; look up if the key has an associated command in another currently active
4022 ;; keymap (minor modes, major mode, global), and executes that command.
4023 ;; There might be problems if any of the keys used by the table editor is
4024 ;; otherwise used as a prefix key.
4026 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4027 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4028 ;; addresses this by checking explicitly for both bindings.
4030 ;; The optimized version (see variable `orgtbl-optimized') takes over
4031 ;; all keys which are bound to `self-insert-command' in the *global map*.
4032 ;; Some modes bind other commands to simple characters, for example
4033 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4034 ;; active, this binding is ignored inside tables and replaced with a
4035 ;; modified self-insert.
4038 (defvar orgtbl-mode-map
(make-keymap)
4039 "Keymap for `orgtbl-mode'.")
4041 (defvar org-old-auto-fill-inhibit-regexp nil
4042 "Local variable used by `orgtbl-mode'.")
4044 (defconst orgtbl-line-start-regexp
4045 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4046 "Matches a line belonging to an orgtbl.")
4048 (defconst orgtbl-extra-font-lock-keywords
4049 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4050 0 (quote 'org-table
) 'prepend
))
4051 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4053 ;; Install it as a minor mode.
4054 (put 'orgtbl-mode
:included t
)
4055 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4058 (define-minor-mode orgtbl-mode
4059 "The `org-mode' table editor as a minor mode for use in other modes."
4060 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4061 (org-load-modules-maybe)
4063 ((derived-mode-p 'org-mode
)
4064 ;; Exit without error, in case some hook functions calls this
4065 ;; by accident in org-mode.
4066 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4068 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4069 ;; Make sure we are first in minor-mode-map-alist
4070 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4071 ;; FIXME: maybe it should use emulation-mode-map-alists?
4072 (and c
(setq minor-mode-map-alist
4073 (cons c
(delq c minor-mode-map-alist
)))))
4074 (org-set-local (quote org-table-may-need-update
) t
)
4075 (org-add-hook 'before-change-functions
'org-before-change-function
4077 (org-set-local 'org-old-auto-fill-inhibit-regexp
4078 auto-fill-inhibit-regexp
)
4079 (org-set-local 'auto-fill-inhibit-regexp
4080 (if auto-fill-inhibit-regexp
4081 (concat orgtbl-line-start-regexp
"\\|"
4082 auto-fill-inhibit-regexp
)
4083 orgtbl-line-start-regexp
))
4084 (add-to-invisibility-spec '(org-cwidth))
4085 (when (fboundp 'font-lock-add-keywords
)
4086 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4087 (org-restart-font-lock))
4088 (easy-menu-add orgtbl-mode-menu
))
4090 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4091 (org-table-cleanup-narrow-column-properties)
4092 (org-remove-from-invisibility-spec '(org-cwidth))
4093 (remove-hook 'before-change-functions
'org-before-change-function t
)
4094 (when (fboundp 'font-lock-remove-keywords
)
4095 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4096 (org-restart-font-lock))
4097 (easy-menu-remove orgtbl-mode-menu
)
4098 (force-mode-line-update 'all
))))
4100 (defun org-table-cleanup-narrow-column-properties ()
4101 "Remove all properties related to narrow-column invisibility."
4102 (let ((s (point-min)))
4103 (while (setq s
(text-property-any s
(point-max)
4104 'display org-narrow-column-arrow
))
4105 (remove-text-properties s
(1+ s
) '(display t
)))
4106 (setq s
(point-min))
4107 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4108 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4109 (setq s
(point-min))
4110 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4111 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4113 (defun orgtbl-make-binding (fun n
&rest keys
)
4114 "Create a function for binding in the table minor mode.
4115 FUN is the command to call inside a table. N is used to create a unique
4116 command name. KEYS are keys that should be checked in for a command
4117 to execute outside of tables."
4120 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4122 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4123 "Outside of tables, run the binding of `"
4124 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
4129 (list 'call-interactively
(list 'quote fun
))
4130 (list 'let
'(orgtbl-mode)
4131 (list 'call-interactively
4134 (list 'key-binding k
))
4136 '('orgtbl-error
))))))))
4138 (defun orgtbl-error ()
4139 "Error when there is no default binding for a table key."
4141 (user-error "This key has no function outside tables"))
4143 (defun orgtbl-setup ()
4144 "Setup orgtbl keymaps."
4147 '(([(meta shift left
)] org-table-delete-column
)
4148 ([(meta left
)] org-table-move-column-left
)
4149 ([(meta right
)] org-table-move-column-right
)
4150 ([(meta shift right
)] org-table-insert-column
)
4151 ([(meta shift up
)] org-table-kill-row
)
4152 ([(meta shift down
)] org-table-insert-row
)
4153 ([(meta up
)] org-table-move-row-up
)
4154 ([(meta down
)] org-table-move-row-down
)
4155 ("\C-c\C-w" org-table-cut-region
)
4156 ("\C-c\M-w" org-table-copy-region
)
4157 ("\C-c\C-y" org-table-paste-rectangle
)
4158 ("\C-c\C-w" org-table-wrap-region
)
4159 ("\C-c-" org-table-insert-hline
)
4160 ("\C-c}" org-table-toggle-coordinate-overlays
)
4161 ("\C-c{" org-table-toggle-formula-debugger
)
4162 ("\C-m" org-table-next-row
)
4163 ([(shift return
)] org-table-copy-down
)
4164 ("\C-c?" org-table-field-info
)
4165 ("\C-c " org-table-blank-field
)
4166 ("\C-c+" org-table-sum
)
4167 ("\C-c=" org-table-eval-formula
)
4168 ("\C-c'" org-table-edit-formulas
)
4169 ("\C-c`" org-table-edit-field
)
4170 ("\C-c*" org-table-recalculate
)
4171 ("\C-c^" org-table-sort-lines
)
4172 ("\M-a" org-table-beginning-of-field
)
4173 ("\M-e" org-table-end-of-field
)
4174 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4176 (while (setq elt
(pop bindings
))
4177 (setq nfunc
(1+ nfunc
))
4178 (setq key
(org-key (car elt
))
4180 cmd
(orgtbl-make-binding fun nfunc key
))
4181 (org-defkey orgtbl-mode-map key cmd
))
4183 ;; Special treatment needed for TAB and RET
4184 (org-defkey orgtbl-mode-map
[(return)]
4185 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4186 (org-defkey orgtbl-mode-map
"\C-m"
4187 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4189 (org-defkey orgtbl-mode-map
[(tab)]
4190 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4191 (org-defkey orgtbl-mode-map
"\C-i"
4192 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4194 (org-defkey orgtbl-mode-map
[(shift tab
)]
4195 (orgtbl-make-binding 'org-table-previous-field
104
4196 [(shift tab
)] [(tab)] "\C-i"))
4199 (unless (featurep 'xemacs
)
4200 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4201 (orgtbl-make-binding 'org-table-previous-field
107
4202 [S-iso-lefttab
] [backtab] [(shift tab)]
4205 (org-defkey orgtbl-mode-map [backtab]
4206 (orgtbl-make-binding 'org-table-previous-field
108
4207 [backtab] [S-iso-lefttab] [(shift tab)]
4210 (org-defkey orgtbl-mode-map "\M-\C-m"
4211 (orgtbl-make-binding 'org-table-wrap-region 105
4212 "\M-\C-m" [(meta return)]))
4213 (org-defkey orgtbl-mode-map [(meta return)]
4214 (orgtbl-make-binding 'org-table-wrap-region 106
4215 [(meta return)] "\M-\C-m"))
4217 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4218 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4220 (when orgtbl-optimized
4221 ;; If the user wants maximum table support, we need to hijack
4222 ;; some standard editing functions
4223 (org-remap orgtbl-mode-map
4224 'self-insert-command 'orgtbl-self-insert-command
4225 'delete-char 'org-delete-char
4226 'delete-backward-char 'org-delete-backward-char)
4227 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4228 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4230 ["Create or convert" org-table-create-or-convert-from-region
4231 :active (not (org-at-table-p)) :keys "C-c |" ]
4233 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4234 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4235 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4236 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4238 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4239 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4240 ["Copy Field from Above"
4241 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4244 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4245 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4246 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4247 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4249 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4250 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4251 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4252 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4253 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4255 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4257 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4258 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4259 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4260 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4263 ["Insert table template" orgtbl-insert-radio-table
4264 (assq major-mode orgtbl-radio-table-templates)]
4265 ["Comment/uncomment table" orgtbl-toggle-comment t])
4267 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4268 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4269 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4270 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4271 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4272 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4273 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4274 ["Sum Column/Rectangle" org-table-sum
4275 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4276 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4278 org-table-toggle-formula-debugger :active (org-at-table-p)
4280 :style toggle :selected org-table-formula-debug]
4281 ["Show Col/Row Numbers"
4282 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4284 :style toggle :selected org-table-overlay-coordinates]
4288 (defun orgtbl-ctrl-c-ctrl-c (arg)
4289 "If the cursor is inside a table, realign the table.
4290 If it is a table to be sent away to a receiver, do it.
4291 With prefix arg, also recompute table."
4293 (let ((case-fold-search t) (pos (point)) action)
4295 (beginning-of-line 1)
4297 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4298 ((looking-at "[ \t]*|") pos)
4299 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4303 (org-table-maybe-eval-formula)
4305 (call-interactively 'org-table-recalculate)
4306 (org-table-maybe-recalculate-line))
4307 (call-interactively 'org-table-align)
4308 (when (orgtbl-send-table 'maybe)
4309 (run-hooks 'orgtbl-after-send-table-hook)))
4310 ((eq action 'recalc)
4311 (org-table-set-constants)
4313 (beginning-of-line 1)
4314 (skip-chars-backward " \r\n\t")
4315 (if (org-at-table-p)
4316 (org-call-with-arg 'org-table-recalculate t))))
4317 (t (let (orgtbl-mode)
4318 (call-interactively (key-binding "\C-c\C-c")))))))
4320 (defun orgtbl-create-or-convert-from-region (arg)
4321 "Create table or convert region to table, if no conflicting binding.
4322 This installs the table binding `C-c |', but only if there is no
4323 conflicting binding to this key outside orgtbl-mode."
4325 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4327 (call-interactively cmd)
4328 (call-interactively 'org-table-create-or-convert-from-region))))
4330 (defun orgtbl-tab (arg)
4331 "Justification and field motion for `orgtbl-mode'."
4333 (if arg (org-table-edit-field t)
4334 (org-table-justify-field-maybe)
4335 (org-table-next-field)))
4337 (defun orgtbl-ret ()
4338 "Justification and field motion for `orgtbl-mode'."
4342 (org-table-justify-field-maybe)
4343 (org-table-next-row)))
4345 (defun orgtbl-self-insert-command (N)
4346 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4347 If the cursor is in a table looking at whitespace, the whitespace is
4348 overwritten, and the table is not marked as requiring realignment."
4350 (if (and (org-at-table-p)
4352 (and org-table-auto-blank-field
4353 (member last-command
4354 '(orgtbl-hijacker-command-100
4355 orgtbl-hijacker-command-101
4356 orgtbl-hijacker-command-102
4357 orgtbl-hijacker-command-103
4358 orgtbl-hijacker-command-104
4359 orgtbl-hijacker-command-105
4361 (org-table-blank-field))
4364 (looking-at "[^|\n]* +|"))
4365 (let (org-table-may-need-update)
4366 (goto-char (1- (match-end 0)))
4367 (org-delete-backward-char 1)
4368 (goto-char (match-beginning 0))
4369 (self-insert-command N))
4370 (setq org-table-may-need-update t)
4373 (cmd (or (key-binding
4374 (or (and (listp function-key-map)
4375 (setq a (assoc last-input-event function-key-map))
4377 (vector last-input-event)))
4378 'self-insert-command)))
4379 (call-interactively cmd)
4380 (if (and org-self-insert-cluster-for-undo
4381 (eq cmd 'self-insert-command))
4382 (if (not (eq last-command 'orgtbl-self-insert-command))
4383 (setq org-self-insert-command-undo-counter 1)
4384 (if (>= org-self-insert-command-undo-counter 20)
4385 (setq org-self-insert-command-undo-counter 1)
4386 (and (> org-self-insert-command-undo-counter 0)
4388 (not (cadr buffer-undo-list)) ; remove nil entry
4389 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4390 (setq org-self-insert-command-undo-counter
4391 (1+ org-self-insert-command-undo-counter))))))))
4393 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4394 "Regular expression matching exponentials as produced by calc.")
4396 (defun orgtbl-gather-send-defs ()
4397 "Gather a plist of :name, :transform, :params for each destination before
4400 (goto-char (org-table-begin))
4402 (beginning-of-line 0)
4403 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4404 (let ((name (org-no-properties (match-string 1)))
4405 (transform (intern (match-string 2)))
4406 (params (if (match-end 3)
4407 (read (concat "(" (match-string 3) ")")))))
4408 (push (list :name name :transform transform :params params)
4410 (beginning-of-line 0)))
4413 (defun orgtbl-send-replace-tbl (name txt)
4414 "Find and replace table NAME with TXT."
4416 (goto-char (point-min))
4417 (unless (re-search-forward
4418 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4419 (user-error "Don't know where to insert translated table"))
4420 (goto-char (match-beginning 0))
4421 (beginning-of-line 2)
4423 (let ((beg (point)))
4424 (unless (re-search-forward
4425 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4426 (user-error "Cannot find end of insertion region"))
4427 (beginning-of-line 1)
4428 (delete-region beg (point))))
4432 (defun org-table-to-lisp (&optional txt)
4433 "Convert the table at point to a Lisp structure.
4434 The structure will be a list. Each item is either the symbol `hline'
4435 for a horizontal separator line, or a list of field values as strings.
4436 The table is taken from the parameter TXT, or from the buffer at point."
4438 (unless (org-at-table-p)
4439 (user-error "No table at point")))
4441 (buffer-substring-no-properties (org-table-begin)
4443 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4447 (if (string-match org-table-hline-regexp x)
4449 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4452 (defun orgtbl-send-table (&optional maybe)
4453 "Send a transformed version of this table to the receiver position.
4454 With argument MAYBE, fail quietly if no transformation is defined for
4458 (unless (org-at-table-p) (user-error "Not at a table"))
4459 ;; when non-interactive, we assume align has just happened.
4460 (when (org-called-interactively-p 'any) (org-table-align))
4461 (let ((dests (orgtbl-gather-send-defs))
4462 (txt (buffer-substring-no-properties (org-table-begin)
4465 (unless dests (if maybe (throw 'exit nil)
4466 (user-error "Don't know how to transform this table")))
4467 (dolist (dest dests)
4468 (let* ((name (plist-get dest :name))
4469 (transform (plist-get dest :transform))
4470 (params (plist-get dest :params))
4471 (skip (plist-get params :skip))
4472 (skipcols (plist-get params :skipcols))
4473 (no-escape (plist-get params :no-escape))
4475 (lines (org-table-clean-before-export
4477 (org-split-string txt "[ \t]*\n[ \t]*"))))
4478 (i0 (if org-table-clean-did-remove-column 2 1))
4479 (lines (if no-escape lines
4480 (mapcar (lambda(l) (replace-regexp-in-string
4481 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4484 (if (string-match org-table-hline-regexp x)
4486 (org-remove-by-index
4487 (org-split-string (org-trim x) "\\s-*|\\s-*")
4490 (fun (if (= i0 2) 'cdr 'identity))
4491 (org-table-last-alignment
4492 (org-remove-by-index (funcall fun org-table-last-alignment)
4494 (org-table-last-column-widths
4495 (org-remove-by-index (funcall fun org-table-last-column-widths)
4497 (txt (if (fboundp transform)
4498 (funcall transform table params)
4499 (user-error "No such transformation function %s" transform))))
4500 (orgtbl-send-replace-tbl name txt))
4501 (setq ntbl (1+ ntbl)))
4502 (message "Table converted and installed at %d receiver location%s"
4503 ntbl (if (> ntbl 1) "s" ""))
4508 (defun org-remove-by-index (list indices &optional i0)
4509 "Remove the elements in LIST with indices in INDICES.
4510 First element has index 0, or I0 if given."
4513 (if (integerp indices) (setq indices (list indices)))
4514 (setq i0 (1- (or i0 0)))
4515 (delq :rm (mapcar (lambda (x)
4517 (if (memq i0 indices) :rm x))
4520 (defun orgtbl-toggle-comment ()
4521 "Comment or uncomment the orgtbl at point."
4523 (let* ((case-fold-search t)
4524 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4525 (re2 (concat "^" orgtbl-line-start-regexp))
4526 (commented (save-excursion (beginning-of-line 1)
4527 (cond ((looking-at re1) t)
4528 ((looking-at re2) nil)
4529 (t (user-error "Not at an org table")))))
4530 (re (if commented re1 re2))
4533 (beginning-of-line 1)
4534 (while (looking-at re) (beginning-of-line 0))
4535 (beginning-of-line 2)
4537 (while (looking-at re) (beginning-of-line 2))
4539 (comment-region beg end (if commented '(4) nil))))
4541 (defun orgtbl-insert-radio-table ()
4542 "Insert a radio table template appropriate for this major mode."
4544 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4547 (unless e (user-error "No radio table setup defined for %s" major-mode))
4548 (setq name (read-string "Table name: "))
4549 (while (string-match "%n" txt)
4550 (setq txt (replace-match name t t txt)))
4551 (or (bolp) (insert "\n"))
4556 ;; Dynamically bound input and output for table formatting.
4557 (defvar *orgtbl-table* nil
4558 "Carries the current table through formatting routines.")
4559 (defvar *orgtbl-rtn* nil
4560 "Formatting routines push the output lines here.")
4561 ;; Formatting parameters for the current table section.
4562 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4563 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4564 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4565 (defvar *orgtbl-fmt* nil "Format for each entry.")
4566 (defvar *orgtbl-efmt* nil "Format for numbers.")
4567 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4568 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4569 (defvar *orgtbl-lstart* nil "Text starting a row.")
4570 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4571 (defvar *orgtbl-lend* nil "Text ending a row.")
4572 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4574 (defsubst orgtbl-get-fmt (fmt i)
4575 "Retrieve the format from FMT corresponding to the Ith column."
4576 (if (and (not (functionp fmt)) (consp fmt))
4580 (defsubst orgtbl-apply-fmt (fmt &rest args)
4581 "Apply format FMT to arguments ARGS.
4582 When FMT is nil, return the first argument from ARGS."
4583 (cond ((functionp fmt) (apply fmt args))
4584 (fmt (apply 'format fmt args))
4588 (defsubst orgtbl-eval-str (str)
4589 "If STR is a function, evaluate it with no arguments."
4594 (defun orgtbl-format-line (line)
4595 "Format LINE as a table row."
4596 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4602 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4603 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4604 (orgtbl-apply-fmt efmt (match-string 1 f)
4607 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4608 *orgtbl-default-fmt*)
4611 (push (if *orgtbl-lfmt*
4612 (apply #'orgtbl-apply-fmt *orgtbl-lfmt* line)
4613 (concat (orgtbl-eval-str *orgtbl-lstart*)
4614 (mapconcat 'identity line *orgtbl-sep*)
4615 (orgtbl-eval-str *orgtbl-lend*)))
4618 (defun orgtbl-format-section (section-stopper)
4619 "Format lines until the first occurrence of SECTION-STOPPER."
4622 (while (not (eq (car *orgtbl-table*) section-stopper))
4623 (if prevline (orgtbl-format-line prevline))
4624 (setq prevline (pop *orgtbl-table*)))
4625 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4626 (*orgtbl-lend* *orgtbl-llend*)
4627 (*orgtbl-lfmt* *orgtbl-llfmt*))
4628 (orgtbl-format-line prevline))))))
4631 (defun orgtbl-to-generic (table params &optional backend)
4632 "Convert the orgtbl-mode TABLE to some other format.
4633 This generic routine can be used for many standard cases.
4634 TABLE is a list, each entry either the symbol `hline' for a horizontal
4635 separator line, or a list of fields for that line.
4636 PARAMS is a property list of parameters that can influence the conversion.
4637 A third optional argument BACKEND can be used to convert the content of
4638 the cells using a specific export back-end.
4640 For the generic converter, some parameters are obligatory: you need to
4641 specify either :lfmt, or all of (:lstart :lend :sep).
4643 Valid parameters are:
4645 :splice When set to t, return only table body lines, don't wrap
4646 them into :tstart and :tend. Default is nil. When :splice
4647 is non-nil, this also means that the exporter should not look
4648 for and interpret header and footer sections.
4650 :hline String to be inserted on horizontal separation lines.
4651 May be nil to ignore hlines.
4653 :sep Separator between two fields
4654 :remove-nil-lines Do not include lines that evaluate to nil.
4656 Each in the following group may be either a string or a function
4657 of no arguments returning a string:
4659 :tstart String to start the table. Ignored when :splice is t.
4660 :tend String to end the table. Ignored when :splice is t.
4661 :lstart String to start a new table line.
4662 :llstart String to start the last table line, defaults to :lstart.
4663 :lend String to end a table line
4664 :llend String to end the last table line, defaults to :lend.
4666 Each in the following group may be a string, a function of one
4667 argument (the field or line) returning a string, or a plist
4668 mapping columns to either of the above:
4670 :lfmt Format for entire line, with enough %s to capture all fields.
4671 If this is present, :lstart, :lend, and :sep are ignored.
4672 :llfmt Format for the entire last line, defaults to :lfmt.
4673 :fmt A format to be used to wrap the field, should contain
4674 %s for the original field value. For example, to wrap
4675 everything in dollars, you could use :fmt \"$%s$\".
4676 This may also be a property list with column numbers and
4677 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4678 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4679 Same as above, specific for the header lines in the table.
4680 All lines before the first hline are treated as header.
4681 If any of these is not present, the data line value is used.
4683 This may be either a string or a function of two arguments:
4685 :efmt Use this format to print numbers with exponentials.
4686 The format should have %s twice for inserting mantissa
4687 and exponent, for example \"%s\\\\times10^{%s}\". This
4688 may also be a property list with column numbers and
4689 formats. :fmt will still be applied after :efmt.
4691 In addition to this, the parameters :skip and :skipcols are always handled
4692 directly by `orgtbl-send-table'. See manual."
4693 (let* ((splicep (plist-get params :splice))
4694 (hline (plist-get params :hline))
4695 (skipheadrule (plist-get params :skipheadrule))
4696 (remove-nil-linesp (plist-get params :remove-nil-lines))
4697 (remove-newlines (plist-get params :remove-newlines))
4698 (*orgtbl-hline* hline)
4699 (*orgtbl-table* table)
4700 (*orgtbl-sep* (plist-get params :sep))
4701 (*orgtbl-efmt* (plist-get params :efmt))
4702 (*orgtbl-lstart* (plist-get params :lstart))
4703 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4704 (*orgtbl-lend* (plist-get params :lend))
4705 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4706 (*orgtbl-lfmt* (plist-get params :lfmt))
4707 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4708 (*orgtbl-fmt* (plist-get params :fmt))
4710 ;; Convert cells content to backend BACKEND
4712 (setq *orgtbl-table*
4718 (org-trim (org-export-string-as c backend t '(:with-tables t))))
4724 (when (plist-member params :tstart)
4725 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4726 (if tstart (push tstart *orgtbl-rtn*)))))
4727 ;; If we have a heading, format it and handle the trailing hline.
4728 (if (and (not splicep)
4729 (or (consp (car *orgtbl-table*))
4730 (consp (nth 1 *orgtbl-table*)))
4731 (memq 'hline (cdr *orgtbl-table*)))
4733 (when (eq 'hline (car *orgtbl-table*))
4734 ;; There is a hline before the first data line
4735 (and hline (push hline *orgtbl-rtn*))
4736 (pop *orgtbl-table*))
4737 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4739 (*orgtbl-llstart* (or (plist-get params :hllstart)
4741 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4742 (*orgtbl-llend* (or (plist-get params :hllend)
4743 (plist-get params :hlend) *orgtbl-llend*))
4744 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4745 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4746 (plist-get params :hlfmt) *orgtbl-llfmt*))
4747 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4748 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4749 (orgtbl-format-section 'hline))
4750 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4751 (pop *orgtbl-table*)))
4752 ;; Now format the main section.
4753 (orgtbl-format-section nil)
4755 (when (plist-member params :tend)
4756 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4757 (if tend (push tend *orgtbl-rtn*)))))
4758 (mapconcat (if remove-newlines
4760 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4762 (nreverse (if remove-nil-linesp
4763 (remq nil *orgtbl-rtn*)
4764 *orgtbl-rtn*)) "\n")))
4767 (defun orgtbl-to-tsv (table params)
4768 "Convert the orgtbl-mode table to TAB separated material."
4769 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4771 (defun orgtbl-to-csv (table params)
4772 "Convert the orgtbl-mode table to CSV material.
4773 This does take care of the proper quoting of fields with comma or quotes."
4774 (orgtbl-to-generic table (org-combine-plists
4775 '(:sep "," :fmt org-quote-csv-field)
4779 (defun orgtbl-to-latex (table params)
4780 "Convert the orgtbl-mode TABLE to LaTeX.
4781 TABLE is a list, each entry either the symbol `hline' for a horizontal
4782 separator line, or a list of fields for that line.
4783 PARAMS is a property list of parameters that can influence the conversion.
4784 Supports all parameters from `orgtbl-to-generic'. Most important for
4787 :splice When set to t, return only table body lines, don't wrap
4788 them into a tabular environment. Default is nil.
4790 :fmt A format to be used to wrap the field, should contain %s for the
4791 original field value. For example, to wrap everything in dollars,
4792 use :fmt \"$%s$\". This may also be a property list with column
4793 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4794 The format may also be a function that formats its one argument.
4796 :efmt Format for transforming numbers with exponentials. The format
4797 should have %s twice for inserting mantissa and exponent, for
4798 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4799 This may also be a property list with column numbers and formats.
4800 The format may also be a function that formats its two arguments.
4802 :llend If you find too much space below the last line of a table,
4803 pass a value of \"\" for :llend to suppress the final \\\\.
4805 The general parameters :skip and :skipcols have already been applied when
4806 this function is called."
4807 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4808 org-table-last-alignment ""))
4811 :tstart (concat "\\begin{tabular}{" alignment "}")
4812 :tend "\\end{tabular}"
4813 :lstart "" :lend " \\\\" :sep " & "
4814 :efmt "%s\\,(%s)" :hline "\\hline")))
4816 (orgtbl-to-generic table (org-combine-plists params2 params) 'latex)))
4819 (defun orgtbl-to-html (table params)
4820 "Convert the orgtbl-mode TABLE to HTML.
4821 TABLE is a list, each entry either the symbol `hline' for a horizontal
4822 separator line, or a list of fields for that line.
4823 PARAMS is a property list of parameters that can influence the conversion.
4824 Currently this function recognizes the following parameters:
4826 :splice When set to t, return only table body lines, don't wrap
4827 them into a <table> environment. Default is nil.
4829 The general parameters :skip and :skipcols have already been applied when
4830 this function is called. The function does *not* use `orgtbl-to-generic',
4831 so you cannot specify parameters for it."
4833 (let ((output (org-export-string-as
4834 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4835 (if (not (plist-get params :splice)) output
4837 (replace-regexp-in-string
4838 "\\`<table .*>\n" ""
4839 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4842 (defun orgtbl-to-texinfo (table params)
4843 "Convert the orgtbl-mode TABLE to TeXInfo.
4844 TABLE is a list, each entry either the symbol `hline' for a horizontal
4845 separator line, or a list of fields for that line.
4846 PARAMS is a property list of parameters that can influence the conversion.
4847 Supports all parameters from `orgtbl-to-generic'. Most important for
4850 :splice nil/t When set to t, return only table body lines, don't wrap
4851 them into a multitable environment. Default is nil.
4853 :fmt fmt A format to be used to wrap the field, should contain
4854 %s for the original field value. For example, to wrap
4855 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4856 This may also be a property list with column numbers and
4857 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4858 Each format also may be a function that formats its one
4861 :cf \"f1 f2..\" The column fractions for the table. By default these
4862 are computed automatically from the width of the columns
4865 The general parameters :skip and :skipcols have already been applied when
4866 this function is called."
4867 (let* ((total (float (apply '+ org-table-last-column-widths)))
4868 (colfrac (or (plist-get params :cf)
4870 (lambda (x) (format "%.3f" (/ (float x) total)))
4871 org-table-last-column-widths " ")))
4874 :tstart (concat "@multitable @columnfractions " colfrac)
4875 :tend "@end multitable"
4876 :lstart "@item " :lend "" :sep " @tab "
4877 :hlstart "@headitem ")))
4878 (require 'ox-texinfo)
4879 (orgtbl-to-generic table (org-combine-plists params2 params) 'texinfo)))
4882 (defun orgtbl-to-orgtbl (table params)
4883 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4884 Useful when slicing one table into many. The :hline, :sep,
4885 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4886 and :tend suppress strings without splicing; they can be set to
4887 provide ORGTBL directives for the generated table."
4891 :tstart nil :tend nil
4896 (params (org-combine-plists params2 params)))
4898 (insert (orgtbl-to-generic table params))
4899 (goto-char (point-min))
4900 (while (re-search-forward org-table-hline-regexp nil t)
4902 (buffer-substring 1 (buffer-size)))))
4904 (defun orgtbl-to-table.el (table params)
4905 "Convert the orgtbl-mode TABLE into a table.el table."
4907 (insert (orgtbl-to-orgtbl table params))
4909 (replace-regexp-in-string
4911 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4913 (defun orgtbl-to-unicode (table params)
4914 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4915 You need the ascii-art-to-unicode.el package for this. You can download
4916 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4918 (insert (orgtbl-to-table.el table params))
4919 (goto-char (point-min))
4920 (if (or (featurep 'ascii-art-to-unicode)
4921 (require 'ascii-art-to-unicode nil t))
4923 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4924 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4925 "Link to ascii-art-to-unicode.el") org-stored-links))
4926 (user-error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4929 (defun org-table-get-remote-range (name-or-id form)
4930 "Get a field value or a list of values in a range from table at ID.
4932 NAME-OR-ID may be the name of a table in the current file as set
4933 by a \"#+NAME:\" directive. The first table following this line
4934 will then be used. Alternatively, it may be an ID referring to
4935 any entry, also in a different file. In this case, the first
4936 table in that entry will be referenced.
4937 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4938 \"@I$2..@II$2\". All the references must be absolute, not relative.
4940 The return value is either a single string for a single field, or a
4941 list of the fields in the rectangle."
4943 (let ((case-fold-search t) (id-loc nil)
4944 ;; Protect a bunch of variables from being overwritten
4945 ;; by the context of the remote table
4946 org-table-column-names org-table-column-name-regexp
4947 org-table-local-parameters org-table-named-field-locations
4948 org-table-current-line-types org-table-current-begin-line
4949 org-table-current-begin-pos org-table-dlines
4950 org-table-current-ncol
4951 org-table-hlines org-table-last-alignment
4952 org-table-last-column-widths org-table-last-alignment
4953 org-table-last-column-widths tbeg
4955 (setq form (org-table-convert-refs-to-rc form))
4960 (goto-char (point-min))
4961 (if (re-search-forward
4962 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
4963 (regexp-quote name-or-id) "[ \t]*$")
4965 (setq buffer (current-buffer) loc (match-beginning 0))
4966 (setq id-loc (org-id-find name-or-id 'marker))
4967 (unless (and id-loc (markerp id-loc))
4968 (user-error "Can't find remote table \"%s\"" name-or-id))
4969 (setq buffer (marker-buffer id-loc)
4970 loc (marker-position id-loc))
4971 (move-marker id-loc nil)))
4972 (with-current-buffer buffer
4978 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4979 (not (match-beginning 1)))
4980 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
4981 (setq tbeg (point-at-bol))
4982 (org-table-get-specials)
4983 (setq form (org-table-formula-substitute-names
4984 (org-table-formula-handle-first/last-rc form)))
4985 (if (and (string-match org-table-range-regexp form)
4986 (> (length (match-string 0 form)) 1))
4988 (org-table-get-range (match-string 0 form) tbeg 1))
4991 (defmacro org-define-lookup-function (mode)
4992 (let ((mode-str (symbol-name mode))
4993 (first-p (equal mode 'first))
4994 (all-p (equal mode 'all)))
4995 (let ((plural-str (if all-p "s" "")))
4996 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4997 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4998 If R-LIST is nil, return matching element%s of S-LIST.
4999 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5000 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5001 This function is generated by a call to the macro `org-define-lookup-function'."
5002 mode-str plural-str plural-str plural-str)
5003 (let ,(let ((lvars '((p (or predicate 'equal))
5005 (rl (or r-list s-list))
5007 (if first-p (add-to-list 'lvars '(match-p nil)))
5009 (while ,(if first-p '(and (not match-p) sl) 'sl)
5011 (if (funcall p val (car sl))
5013 ,(if first-p '(setq match-p t))
5014 (let ((rval (car rl)))
5015 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5016 (setq sl (cdr sl) rl (cdr rl))))
5019 (org-define-lookup-function first)
5020 (org-define-lookup-function last)
5021 (org-define-lookup-function all)
5023 (provide 'org-table)
5026 ;; generated-autoload-file: "org-loaddefs.el"
5029 ;;; org-table.el ends here