Small fixes to the guide and the manual
[org-mode.git] / lisp / org-table.el
blob3eb63b6e53ce12331def516eff8175694948ed1a
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
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.
35 ;;; Code:
37 (eval-when-compile
38 (require 'cl))
39 (require 'org)
41 (declare-function org-table-clean-before-export "org-exp"
42 (lines &optional maybe-quoted))
43 (declare-function org-format-org-table-html "org-html" (lines &optional splice))
44 (declare-function aa2u "ext:ascii-art-to-unicode" ())
45 (defvar orgtbl-mode) ; defined below
46 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
47 (defvar org-export-html-table-tag) ; defined in org-exp.el
48 (defvar constants-unit-system)
49 (defvar org-table-follow-field-mode)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, otherwise, if table is not sent, the functions
55 are not run.")
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
63 restored.
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."
68 :group 'org-table
69 :type 'boolean)
71 (defcustom orgtbl-radio-table-templates
72 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
73 % END RECEIVE ORGTBL %n
74 \\begin{comment}
75 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
76 | | |
77 \\end{comment}\n")
78 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
79 @c END RECEIVE ORGTBL %n
80 @ignore
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 | | |
83 @end ignore\n")
84 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
85 <!-- END RECEIVE ORGTBL %n -->
86 <!--
87 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
88 | | |
89 -->\n")
90 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
91 #+ END RECEIVE ORGTBL %n
93 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
94 | | |
95 "))
96 "Templates for radio tables in different major modes.
97 All occurrences of %n in a template will be replaced with the name of the
98 table, obtained by prompting the user."
99 :group 'org-table
100 :type '(repeat
101 (list (symbol :tag "Major mode")
102 (string :tag "Format"))))
104 (defgroup org-table-settings nil
105 "Settings for tables in Org-mode."
106 :tag "Org Table Settings"
107 :group 'org-table)
109 (defcustom org-table-default-size "5x2"
110 "The default size for newly created tables, Columns x Rows."
111 :group 'org-table-settings
112 :type 'string)
114 (defcustom org-table-number-regexp
115 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
116 "Regular expression for recognizing numbers in table columns.
117 If a table column contains mostly numbers, it will be aligned to the
118 right. If not, it will be aligned to the left.
120 The default value of this option is a regular expression which allows
121 anything which looks remotely like a number as used in scientific
122 context. For example, all of the following will be considered a
123 number:
124 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
126 Other options offered by the customize interface are more restrictive."
127 :group 'org-table-settings
128 :type '(choice
129 (const :tag "Positive Integers"
130 "^[0-9]+$")
131 (const :tag "Integers"
132 "^[-+]?[0-9]+$")
133 (const :tag "Floating Point Numbers"
134 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
135 (const :tag "Floating Point Number or Integer"
136 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
137 (const :tag "Exponential, Floating point, Integer"
138 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
139 (const :tag "Very General Number-Like, including hex"
140 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
141 (const :tag "Very General Number-Like, including hex, allows comma as decimal mark"
142 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
143 (string :tag "Regexp:")))
145 (defcustom org-table-number-fraction 0.5
146 "Fraction of numbers in a column required to make the column align right.
147 In a column all non-white fields are considered. If at least
148 this fraction of fields is matched by `org-table-number-regexp',
149 alignment to the right border applies."
150 :group 'org-table-settings
151 :type 'number)
153 (defgroup org-table-editing nil
154 "Behavior of tables during editing in Org-mode."
155 :tag "Org Table Editing"
156 :group 'org-table)
158 (defcustom org-table-automatic-realign t
159 "Non-nil means automatically re-align table when pressing TAB or RETURN.
160 When nil, aligning is only done with \\[org-table-align], or after column
161 removal/insertion."
162 :group 'org-table-editing
163 :type 'boolean)
165 (defcustom org-table-auto-blank-field t
166 "Non-nil means automatically blank table field when starting to type into it.
167 This only happens when typing immediately after a field motion
168 command (TAB, S-TAB or RET).
169 Only relevant when `org-enable-table-editor' is equal to `optimized'."
170 :group 'org-table-editing
171 :type 'boolean)
173 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
174 "Non-nil means automatically exit the follow mode.
175 When nil, the follow mode will stay on and be active in any table
176 the cursor enters. Since the table follow filed mode messes with the
177 window configuration, it is not recommended to set this variable to nil,
178 except maybe locally in a special file that has mostly tables with long
179 fields."
180 :group 'org-table
181 :version "24.1"
182 :type 'boolean)
184 (defcustom org-table-fix-formulas-confirm nil
185 "Whether the user should confirm when Org fixes formulas."
186 :group 'org-table-editing
187 :version "24.1"
188 :type '(choice
189 (const :tag "with yes-or-no" yes-or-no-p)
190 (const :tag "with y-or-n" y-or-n-p)
191 (const :tag "no confirmation" nil)))
192 (put 'org-table-fix-formulas-confirm
193 'safe-local-variable
194 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
196 (defcustom org-table-tab-jumps-over-hlines t
197 "Non-nil means tab in the last column of a table with jump over a hline.
198 If a horizontal separator line is following the current line,
199 `org-table-next-field' can either create a new row before that line, or jump
200 over the line. When this option is nil, a new line will be created before
201 this line."
202 :group 'org-table-editing
203 :type 'boolean)
205 (defgroup org-table-calculation nil
206 "Options concerning tables in Org-mode."
207 :tag "Org Table Calculation"
208 :group 'org-table)
210 (defcustom org-table-use-standard-references 'from
211 "Should org-mode work with table references like B3 instead of @3$2?
212 Possible values are:
213 nil never use them
214 from accept as input, do not present for editing
215 t accept as input and present for editing"
216 :group 'org-table-calculation
217 :type '(choice
218 (const :tag "Never, don't even check user input for them" nil)
219 (const :tag "Always, both as user input, and when editing" t)
220 (const :tag "Convert user input, don't offer during editing" from)))
222 (defcustom org-table-copy-increment t
223 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
224 :group 'org-table-calculation
225 :type 'boolean)
227 (defcustom org-calc-default-modes
228 '(calc-internal-prec 12
229 calc-float-format (float 8)
230 calc-angle-mode deg
231 calc-prefer-frac nil
232 calc-symbolic-mode nil
233 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
234 calc-display-working-message t
236 "List with Calc mode settings for use in `calc-eval' for table formulas.
237 The list must contain alternating symbols (Calc modes variables and values).
238 Don't remove any of the default settings, just change the values. Org-mode
239 relies on the variables to be present in the list."
240 :group 'org-table-calculation
241 :type 'plist)
243 (defcustom org-table-duration-custom-format 'hours
244 "Format for the output of calc computations like $1+$2;t.
245 The default value is 'hours, and will output the results as a
246 number of hours. Other allowed values are 'seconds, 'minutes and
247 'days, and the output will be a fraction of seconds, minutes or
248 days."
249 :group 'org-table-calculation
250 :version "24.1"
251 :type '(choice (symbol :tag "Seconds" 'seconds)
252 (symbol :tag "Minutes" 'minutes)
253 (symbol :tag "Hours " 'hours)
254 (symbol :tag "Days " 'days)))
256 (defcustom org-table-formula-field-format "%s"
257 "Format for fields which contain the result of a formula.
258 For example, using \"~%s~\" will display the result within tilde
259 characters. Beware that modifying the display can prevent the
260 field from being used in another formula."
261 :group 'org-table-settings
262 :version "24.1"
263 :type 'string)
265 (defcustom org-table-formula-evaluate-inline t
266 "Non-nil means TAB and RET evaluate a formula in current table field.
267 If the current field starts with an equal sign, it is assumed to be a formula
268 which should be evaluated as described in the manual and in the documentation
269 string of the command `org-table-eval-formula'. This feature requires the
270 Emacs calc package.
271 When this variable is nil, formula calculation is only available through
272 the command \\[org-table-eval-formula]."
273 :group 'org-table-calculation
274 :type 'boolean)
276 (defcustom org-table-formula-use-constants t
277 "Non-nil means interpret constants in formulas in tables.
278 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
279 by the value given in `org-table-formula-constants', or by a value obtained
280 from the `constants.el' package."
281 :group 'org-table-calculation
282 :type 'boolean)
284 (defcustom org-table-formula-constants nil
285 "Alist with constant names and values, for use in table formulas.
286 The car of each element is a name of a constant, without the `$' before it.
287 The cdr is the value as a string. For example, if you'd like to use the
288 speed of light in a formula, you would configure
290 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
292 and then use it in an equation like `$1*$c'.
294 Constants can also be defined on a per-file basis using a line like
296 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
297 :group 'org-table-calculation
298 :type '(repeat
299 (cons (string :tag "name")
300 (string :tag "value"))))
302 (defcustom org-table-allow-automatic-line-recalculation t
303 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
304 Automatically means when TAB or RET or C-c C-c are pressed in the line."
305 :group 'org-table-calculation
306 :type 'boolean)
308 (defcustom org-table-error-on-row-ref-crossing-hline t
309 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
310 :group 'org-table
311 :type 'boolean)
313 (defcustom org-table-relative-ref-may-cross-hline t
314 "Non-nil means relative formula references may cross hlines.
315 Here are the allowed values:
317 nil Relative references may not cross hlines. They will reference the
318 field next to the hline instead. Coming from below, the reference
319 will be to the field below the hline. Coming from above, it will be
320 to the field above.
321 t Relative references may cross hlines.
322 error An attempt to cross a hline will throw an error.
324 It is probably good to never set this variable to nil, for the sake of
325 portability of tables."
326 :group 'org-table-calculation
327 :type '(choice
328 (const :tag "Allow to cross" t)
329 (const :tag "Stick to hline" nil)
330 (const :tag "Error on attempt to cross" error)))
332 (defgroup org-table-import-export nil
333 "Options concerning table import and export in Org-mode."
334 :tag "Org Table Import Export"
335 :group 'org-table)
337 (defcustom org-table-export-default-format "orgtbl-to-tsv"
338 "Default export parameters for `org-table-export'.
339 These can be overridden for a specific table by setting the
340 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
341 radio tables for the different export transformations and
342 available parameters."
343 :group 'org-table-import-export
344 :type 'string)
346 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
347 "Detects a table line marked for automatic recalculation.")
348 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
349 "Detects a table line marked for automatic recalculation.")
350 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
351 "Detects a table line marked for automatic recalculation.")
352 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
353 "Searching from within a table (any type) this finds the first line outside the table.")
354 (defvar org-table-last-highlighted-reference nil)
355 (defvar org-table-formula-history nil)
357 (defvar org-table-column-names nil
358 "Alist with column names, derived from the `!' line.")
359 (defvar org-table-column-name-regexp nil
360 "Regular expression matching the current column names.")
361 (defvar org-table-local-parameters nil
362 "Alist with parameter names, derived from the `$' line.")
363 (defvar org-table-named-field-locations nil
364 "Alist with locations of named fields.")
366 (defvar org-table-current-line-types nil
367 "Table row types, non-nil only for the duration of a command.")
368 (defvar org-table-current-begin-line nil
369 "Table begin line, non-nil only for the duration of a command.")
370 (defvar org-table-current-begin-pos nil
371 "Table begin position, non-nil only for the duration of a command.")
372 (defvar org-table-current-ncol nil
373 "Number of columns in table, non-nil only for the duration of a command.")
374 (defvar org-table-dlines nil
375 "Vector of data line line numbers in the current table.")
376 (defvar org-table-hlines nil
377 "Vector of hline line numbers in the current table.")
379 (defconst org-table-range-regexp
380 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
381 ;; 1 2 3 4 5
382 "Regular expression for matching ranges in formulas.")
384 (defconst org-table-range-regexp2
385 (concat
386 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
387 "\\.\\."
388 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
389 "Match a range for reference display.")
391 (defun org-table-colgroup-line-p (line)
392 "Is this a table line colgroup information?"
393 (save-match-data
394 (and (string-match "[<>]\\|&[lg]t;" line)
395 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
396 line)
397 (not (delq
399 (mapcar
400 (lambda (s)
401 (not (member s '("" "<" ">" "<>" "&lt;" "&gt;" "&lt;&gt;"))))
402 (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
404 (defun org-table-cookie-line-p (line)
405 "Is this a table line with only alignment/width cookies?"
406 (save-match-data
407 (and (string-match "[<>]\\|&[lg]t;" line)
408 (or (string-match
409 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line)
410 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line))
411 (not (delq nil (mapcar
412 (lambda (s)
413 (not (or (equal s "")
414 (string-match
415 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s)
416 (string-match
417 "\\`&lt;\\([lrc]?[0-9]+\\|[lrc]\\)&gt;\\'"
418 s))))
419 (org-split-string (match-string 1 line)
420 "[ \t]*|[ \t]*")))))))
422 (defconst org-table-translate-regexp
423 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
424 "Match a reference that needs translation, for reference display.")
426 (defun org-table-create-with-table.el ()
427 "Use the table.el package to insert a new table.
428 If there is already a table at point, convert between Org-mode tables
429 and table.el tables."
430 (interactive)
431 (require 'table)
432 (cond
433 ((org-at-table.el-p)
434 (if (y-or-n-p "Convert table to Org-mode table? ")
435 (org-table-convert)))
436 ((org-at-table-p)
437 (when (y-or-n-p "Convert table to table.el table? ")
438 (org-table-align)
439 (org-table-convert)))
440 (t (call-interactively 'table-insert))))
442 (defun org-table-create-or-convert-from-region (arg)
443 "Convert region to table, or create an empty table.
444 If there is an active region, convert it to a table, using the function
445 `org-table-convert-region'. See the documentation of that function
446 to learn how the prefix argument is interpreted to determine the field
447 separator.
448 If there is no such region, create an empty table with `org-table-create'."
449 (interactive "P")
450 (if (org-region-active-p)
451 (org-table-convert-region (region-beginning) (region-end) arg)
452 (org-table-create arg)))
454 (defun org-table-create (&optional size)
455 "Query for a size and insert a table skeleton.
456 SIZE is a string Columns x Rows like for example \"3x2\"."
457 (interactive "P")
458 (unless size
459 (setq size (read-string
460 (concat "Table size Columns x Rows [e.g. "
461 org-table-default-size "]: ")
462 "" nil org-table-default-size)))
464 (let* ((pos (point))
465 (indent (make-string (current-column) ?\ ))
466 (split (org-split-string size " *x *"))
467 (rows (string-to-number (nth 1 split)))
468 (columns (string-to-number (car split)))
469 (line (concat (apply 'concat indent "|" (make-list columns " |"))
470 "\n")))
471 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
472 (point-at-bol) (point)))
473 (beginning-of-line 1)
474 (newline))
475 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
476 (dotimes (i rows) (insert line))
477 (goto-char pos)
478 (if (> rows 1)
479 ;; Insert a hline after the first row.
480 (progn
481 (end-of-line 1)
482 (insert "\n|-")
483 (goto-char pos)))
484 (org-table-align)))
486 (defun org-table-convert-region (beg0 end0 &optional separator)
487 "Convert region to a table.
488 The region goes from BEG0 to END0, but these borders will be moved
489 slightly, to make sure a beginning of line in the first line is included.
491 SEPARATOR specifies the field separator in the lines. It can have the
492 following values:
494 '(4) Use the comma as a field separator
495 '(16) Use a TAB as field separator
496 integer When a number, use that many spaces as field separator
497 nil When nil, the command tries to be smart and figure out the
498 separator in the following way:
499 - when each line contains a TAB, assume TAB-separated material
500 - when each line contains a comma, assume CSV material
501 - else, assume one or more SPACE characters as separator."
502 (interactive "rP")
503 (let* ((beg (min beg0 end0))
504 (end (max beg0 end0))
506 (goto-char beg)
507 (beginning-of-line 1)
508 (setq beg (move-marker (make-marker) (point)))
509 (goto-char end)
510 (if (bolp) (backward-char 1) (end-of-line 1))
511 (setq end (move-marker (make-marker) (point)))
512 ;; Get the right field separator
513 (unless separator
514 (goto-char beg)
515 (setq separator
516 (cond
517 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
518 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
519 (t 1))))
520 (goto-char beg)
521 (if (equal separator '(4))
522 (while (< (point) end)
523 ;; parse the csv stuff
524 (cond
525 ((looking-at "^") (insert "| "))
526 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
527 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
528 (replace-match "\\1")
529 (if (looking-at "\"") (insert "\"")))
530 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
531 ((looking-at "[ \t]*,") (replace-match " | "))
532 (t (beginning-of-line 2))))
533 (setq re (cond
534 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
535 ((equal separator '(16)) "^\\|\t")
536 ((integerp separator)
537 (if (< separator 1)
538 (error "Number of spaces in separator must be >= 1")
539 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
540 (t (error "This should not happen"))))
541 (while (re-search-forward re end t)
542 (replace-match "| " t t)))
543 (goto-char beg)
544 (org-table-align)))
546 (defun org-table-import (file arg)
547 "Import FILE as a table.
548 The file is assumed to be tab-separated. Such files can be produced by most
549 spreadsheet and database applications. If no tabs (at least one per line)
550 are found, lines will be split on whitespace into fields."
551 (interactive "f\nP")
552 (or (bolp) (newline))
553 (let ((beg (point))
554 (pm (point-max)))
555 (insert-file-contents file)
556 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
559 (defvar org-table-last-alignment)
560 (defvar org-table-last-column-widths)
561 (defun org-table-export (&optional file format)
562 "Export table to a file, with configurable format.
563 Such a file can be imported into usual spreadsheet programs.
565 FILE can be the output file name. If not given, it will be taken
566 from a TABLE_EXPORT_FILE property in the current entry or higher
567 up in the hierarchy, or the user will be prompted for a file
568 name. FORMAT can be an export format, of the same kind as it
569 used when `orgtbl-mode' sends a table in a different format.
571 The command suggests a format depending on TABLE_EXPORT_FORMAT,
572 whether it is set locally or up in the hierarchy, then on the
573 extension of the given file name, and finally on the variable
574 `org-table-export-default-format'."
575 (interactive)
576 (unless (org-at-table-p)
577 (error "No table at point"))
578 (require 'org-exp)
579 (org-table-align) ;; make sure we have everything we need
580 (let* ((beg (org-table-begin))
581 (end (org-table-end))
582 (txt (buffer-substring-no-properties beg end))
583 (file (or file (org-entry-get beg "TABLE_EXPORT_FILE" t)))
584 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
585 "orgtbl-to-latex" "orgtbl-to-html"
586 "orgtbl-to-generic" "orgtbl-to-texinfo"
587 "orgtbl-to-orgtbl"))
588 (format (or format
589 (org-entry-get beg "TABLE_EXPORT_FORMAT" t)))
590 buf deffmt-readable fileext)
591 (unless file
592 (setq file (read-file-name "Export table to: "))
593 (unless (or (not (file-exists-p file))
594 (y-or-n-p (format "Overwrite file %s? " file)))
595 (error "Abort")))
596 (if (file-directory-p file)
597 (error "This is a directory path, not a file"))
598 (if (and (buffer-file-name)
599 (equal (file-truename file)
600 (file-truename (buffer-file-name))))
601 (error "Please specify a file name that is different from current"))
602 (setq fileext (concat (file-name-extension file) "$"))
603 (unless format
604 (setq deffmt-readable
605 (or (car (delq nil (mapcar (lambda(f) (if (string-match fileext f) f)) formats)))
606 org-table-export-default-format))
607 (while (string-match "\t" deffmt-readable)
608 (setq deffmt-readable (replace-match "\\t" t t deffmt-readable)))
609 (while (string-match "\n" deffmt-readable)
610 (setq deffmt-readable (replace-match "\\n" t t deffmt-readable)))
611 (setq format (org-completing-read "Format: " formats nil nil deffmt-readable)))
612 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
613 (let* ((transform (intern (match-string 1 format)))
614 (params (if (match-end 2)
615 (read (concat "(" (match-string 2 format) ")"))))
616 (skip (plist-get params :skip))
617 (skipcols (plist-get params :skipcols))
618 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
619 (lines (org-table-clean-before-export lines))
620 (i0 (if org-table-clean-did-remove-column 2 1))
621 (table (mapcar
622 (lambda (x)
623 (if (string-match org-table-hline-regexp x)
624 'hline
625 (org-remove-by-index
626 (org-split-string (org-trim x) "\\s-*|\\s-*")
627 skipcols i0)))
628 lines))
629 (fun (if (= i0 2) 'cdr 'identity))
630 (org-table-last-alignment
631 (org-remove-by-index (funcall fun org-table-last-alignment)
632 skipcols i0))
633 (org-table-last-column-widths
634 (org-remove-by-index (funcall fun org-table-last-column-widths)
635 skipcols i0)))
637 (unless (fboundp transform)
638 (error "No such transformation function %s" transform))
639 (setq txt (funcall transform table params))
641 (with-current-buffer (find-file-noselect file)
642 (setq buf (current-buffer))
643 (erase-buffer)
644 (fundamental-mode)
645 (insert txt "\n")
646 (save-buffer))
647 (kill-buffer buf)
648 (message "Export done."))
649 (error "TABLE_EXPORT_FORMAT invalid"))))
651 (defvar org-table-aligned-begin-marker (make-marker)
652 "Marker at the beginning of the table last aligned.
653 Used to check if cursor still is in that table, to minimize realignment.")
654 (defvar org-table-aligned-end-marker (make-marker)
655 "Marker at the end of the table last aligned.
656 Used to check if cursor still is in that table, to minimize realignment.")
657 (defvar org-table-last-alignment nil
658 "List of flags for flushright alignment, from the last re-alignment.
659 This is being used to correctly align a single field after TAB or RET.")
660 (defvar org-table-last-column-widths nil
661 "List of max width of fields in each column.
662 This is being used to correctly align a single field after TAB or RET.")
663 (defvar org-table-formula-debug nil
664 "Non-nil means debug table formulas.
665 When nil, simply write \"#ERROR\" in corrupted fields.")
666 (make-variable-buffer-local 'org-table-formula-debug)
667 (defvar org-table-overlay-coordinates nil
668 "Overlay coordinates after each align of a table.")
669 (make-variable-buffer-local 'org-table-overlay-coordinates)
671 (defvar org-last-recalc-line nil)
672 (defvar org-table-do-narrow t) ; for dynamic scoping
673 (defconst org-narrow-column-arrow "=>"
674 "Used as display property in narrowed table columns.")
676 (defun org-table-align ()
677 "Align the table at point by aligning all vertical bars."
678 (interactive)
679 (let* (
680 ;; Limits of table
681 (beg (org-table-begin))
682 (end (org-table-end))
683 ;; Current cursor position
684 (linepos (org-current-line))
685 (colpos (org-table-current-column))
686 (winstart (window-start))
687 (winstartline (org-current-line (min winstart (1- (point-max)))))
688 lines (new "") lengths l typenums ty fields maxfields i
689 column
690 (indent "") cnt frac
691 rfmt hfmt
692 (spaces '(1 . 1))
693 (sp1 (car spaces))
694 (sp2 (cdr spaces))
695 (rfmt1 (concat
696 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
697 (hfmt1 (concat
698 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
699 emptystrings links dates emph raise narrow
700 falign falign1 fmax f1 len c e space)
701 (untabify beg end)
702 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
703 ;; Check if we have links or dates
704 (goto-char beg)
705 (setq links (re-search-forward org-bracket-link-regexp end t))
706 (goto-char beg)
707 (setq emph (and org-hide-emphasis-markers
708 (re-search-forward org-emph-re end t)))
709 (goto-char beg)
710 (setq raise (and org-use-sub-superscripts
711 (re-search-forward org-match-substring-regexp end t)))
712 (goto-char beg)
713 (setq dates (and org-display-custom-times
714 (re-search-forward org-ts-regexp-both end t)))
715 ;; Make sure the link properties are right
716 (when links (goto-char beg) (while (org-activate-bracket-links end)))
717 ;; Make sure the date properties are right
718 (when dates (goto-char beg) (while (org-activate-dates end)))
719 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
720 (when raise (goto-char beg) (while (org-raise-scripts end)))
722 ;; Check if we are narrowing any columns
723 (goto-char beg)
724 (setq narrow (and org-table-do-narrow
725 org-format-transports-properties-p
726 (re-search-forward "<[lrc]?[0-9]+>" end t)))
727 (goto-char beg)
728 (setq falign (re-search-forward "<[lrc][0-9]*>" end t))
729 (goto-char beg)
730 ;; Get the rows
731 (setq lines (org-split-string
732 (buffer-substring beg end) "\n"))
733 ;; Store the indentation of the first line
734 (if (string-match "^ *" (car lines))
735 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
736 ;; Mark the hlines by setting the corresponding element to nil
737 ;; At the same time, we remove trailing space.
738 (setq lines (mapcar (lambda (l)
739 (if (string-match "^ *|-" l)
741 (if (string-match "[ \t]+$" l)
742 (substring l 0 (match-beginning 0))
743 l)))
744 lines))
745 ;; Get the data fields by splitting the lines.
746 (setq fields (mapcar
747 (lambda (l)
748 (org-split-string l " *| *"))
749 (delq nil (copy-sequence lines))))
750 ;; How many fields in the longest line?
751 (condition-case nil
752 (setq maxfields (apply 'max (mapcar 'length fields)))
753 (error
754 (kill-region beg end)
755 (org-table-create org-table-default-size)
756 (error "Empty table - created default table")))
757 ;; A list of empty strings to fill any short rows on output
758 (setq emptystrings (make-list maxfields ""))
759 ;; Check for special formatting.
760 (setq i -1)
761 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
762 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
763 ;; Check if there is an explicit width specified
764 (setq fmax nil)
765 (when (or narrow falign)
766 (setq c column fmax nil falign1 nil)
767 (while c
768 (setq e (pop c))
769 (when (and (stringp e) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e))
770 (if (match-end 1) (setq falign1 (match-string 1 e)))
771 (if (and org-table-do-narrow (match-end 2))
772 (setq fmax (string-to-number (match-string 2 e)) c nil))))
773 ;; Find fields that are wider than fmax, and shorten them
774 (when fmax
775 (loop for xx in column do
776 (when (and (stringp xx)
777 (> (org-string-width xx) fmax))
778 (org-add-props xx nil
779 'help-echo
780 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
781 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
782 (unless (> f1 1)
783 (error "Cannot narrow field starting with wide link \"%s\""
784 (match-string 0 xx)))
785 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
786 (add-text-properties (- f1 2) f1
787 (list 'display org-narrow-column-arrow)
788 xx)))))
789 ;; Get the maximum width for each column
790 (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
791 lengths)
792 ;; Get the fraction of numbers, to decide about alignment of the column
793 (if falign1
794 (push (equal (downcase falign1) "r") typenums)
795 (setq cnt 0 frac 0.0)
796 (loop for x in column do
797 (if (equal x "")
799 (setq frac ( / (+ (* frac cnt)
800 (if (string-match org-table-number-regexp x) 1 0))
801 (setq cnt (1+ cnt))))))
802 (push (>= frac org-table-number-fraction) typenums)))
803 (setq lengths (nreverse lengths) typenums (nreverse typenums))
805 ;; Store the alignment of this table, for later editing of single fields
806 (setq org-table-last-alignment typenums
807 org-table-last-column-widths lengths)
809 ;; With invisible characters, `format' does not get the field width right
810 ;; So we need to make these fields wide by hand.
811 (when (or links emph raise)
812 (loop for i from 0 upto (1- maxfields) do
813 (setq len (nth i lengths))
814 (loop for j from 0 upto (1- (length fields)) do
815 (setq c (nthcdr i (car (nthcdr j fields))))
816 (if (and (stringp (car c))
817 (or (text-property-any 0 (length (car c))
818 'invisible 'org-link (car c))
819 (text-property-any 0 (length (car c))
820 'org-dwidth t (car c)))
821 (< (org-string-width (car c)) len))
822 (progn
823 (setq space (make-string (- len (org-string-width (car c))) ?\ ))
824 (setcar c (if (nth i typenums)
825 (concat space (car c))
826 (concat (car c) space))))))))
828 ;; Compute the formats needed for output of the table
829 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
830 (while (setq l (pop lengths))
831 (setq ty (if (pop typenums) "" "-")) ; number types flushright
832 (setq rfmt (concat rfmt (format rfmt1 ty l))
833 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
834 (setq rfmt (concat rfmt "\n")
835 hfmt (concat (substring hfmt 0 -1) "|\n"))
837 (setq new (mapconcat
838 (lambda (l)
839 (if l (apply 'format rfmt
840 (append (pop fields) emptystrings))
841 hfmt))
842 lines ""))
843 (move-marker org-table-aligned-begin-marker (point))
844 (insert new)
845 ;; Replace the old one
846 (delete-region (point) end)
847 (move-marker end nil)
848 (move-marker org-table-aligned-end-marker (point))
849 (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
850 (goto-char org-table-aligned-begin-marker)
851 (while (org-hide-wide-columns org-table-aligned-end-marker)))
852 ;; Try to move to the old location
853 (org-goto-line winstartline)
854 (setq winstart (point-at-bol))
855 (org-goto-line linepos)
856 (set-window-start (selected-window) winstart 'noforce)
857 (org-table-goto-column colpos)
858 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
859 (setq org-table-may-need-update nil)
862 (defun org-table-begin (&optional table-type)
863 "Find the beginning of the table and return its position.
864 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
865 (save-excursion
866 (if (not (re-search-backward
867 (if table-type org-table-any-border-regexp
868 org-table-border-regexp)
869 nil t))
870 (progn (goto-char (point-min)) (point))
871 (goto-char (match-beginning 0))
872 (beginning-of-line 2)
873 (point))))
875 (defun org-table-end (&optional table-type)
876 "Find the end of the table and return its position.
877 With argument TABLE-TYPE, go to the end of a table.el-type table."
878 (save-excursion
879 (if (not (re-search-forward
880 (if table-type org-table-any-border-regexp
881 org-table-border-regexp)
882 nil t))
883 (goto-char (point-max))
884 (goto-char (match-beginning 0)))
885 (point-marker)))
887 (defun org-table-justify-field-maybe (&optional new)
888 "Justify the current field, text to left, number to right.
889 Optional argument NEW may specify text to replace the current field content."
890 (cond
891 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
892 ((org-at-table-hline-p))
893 ((and (not new)
894 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
895 (current-buffer)))
896 (< (point) org-table-aligned-begin-marker)
897 (>= (point) org-table-aligned-end-marker)))
898 ;; This is not the same table, force a full re-align
899 (setq org-table-may-need-update t))
900 (t ;; realign the current field, based on previous full realign
901 (let* ((pos (point)) s
902 (col (org-table-current-column))
903 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
904 l f n o e)
905 (when (> col 0)
906 (skip-chars-backward "^|\n")
907 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
908 (progn
909 (setq s (match-string 1)
910 o (match-string 0)
911 l (max 1 (- (match-end 0) (match-beginning 0) 3))
912 e (not (= (match-beginning 2) (match-end 2))))
913 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
914 l (if e "|" (setq org-table-may-need-update t) ""))
915 n (format f s))
916 (if new
917 (if (<= (length new) l) ;; FIXME: length -> str-width?
918 (setq n (format f new))
919 (setq n (concat new "|") org-table-may-need-update t)))
920 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
921 (or (equal n o)
922 (let (org-table-may-need-update)
923 (replace-match n t t))))
924 (setq org-table-may-need-update t))
925 (goto-char pos))))))
927 (defun org-table-next-field ()
928 "Go to the next field in the current table, creating new lines as needed.
929 Before doing so, re-align the table if necessary."
930 (interactive)
931 (org-table-maybe-eval-formula)
932 (org-table-maybe-recalculate-line)
933 (if (and org-table-automatic-realign
934 org-table-may-need-update)
935 (org-table-align))
936 (let ((end (org-table-end)))
937 (if (org-at-table-hline-p)
938 (end-of-line 1))
939 (condition-case nil
940 (progn
941 (re-search-forward "|" end)
942 (if (looking-at "[ \t]*$")
943 (re-search-forward "|" end))
944 (if (and (looking-at "-")
945 org-table-tab-jumps-over-hlines
946 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
947 (goto-char (match-beginning 1)))
948 (if (looking-at "-")
949 (progn
950 (beginning-of-line 0)
951 (org-table-insert-row 'below))
952 (if (looking-at " ") (forward-char 1))))
953 (error
954 (org-table-insert-row 'below)))))
956 (defun org-table-previous-field ()
957 "Go to the previous field in the table.
958 Before doing so, re-align the table if necessary."
959 (interactive)
960 (org-table-justify-field-maybe)
961 (org-table-maybe-recalculate-line)
962 (if (and org-table-automatic-realign
963 org-table-may-need-update)
964 (org-table-align))
965 (if (org-at-table-hline-p)
966 (end-of-line 1))
967 (condition-case nil
968 (progn
969 (re-search-backward "|" (org-table-begin))
970 (re-search-backward "|" (org-table-begin)))
971 (error (error "Cannot move to previous table field")))
972 (while (looking-at "|\\(-\\|[ \t]*$\\)")
973 (re-search-backward "|" (org-table-begin)))
974 (if (looking-at "| ?")
975 (goto-char (match-end 0))))
977 (defun org-table-beginning-of-field (&optional n)
978 "Move to the end of the current table field.
979 If already at or after the end, move to the end of the next table field.
980 With numeric argument N, move N-1 fields forward first."
981 (interactive "p")
982 (let ((pos (point)))
983 (while (> n 1)
984 (setq n (1- n))
985 (org-table-previous-field))
986 (if (not (re-search-backward "|" (point-at-bol 0) t))
987 (error "No more table fields before the current")
988 (goto-char (match-end 0))
989 (and (looking-at " ") (forward-char 1)))
990 (if (>= (point) pos) (org-table-beginning-of-field 2))))
992 (defun org-table-end-of-field (&optional n)
993 "Move to the beginning of the current table field.
994 If already at or before the beginning, move to the beginning of the
995 previous field.
996 With numeric argument N, move N-1 fields backward first."
997 (interactive "p")
998 (let ((pos (point)))
999 (while (> n 1)
1000 (setq n (1- n))
1001 (org-table-next-field))
1002 (when (re-search-forward "|" (point-at-eol 1) t)
1003 (backward-char 1)
1004 (skip-chars-backward " ")
1005 (if (and (equal (char-before (point)) ?|) (looking-at " "))
1006 (forward-char 1)))
1007 (if (<= (point) pos) (org-table-end-of-field 2))))
1009 (defun org-table-next-row ()
1010 "Go to the next row (same column) in the current table.
1011 Before doing so, re-align the table if necessary."
1012 (interactive)
1013 (org-table-maybe-eval-formula)
1014 (org-table-maybe-recalculate-line)
1015 (if (or (looking-at "[ \t]*$")
1016 (save-excursion (skip-chars-backward " \t") (bolp)))
1017 (newline)
1018 (if (and org-table-automatic-realign
1019 org-table-may-need-update)
1020 (org-table-align))
1021 (let ((col (org-table-current-column)))
1022 (beginning-of-line 2)
1023 (if (or (not (org-at-table-p))
1024 (org-at-table-hline-p))
1025 (progn
1026 (beginning-of-line 0)
1027 (org-table-insert-row 'below)))
1028 (org-table-goto-column col)
1029 (skip-chars-backward "^|\n\r")
1030 (if (looking-at " ") (forward-char 1)))))
1032 (defun org-table-copy-down (n)
1033 "Copy a field down in the current column.
1034 If the field at the cursor is empty, copy into it the content of
1035 the nearest non-empty field above. With argument N, use the Nth
1036 non-empty field. If the current field is not empty, it is copied
1037 down to the next row, and the cursor is moved with it.
1038 Therefore, repeating this command causes the column to be filled
1039 row-by-row.
1040 If the variable `org-table-copy-increment' is non-nil and the
1041 field is an integer or a timestamp, it will be incremented while
1042 copying. In the case of a timestamp, increment by one day."
1043 (interactive "p")
1044 (let* ((colpos (org-table-current-column))
1045 (col (current-column))
1046 (field (org-table-get-field))
1047 (non-empty (string-match "[^ \t]" field))
1048 (beg (org-table-begin))
1049 (orig-n n)
1050 txt)
1051 (org-table-check-inside-data-field)
1052 (if non-empty
1053 (progn
1054 (setq txt (org-trim field))
1055 (org-table-next-row)
1056 (org-table-blank-field))
1057 (save-excursion
1058 (setq txt
1059 (catch 'exit
1060 (while (progn (beginning-of-line 1)
1061 (re-search-backward org-table-dataline-regexp
1062 beg t))
1063 (org-table-goto-column colpos t)
1064 (if (and (looking-at
1065 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1066 (<= (setq n (1- n)) 0))
1067 (throw 'exit (match-string 1))))))))
1068 (if txt
1069 (progn
1070 (if (and org-table-copy-increment
1071 (not (equal orig-n 0))
1072 (string-match "^[0-9]+$" txt)
1073 (< (string-to-number txt) 100000000))
1074 (setq txt (format "%d" (+ (string-to-number txt) 1))))
1075 (insert txt)
1076 (org-move-to-column col)
1077 (if (and org-table-copy-increment (org-at-timestamp-p t))
1078 (org-timestamp-up-day)
1079 (org-table-maybe-recalculate-line))
1080 (org-table-align)
1081 (org-move-to-column col))
1082 (error "No non-empty field found"))))
1084 (defun org-table-check-inside-data-field (&optional noerror)
1085 "Is point inside a table data field?
1086 I.e. not on a hline or before the first or after the last column?
1087 This actually throws an error, so it aborts the current command."
1088 (if (or (not (org-at-table-p))
1089 (= (org-table-current-column) 0)
1090 (org-at-table-hline-p)
1091 (looking-at "[ \t]*$"))
1092 (if noerror
1094 (error "Not in table data field"))
1097 (defvar org-table-clip nil
1098 "Clipboard for table regions.")
1100 (defun org-table-get (line column)
1101 "Get the field in table line LINE, column COLUMN.
1102 If LINE is larger than the number of data lines in the table, the function
1103 returns nil. However, if COLUMN is too large, we will simply return an
1104 empty string.
1105 If LINE is nil, use the current line.
1106 If column is nil, use the current column."
1107 (setq column (or column (org-table-current-column)))
1108 (save-excursion
1109 (and (or (not line) (org-table-goto-line line))
1110 (org-trim (org-table-get-field column)))))
1112 (defun org-table-put (line column value &optional align)
1113 "Put VALUE into line LINE, column COLUMN.
1114 When ALIGN is set, also realign the table."
1115 (setq column (or column (org-table-current-column)))
1116 (prog1 (save-excursion
1117 (and (or (not line) (org-table-goto-line line))
1118 (progn (org-table-goto-column column nil 'force) t)
1119 (org-table-get-field column value)))
1120 (and align (org-table-align))))
1122 (defun org-table-current-line ()
1123 "Return the index of the current data line."
1124 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1125 (save-excursion
1126 (goto-char (org-table-begin))
1127 (while (and (re-search-forward org-table-dataline-regexp end t)
1128 (setq cnt (1+ cnt))
1129 (< (point-at-eol) pos))))
1130 cnt))
1132 (defun org-table-goto-line (N)
1133 "Go to the Nth data line in the current table.
1134 Return t when the line exists, nil if it does not exist."
1135 (goto-char (org-table-begin))
1136 (let ((end (org-table-end)) (cnt 0))
1137 (while (and (re-search-forward org-table-dataline-regexp end t)
1138 (< (setq cnt (1+ cnt)) N)))
1139 (= cnt N)))
1141 (defun org-table-blank-field ()
1142 "Blank the current table field or active region."
1143 (interactive)
1144 (org-table-check-inside-data-field)
1145 (if (and (org-called-interactively-p 'any) (org-region-active-p))
1146 (let (org-table-clip)
1147 (org-table-cut-region (region-beginning) (region-end)))
1148 (skip-chars-backward "^|")
1149 (backward-char 1)
1150 (if (looking-at "|[^|\n]+")
1151 (let* ((pos (match-beginning 0))
1152 (match (match-string 0))
1153 (len (org-string-width match)))
1154 (replace-match (concat "|" (make-string (1- len) ?\ )))
1155 (goto-char (+ 2 pos))
1156 (substring match 1)))))
1158 (defun org-table-get-field (&optional n replace)
1159 "Return the value of the field in column N of current row.
1160 N defaults to current field.
1161 If REPLACE is a string, replace field with this value. The return value
1162 is always the old value."
1163 (and n (org-table-goto-column n))
1164 (skip-chars-backward "^|\n")
1165 (backward-char 1)
1166 (if (looking-at "|[^|\r\n]*")
1167 (let* ((pos (match-beginning 0))
1168 (val (buffer-substring (1+ pos) (match-end 0))))
1169 (if replace
1170 (replace-match (concat "|" (if (equal replace "") " " replace))
1171 t t))
1172 (goto-char (min (point-at-eol) (+ 2 pos)))
1173 val)
1174 (forward-char 1) ""))
1176 (defun org-table-field-info (arg)
1177 "Show info about the current field, and highlight any reference at point."
1178 (interactive "P")
1179 (org-table-get-specials)
1180 (save-excursion
1181 (let* ((pos (point))
1182 (col (org-table-current-column))
1183 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1184 (name (car (rassoc (list (org-current-line) col)
1185 org-table-named-field-locations)))
1186 (eql (org-table-expand-lhs-ranges
1187 (mapcar
1188 (lambda (e)
1189 (cons (org-table-formula-handle-first/last-rc
1190 (car e)) (cdr e)))
1191 (org-table-get-stored-formulas))))
1192 (dline (org-table-current-dline))
1193 (ref (format "@%d$%d" dline col))
1194 (ref1 (org-table-convert-refs-to-an ref))
1195 (fequation (or (assoc name eql) (assoc ref eql)))
1196 (cequation (assoc (int-to-string col) eql))
1197 (eqn (or fequation cequation)))
1198 (if (and eqn (get-text-property 0 :orig-eqn (car eqn)))
1199 (setq eqn (get-text-property 0 :orig-eqn (car eqn))))
1200 (goto-char pos)
1201 (condition-case nil
1202 (org-table-show-reference 'local)
1203 (error nil))
1204 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1205 dline col
1206 (if cname (concat " or $" cname) "")
1207 dline col ref1
1208 (if name (concat " or $" name) "")
1209 ;; FIXME: formula info not correct if special table line
1210 (if eqn
1211 (concat ", formula: "
1212 (org-table-formula-to-user
1213 (concat
1214 (if (string-match "^[$@]"(car eqn)) "" "$")
1215 (car eqn) "=" (cdr eqn))))
1216 "")))))
1218 (defun org-table-current-column ()
1219 "Find out which column we are in."
1220 (interactive)
1221 (if (org-called-interactively-p 'any) (org-table-check-inside-data-field))
1222 (save-excursion
1223 (let ((cnt 0) (pos (point)))
1224 (beginning-of-line 1)
1225 (while (search-forward "|" pos t)
1226 (setq cnt (1+ cnt)))
1227 (when (org-called-interactively-p 'interactive)
1228 (message "In table column %d" cnt))
1229 cnt)))
1231 (defun org-table-current-dline ()
1232 "Find out what table data line we are in.
1233 Only data lines count for this."
1234 (interactive)
1235 (when (org-called-interactively-p 'any)
1236 (org-table-check-inside-data-field))
1237 (save-excursion
1238 (let ((cnt 0) (pos (point)))
1239 (goto-char (org-table-begin))
1240 (while (<= (point) pos)
1241 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1242 (beginning-of-line 2))
1243 (when (org-called-interactively-p 'any)
1244 (message "This is table line %d" cnt))
1245 cnt)))
1247 (defun org-table-goto-column (n &optional on-delim force)
1248 "Move the cursor to the Nth column in the current table line.
1249 With optional argument ON-DELIM, stop with point before the left delimiter
1250 of the field.
1251 If there are less than N fields, just go to after the last delimiter.
1252 However, when FORCE is non-nil, create new columns if necessary."
1253 (interactive "p")
1254 (beginning-of-line 1)
1255 (when (> n 0)
1256 (while (and (> (setq n (1- n)) -1)
1257 (or (search-forward "|" (point-at-eol) t)
1258 (and force
1259 (progn (end-of-line 1)
1260 (skip-chars-backward "^|")
1261 (insert " | ")
1262 t)))))
1263 (when (and force (not (looking-at ".*|")))
1264 (save-excursion (end-of-line 1) (insert " | ")))
1265 (if on-delim
1266 (backward-char 1)
1267 (if (looking-at " ") (forward-char 1)))))
1269 (defun org-table-insert-column ()
1270 "Insert a new column into the table."
1271 (interactive)
1272 (if (not (org-at-table-p))
1273 (error "Not at a table"))
1274 (org-table-find-dataline)
1275 (let* ((col (max 1 (org-table-current-column)))
1276 (beg (org-table-begin))
1277 (end (org-table-end))
1278 ;; Current cursor position
1279 (linepos (org-current-line))
1280 (colpos col))
1281 (goto-char beg)
1282 (while (< (point) end)
1283 (if (org-at-table-hline-p)
1285 (org-table-goto-column col t)
1286 (insert "| "))
1287 (beginning-of-line 2))
1288 (move-marker end nil)
1289 (org-goto-line linepos)
1290 (org-table-goto-column colpos)
1291 (org-table-align)
1292 (when (or (not org-table-fix-formulas-confirm)
1293 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1294 (org-table-fix-formulas "$" nil (1- col) 1)
1295 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1297 (defun org-table-find-dataline ()
1298 "Find a data line in the current table, which is needed for column commands."
1299 (if (and (org-at-table-p)
1300 (not (org-at-table-hline-p)))
1302 (let ((col (current-column))
1303 (end (org-table-end)))
1304 (org-move-to-column col)
1305 (while (and (< (point) end)
1306 (or (not (= (current-column) col))
1307 (org-at-table-hline-p)))
1308 (beginning-of-line 2)
1309 (org-move-to-column col))
1310 (if (and (org-at-table-p)
1311 (not (org-at-table-hline-p)))
1313 (error
1314 "Please position cursor in a data line for column operations")))))
1316 (defun org-table-line-to-dline (line &optional above)
1317 "Turn a buffer line number into a data line number.
1318 If there is no data line in this line, return nil.
1319 If there is no matching dline (most likely te reference was a hline), the
1320 first dline below it is used. When ABOVE is non-nil, the one above is used."
1321 (catch 'exit
1322 (let ((ll (length org-table-dlines))
1324 (if above
1325 (progn
1326 (setq i (1- ll))
1327 (while (> i 0)
1328 (if (<= (aref org-table-dlines i) line)
1329 (throw 'exit i))
1330 (setq i (1- i))))
1331 (setq i 1)
1332 (while (< i ll)
1333 (if (>= (aref org-table-dlines i) line)
1334 (throw 'exit i))
1335 (setq i (1+ i)))))
1336 nil))
1338 (defun org-table-delete-column ()
1339 "Delete a column from the table."
1340 (interactive)
1341 (if (not (org-at-table-p))
1342 (error "Not at a table"))
1343 (org-table-find-dataline)
1344 (org-table-check-inside-data-field)
1345 (let* ((col (org-table-current-column))
1346 (beg (org-table-begin))
1347 (end (org-table-end))
1348 ;; Current cursor position
1349 (linepos (org-current-line))
1350 (colpos col))
1351 (goto-char beg)
1352 (while (< (point) end)
1353 (if (org-at-table-hline-p)
1355 (org-table-goto-column col t)
1356 (and (looking-at "|[^|\n]+|")
1357 (replace-match "|")))
1358 (beginning-of-line 2))
1359 (move-marker end nil)
1360 (org-goto-line linepos)
1361 (org-table-goto-column colpos)
1362 (org-table-align)
1363 (when (or (not org-table-fix-formulas-confirm)
1364 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1365 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1366 col -1 col)
1367 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1368 col -1 col))))
1370 (defun org-table-move-column-right ()
1371 "Move column to the right."
1372 (interactive)
1373 (org-table-move-column nil))
1374 (defun org-table-move-column-left ()
1375 "Move column to the left."
1376 (interactive)
1377 (org-table-move-column 'left))
1379 (defun org-table-move-column (&optional left)
1380 "Move the current column to the right. With arg LEFT, move to the left."
1381 (interactive "P")
1382 (if (not (org-at-table-p))
1383 (error "Not at a table"))
1384 (org-table-find-dataline)
1385 (org-table-check-inside-data-field)
1386 (let* ((col (org-table-current-column))
1387 (col1 (if left (1- col) col))
1388 (beg (org-table-begin))
1389 (end (org-table-end))
1390 ;; Current cursor position
1391 (linepos (org-current-line))
1392 (colpos (if left (1- col) (1+ col))))
1393 (if (and left (= col 1))
1394 (error "Cannot move column further left"))
1395 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1396 (error "Cannot move column further right"))
1397 (goto-char beg)
1398 (while (< (point) end)
1399 (if (org-at-table-hline-p)
1401 (org-table-goto-column col1 t)
1402 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1403 (replace-match "|\\2|\\1|")))
1404 (beginning-of-line 2))
1405 (move-marker end nil)
1406 (org-goto-line linepos)
1407 (org-table-goto-column colpos)
1408 (org-table-align)
1409 (when (or (not org-table-fix-formulas-confirm)
1410 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1411 (org-table-fix-formulas
1412 "$" (list (cons (number-to-string col) (number-to-string colpos))
1413 (cons (number-to-string colpos) (number-to-string col))))
1414 (org-table-fix-formulas
1415 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1416 (cons (number-to-string colpos) (number-to-string col)))))))
1418 (defun org-table-move-row-down ()
1419 "Move table row down."
1420 (interactive)
1421 (org-table-move-row nil))
1422 (defun org-table-move-row-up ()
1423 "Move table row up."
1424 (interactive)
1425 (org-table-move-row 'up))
1427 (defun org-table-move-row (&optional up)
1428 "Move the current table line down. With arg UP, move it up."
1429 (interactive "P")
1430 (let* ((col (current-column))
1431 (pos (point))
1432 (hline1p (save-excursion (beginning-of-line 1)
1433 (looking-at org-table-hline-regexp)))
1434 (dline1 (org-table-current-dline))
1435 (dline2 (+ dline1 (if up -1 1)))
1436 (tonew (if up 0 2))
1437 txt hline2p)
1438 (beginning-of-line tonew)
1439 (unless (org-at-table-p)
1440 (goto-char pos)
1441 (error "Cannot move row further"))
1442 (setq hline2p (looking-at org-table-hline-regexp))
1443 (goto-char pos)
1444 (beginning-of-line 1)
1445 (setq pos (point))
1446 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1447 (delete-region (point) (1+ (point-at-eol)))
1448 (beginning-of-line tonew)
1449 (insert txt)
1450 (beginning-of-line 0)
1451 (org-move-to-column col)
1452 (unless (or hline1p hline2p
1453 (not (or (not org-table-fix-formulas-confirm)
1454 (funcall org-table-fix-formulas-confirm
1455 "Fix formulas? "))))
1456 (org-table-fix-formulas
1457 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1458 (cons (number-to-string dline2) (number-to-string dline1)))))))
1460 (defun org-table-insert-row (&optional arg)
1461 "Insert a new row above the current line into the table.
1462 With prefix ARG, insert below the current line."
1463 (interactive "P")
1464 (if (not (org-at-table-p))
1465 (error "Not at a table"))
1466 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1467 (new (org-table-clean-line line)))
1468 ;; Fix the first field if necessary
1469 (if (string-match "^[ \t]*| *[#$] *|" line)
1470 (setq new (replace-match (match-string 0 line) t t new)))
1471 (beginning-of-line (if arg 2 1))
1472 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1473 (beginning-of-line 0)
1474 (re-search-forward "| ?" (point-at-eol) t)
1475 (and (or org-table-may-need-update org-table-overlay-coordinates)
1476 (org-table-align))
1477 (when (or (not org-table-fix-formulas-confirm)
1478 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1479 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1481 (defun org-table-insert-hline (&optional above)
1482 "Insert a horizontal-line below the current line into the table.
1483 With prefix ABOVE, insert above the current line."
1484 (interactive "P")
1485 (if (not (org-at-table-p))
1486 (error "Not at a table"))
1487 (when (eobp) (insert "\n") (backward-char 1))
1488 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1489 (org-table-align))
1490 (let ((line (org-table-clean-line
1491 (buffer-substring (point-at-bol) (point-at-eol))))
1492 (col (current-column)))
1493 (while (string-match "|\\( +\\)|" line)
1494 (setq line (replace-match
1495 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1496 ?-) "|") t t line)))
1497 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1498 (beginning-of-line (if above 1 2))
1499 (insert line "\n")
1500 (beginning-of-line (if above 1 -1))
1501 (org-move-to-column col)
1502 (and org-table-overlay-coordinates (org-table-align))))
1504 (defun org-table-hline-and-move (&optional same-column)
1505 "Insert a hline and move to the row below that line."
1506 (interactive "P")
1507 (let ((col (org-table-current-column)))
1508 (org-table-maybe-eval-formula)
1509 (org-table-maybe-recalculate-line)
1510 (org-table-insert-hline)
1511 (end-of-line 2)
1512 (if (looking-at "\n[ \t]*|-")
1513 (progn (insert "\n|") (org-table-align))
1514 (org-table-next-field))
1515 (if same-column (org-table-goto-column col))))
1517 (defun org-table-clean-line (s)
1518 "Convert a table line S into a string with only \"|\" and space.
1519 In particular, this does handle wide and invisible characters."
1520 (if (string-match "^[ \t]*|-" s)
1521 ;; It's a hline, just map the characters
1522 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1523 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1524 (setq s (replace-match
1525 (concat "|" (make-string (org-string-width (match-string 1 s))
1526 ?\ ) "|")
1527 t t s)))
1530 (defun org-table-kill-row ()
1531 "Delete the current row or horizontal line from the table."
1532 (interactive)
1533 (if (not (org-at-table-p))
1534 (error "Not at a table"))
1535 (let ((col (current-column))
1536 (dline (org-table-current-dline)))
1537 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1538 (if (not (org-at-table-p)) (beginning-of-line 0))
1539 (org-move-to-column col)
1540 (when (or (not org-table-fix-formulas-confirm)
1541 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1542 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1543 dline -1 dline))))
1545 (defun org-table-sort-lines (with-case &optional sorting-type)
1546 "Sort table lines according to the column at point.
1548 The position of point indicates the column to be used for
1549 sorting, and the range of lines is the range between the nearest
1550 horizontal separator lines, or the entire table of no such lines
1551 exist. If point is before the first column, you will be prompted
1552 for the sorting column. If there is an active region, the mark
1553 specifies the first line and the sorting column, while point
1554 should be in the last line to be included into the sorting.
1556 The command then prompts for the sorting type which can be
1557 alphabetically, numerically, or by time (as given in a time stamp
1558 in the field). Sorting in reverse order is also possible.
1560 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1562 If SORTING-TYPE is specified when this function is called from a Lisp
1563 program, no prompting will take place. SORTING-TYPE must be a character,
1564 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1565 should be done in reverse order."
1566 (interactive "P")
1567 (let* ((thisline (org-current-line))
1568 (thiscol (org-table-current-column))
1569 beg end bcol ecol tend tbeg column lns pos)
1570 (when (equal thiscol 0)
1571 (if (org-called-interactively-p 'any)
1572 (setq thiscol
1573 (string-to-number
1574 (read-string "Use column N for sorting: ")))
1575 (setq thiscol 1))
1576 (org-table-goto-column thiscol))
1577 (org-table-check-inside-data-field)
1578 (if (org-region-active-p)
1579 (progn
1580 (setq beg (region-beginning) end (region-end))
1581 (goto-char beg)
1582 (setq column (org-table-current-column)
1583 beg (point-at-bol))
1584 (goto-char end)
1585 (setq end (point-at-bol 2)))
1586 (setq column (org-table-current-column)
1587 pos (point)
1588 tbeg (org-table-begin)
1589 tend (org-table-end))
1590 (if (re-search-backward org-table-hline-regexp tbeg t)
1591 (setq beg (point-at-bol 2))
1592 (goto-char tbeg)
1593 (setq beg (point-at-bol 1)))
1594 (goto-char pos)
1595 (if (re-search-forward org-table-hline-regexp tend t)
1596 (setq end (point-at-bol 1))
1597 (goto-char tend)
1598 (setq end (point-at-bol))))
1599 (setq beg (move-marker (make-marker) beg)
1600 end (move-marker (make-marker) end))
1601 (untabify beg end)
1602 (goto-char beg)
1603 (org-table-goto-column column)
1604 (skip-chars-backward "^|")
1605 (setq bcol (current-column))
1606 (org-table-goto-column (1+ column))
1607 (skip-chars-backward "^|")
1608 (setq ecol (1- (current-column)))
1609 (org-table-goto-column column)
1610 (setq lns (mapcar (lambda(x) (cons
1611 (org-sort-remove-invisible
1612 (nth (1- column)
1613 (org-split-string x "[ \t]*|[ \t]*")))
1615 (org-split-string (buffer-substring beg end) "\n")))
1616 (setq lns (org-do-sort lns "Table" with-case sorting-type))
1617 (delete-region beg end)
1618 (move-marker beg nil)
1619 (move-marker end nil)
1620 (insert (mapconcat 'cdr lns "\n") "\n")
1621 (org-goto-line thisline)
1622 (org-table-goto-column thiscol)
1623 (message "%d lines sorted, based on column %d" (length lns) column)))
1626 (defun org-table-cut-region (beg end)
1627 "Copy region in table to the clipboard and blank all relevant fields.
1628 If there is no active region, use just the field at point."
1629 (interactive (list
1630 (if (org-region-active-p) (region-beginning) (point))
1631 (if (org-region-active-p) (region-end) (point))))
1632 (org-table-copy-region beg end 'cut))
1634 (defun org-table-copy-region (beg end &optional cut)
1635 "Copy rectangular region in table to clipboard.
1636 A special clipboard is used which can only be accessed
1637 with `org-table-paste-rectangle'."
1638 (interactive (list
1639 (if (org-region-active-p) (region-beginning) (point))
1640 (if (org-region-active-p) (region-end) (point))
1641 current-prefix-arg))
1642 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1643 region cols
1644 (rpl (if cut " " nil)))
1645 (goto-char beg)
1646 (org-table-check-inside-data-field)
1647 (setq l01 (org-current-line)
1648 c01 (org-table-current-column))
1649 (goto-char end)
1650 (org-table-check-inside-data-field)
1651 (setq l02 (org-current-line)
1652 c02 (org-table-current-column))
1653 (setq l1 (min l01 l02) l2 (max l01 l02)
1654 c1 (min c01 c02) c2 (max c01 c02))
1655 (catch 'exit
1656 (while t
1657 (catch 'nextline
1658 (if (> l1 l2) (throw 'exit t))
1659 (org-goto-line l1)
1660 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1661 (setq cols nil ic1 c1 ic2 c2)
1662 (while (< ic1 (1+ ic2))
1663 (push (org-table-get-field ic1 rpl) cols)
1664 (setq ic1 (1+ ic1)))
1665 (push (nreverse cols) region)
1666 (setq l1 (1+ l1)))))
1667 (setq org-table-clip (nreverse region))
1668 (if cut (org-table-align))
1669 org-table-clip))
1671 (defun org-table-paste-rectangle ()
1672 "Paste a rectangular region into a table.
1673 The upper right corner ends up in the current field. All involved fields
1674 will be overwritten. If the rectangle does not fit into the present table,
1675 the table is enlarged as needed. The process ignores horizontal separator
1676 lines."
1677 (interactive)
1678 (unless (and org-table-clip (listp org-table-clip))
1679 (error "First cut/copy a region to paste!"))
1680 (org-table-check-inside-data-field)
1681 (let* ((clip org-table-clip)
1682 (line (org-current-line))
1683 (col (org-table-current-column))
1684 (org-enable-table-editor t)
1685 (org-table-automatic-realign nil)
1686 c cols field)
1687 (while (setq cols (pop clip))
1688 (while (org-at-table-hline-p) (beginning-of-line 2))
1689 (if (not (org-at-table-p))
1690 (progn (end-of-line 0) (org-table-next-field)))
1691 (setq c col)
1692 (while (setq field (pop cols))
1693 (org-table-goto-column c nil 'force)
1694 (org-table-get-field nil field)
1695 (setq c (1+ c)))
1696 (beginning-of-line 2))
1697 (org-goto-line line)
1698 (org-table-goto-column col)
1699 (org-table-align)))
1701 (defun org-table-convert ()
1702 "Convert from `org-mode' table to table.el and back.
1703 Obviously, this only works within limits. When an Org-mode table is
1704 converted to table.el, all horizontal separator lines get lost, because
1705 table.el uses these as cell boundaries and has no notion of horizontal lines.
1706 A table.el table can be converted to an Org-mode table only if it does not
1707 do row or column spanning. Multiline cells will become multiple cells.
1708 Beware, Org-mode does not test if the table can be successfully converted - it
1709 blindly applies a recipe that works for simple tables."
1710 (interactive)
1711 (require 'table)
1712 (if (org-at-table.el-p)
1713 ;; convert to Org-mode table
1714 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1715 (end (move-marker (make-marker) (org-table-end t))))
1716 (table-unrecognize-region beg end)
1717 (goto-char beg)
1718 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1719 (replace-match ""))
1720 (goto-char beg))
1721 (if (org-at-table-p)
1722 ;; convert to table.el table
1723 (let ((beg (move-marker (make-marker) (org-table-begin)))
1724 (end (move-marker (make-marker) (org-table-end))))
1725 ;; first, get rid of all horizontal lines
1726 (goto-char beg)
1727 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1728 (replace-match ""))
1729 ;; insert a hline before first
1730 (goto-char beg)
1731 (org-table-insert-hline 'above)
1732 (beginning-of-line -1)
1733 ;; insert a hline after each line
1734 (while (progn (beginning-of-line 3) (< (point) end))
1735 (org-table-insert-hline))
1736 (goto-char beg)
1737 (setq end (move-marker end (org-table-end)))
1738 ;; replace "+" at beginning and ending of hlines
1739 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1740 (replace-match "\\1+-"))
1741 (goto-char beg)
1742 (while (re-search-forward "-|[ \t]*$" end t)
1743 (replace-match "-+"))
1744 (goto-char beg)))))
1746 (defun org-table-transpose-table-at-point ()
1747 "Transpose orgmode table at point and eliminate hlines.
1748 So a table like
1750 | 1 | 2 | 4 | 5 |
1751 |---+---+---+---|
1752 | a | b | c | d |
1753 | e | f | g | h |
1755 will be transposed as
1757 | 1 | a | e |
1758 | 2 | b | f |
1759 | 4 | c | g |
1760 | 5 | d | h |
1762 Note that horizontal lines disappeared."
1763 (interactive)
1764 (let ((contents
1765 (apply #'mapcar* #'list
1766 ;; remove 'hline from list
1767 (delq nil (mapcar (lambda (x) (when (listp x) x))
1768 (org-table-to-lisp))))))
1769 (delete-region (org-table-begin) (org-table-end))
1770 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1771 contents ""))
1772 (org-table-align)))
1774 (defun org-table-wrap-region (arg)
1775 "Wrap several fields in a column like a paragraph.
1776 This is useful if you'd like to spread the contents of a field over several
1777 lines, in order to keep the table compact.
1779 If there is an active region, and both point and mark are in the same column,
1780 the text in the column is wrapped to minimum width for the given number of
1781 lines. Generally, this makes the table more compact. A prefix ARG may be
1782 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1783 formats the selected text to two lines. If the region was longer than two
1784 lines, the remaining lines remain empty. A negative prefix argument reduces
1785 the current number of lines by that amount. The wrapped text is pasted back
1786 into the table. If you formatted it to more lines than it was before, fields
1787 further down in the table get overwritten - so you might need to make space in
1788 the table first.
1790 If there is no region, the current field is split at the cursor position and
1791 the text fragment to the right of the cursor is prepended to the field one
1792 line down.
1794 If there is no region, but you specify a prefix ARG, the current field gets
1795 blank, and the content is appended to the field above."
1796 (interactive "P")
1797 (org-table-check-inside-data-field)
1798 (if (org-region-active-p)
1799 ;; There is a region: fill as a paragraph
1800 (let* ((beg (region-beginning))
1801 (cline (save-excursion (goto-char beg) (org-current-line)))
1802 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1803 nlines)
1804 (org-table-cut-region (region-beginning) (region-end))
1805 (if (> (length (car org-table-clip)) 1)
1806 (error "Region must be limited to single column"))
1807 (setq nlines (if arg
1808 (if (< arg 1)
1809 (+ (length org-table-clip) arg)
1810 arg)
1811 (length org-table-clip)))
1812 (setq org-table-clip
1813 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1814 nil nlines)))
1815 (org-goto-line cline)
1816 (org-table-goto-column ccol)
1817 (org-table-paste-rectangle))
1818 ;; No region, split the current field at point
1819 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1820 (skip-chars-forward "^\r\n|"))
1821 (if arg
1822 ;; combine with field above
1823 (let ((s (org-table-blank-field))
1824 (col (org-table-current-column)))
1825 (beginning-of-line 0)
1826 (while (org-at-table-hline-p) (beginning-of-line 0))
1827 (org-table-goto-column col)
1828 (skip-chars-forward "^|")
1829 (skip-chars-backward " ")
1830 (insert " " (org-trim s))
1831 (org-table-align))
1832 ;; split field
1833 (if (looking-at "\\([^|]+\\)+|")
1834 (let ((s (match-string 1)))
1835 (replace-match " |")
1836 (goto-char (match-beginning 0))
1837 (org-table-next-row)
1838 (insert (org-trim s) " ")
1839 (org-table-align))
1840 (org-table-next-row)))))
1842 (defvar org-field-marker nil)
1844 (defun org-table-edit-field (arg)
1845 "Edit table field in a different window.
1846 This is mainly useful for fields that contain hidden parts.
1847 When called with a \\[universal-argument] prefix, just make the full field visible so that
1848 it can be edited in place."
1849 (interactive "P")
1850 (cond
1851 ((equal arg '(16))
1852 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1853 (arg
1854 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1855 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1856 (remove-text-properties b e '(org-cwidth t invisible t
1857 display t intangible t))
1858 (if (and (boundp 'font-lock-mode) font-lock-mode)
1859 (font-lock-fontify-block))))
1861 (let ((pos (move-marker (make-marker) (point)))
1862 (coord
1863 (if (eq org-table-use-standard-references t)
1864 (concat (org-number-to-letters (org-table-current-column))
1865 (int-to-string (org-table-current-dline)))
1866 (concat "@" (int-to-string (org-table-current-dline))
1867 "$" (int-to-string (org-table-current-column)))))
1868 (field (org-table-get-field))
1869 (cw (current-window-configuration))
1871 (goto-char pos)
1872 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1873 (when (and (local-variable-p 'org-field-marker)
1874 (markerp org-field-marker))
1875 (move-marker org-field-marker nil))
1876 (erase-buffer)
1877 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
1878 (let ((org-inhibit-startup t)) (org-mode))
1879 (auto-fill-mode -1)
1880 (setq truncate-lines nil)
1881 (setq word-wrap t)
1882 (goto-char (setq p (point-max)))
1883 (insert (org-trim field))
1884 (remove-text-properties p (point-max)
1885 '(invisible t org-cwidth t display t
1886 intangible t))
1887 (goto-char p)
1888 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
1889 (org-set-local 'org-window-configuration cw)
1890 (org-set-local 'org-field-marker pos)
1891 (message "Edit and finish with C-c C-c")))))
1893 (defun org-table-finish-edit-field ()
1894 "Finish editing a table data field.
1895 Remove all newline characters, insert the result into the table, realign
1896 the table and kill the editing buffer."
1897 (let ((pos org-field-marker)
1898 (cw org-window-configuration)
1899 (cb (current-buffer))
1900 text)
1901 (goto-char (point-min))
1902 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
1903 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
1904 (replace-match " "))
1905 (setq text (org-trim (buffer-string)))
1906 (set-window-configuration cw)
1907 (kill-buffer cb)
1908 (select-window (get-buffer-window (marker-buffer pos)))
1909 (goto-char pos)
1910 (move-marker pos nil)
1911 (org-table-check-inside-data-field)
1912 (org-table-get-field nil text)
1913 (org-table-align)
1914 (message "New field value inserted")))
1916 (define-minor-mode org-table-follow-field-mode
1917 "Minor mode to make the table field editor window follow the cursor.
1918 When this mode is active, the field editor window will always show the
1919 current field. The mode exits automatically when the cursor leaves the
1920 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1921 nil " TblFollow" nil
1922 (if org-table-follow-field-mode
1923 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
1924 'append 'local)
1925 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
1926 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1927 (win (and buf (get-buffer-window buf))))
1928 (when win (delete-window win))
1929 (when buf
1930 (with-current-buffer buf
1931 (move-marker org-field-marker nil))
1932 (kill-buffer buf)))))
1934 (defun org-table-follow-fields-with-editor ()
1935 (if (and org-table-exit-follow-field-mode-when-leaving-table
1936 (not (org-at-table-p)))
1937 ;; We have left the table, exit the follow mode
1938 (org-table-follow-field-mode -1)
1939 (when (org-table-check-inside-data-field 'noerror)
1940 (let ((win (selected-window)))
1941 (org-table-edit-field nil)
1942 (org-fit-window-to-buffer)
1943 (select-window win)))))
1945 (defvar org-timecnt) ; dynamically scoped parameter
1947 (defun org-table-sum (&optional beg end nlast)
1948 "Sum numbers in region of current table column.
1949 The result will be displayed in the echo area, and will be available
1950 as kill to be inserted with \\[yank].
1952 If there is an active region, it is interpreted as a rectangle and all
1953 numbers in that rectangle will be summed. If there is no active
1954 region and point is located in a table column, sum all numbers in that
1955 column.
1957 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1958 numbers are assumed to be times as well (in decimal hours) and the
1959 numbers are added as such.
1961 If NLAST is a number, only the NLAST fields will actually be summed."
1962 (interactive)
1963 (save-excursion
1964 (let (col (org-timecnt 0) diff h m s org-table-clip)
1965 (cond
1966 ((and beg end)) ; beg and end given explicitly
1967 ((org-region-active-p)
1968 (setq beg (region-beginning) end (region-end)))
1970 (setq col (org-table-current-column))
1971 (goto-char (org-table-begin))
1972 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
1973 (error "No table data"))
1974 (org-table-goto-column col)
1975 (setq beg (point))
1976 (goto-char (org-table-end))
1977 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
1978 (error "No table data"))
1979 (org-table-goto-column col)
1980 (setq end (point))))
1981 (let* ((items (apply 'append (org-table-copy-region beg end)))
1982 (items1 (cond ((not nlast) items)
1983 ((>= nlast (length items)) items)
1984 (t (setq items (reverse items))
1985 (setcdr (nthcdr (1- nlast) items) nil)
1986 (nreverse items))))
1987 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
1988 items1)))
1989 (res (apply '+ numbers))
1990 (sres (if (= org-timecnt 0)
1991 (number-to-string res)
1992 (setq diff (* 3600 res)
1993 h (floor (/ diff 3600)) diff (mod diff 3600)
1994 m (floor (/ diff 60)) diff (mod diff 60)
1995 s diff)
1996 (format "%d:%02d:%02d" h m s))))
1997 (kill-new sres)
1998 (if (org-called-interactively-p 'interactive)
1999 (message "%s"
2000 (substitute-command-keys
2001 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2002 (length numbers) sres))))
2003 sres))))
2005 (defun org-table-get-number-for-summing (s)
2006 (let (n)
2007 (if (string-match "^ *|? *" s)
2008 (setq s (replace-match "" nil nil s)))
2009 (if (string-match " *|? *$" s)
2010 (setq s (replace-match "" nil nil s)))
2011 (setq n (string-to-number s))
2012 (cond
2013 ((and (string-match "0" s)
2014 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2015 ((string-match "\\`[ \t]+\\'" s) nil)
2016 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2017 (let ((h (string-to-number (or (match-string 1 s) "0")))
2018 (m (string-to-number (or (match-string 2 s) "0")))
2019 (s (string-to-number (or (match-string 4 s) "0"))))
2020 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2021 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2022 ((equal n 0) nil)
2023 (t n))))
2025 (defun org-table-current-field-formula (&optional key noerror)
2026 "Return the formula active for the current field.
2027 Assumes that specials are in place.
2028 If KEY is given, return the key to this formula.
2029 Otherwise return the formula preceded with \"=\" or \":=\"."
2030 (let* ((name (car (rassoc (list (org-current-line)
2031 (org-table-current-column))
2032 org-table-named-field-locations)))
2033 (col (org-table-current-column))
2034 (scol (int-to-string col))
2035 (ref (format "@%d$%d" (org-table-current-dline) col))
2036 (stored-list (org-table-get-stored-formulas noerror))
2037 (ass (or (assoc name stored-list)
2038 (assoc ref stored-list)
2039 (assoc scol stored-list))))
2040 (if key
2041 (car ass)
2042 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2043 (cdr ass))))))
2045 (defun org-table-get-formula (&optional equation named)
2046 "Read a formula from the minibuffer, offer stored formula as default.
2047 When NAMED is non-nil, look for a named equation."
2048 (let* ((stored-list (org-table-get-stored-formulas))
2049 (name (car (rassoc (list (org-current-line)
2050 (org-table-current-column))
2051 org-table-named-field-locations)))
2052 (ref (format "@%d$%d" (org-table-current-dline)
2053 (org-table-current-column)))
2054 (refass (assoc ref stored-list))
2055 (nameass (assoc name stored-list))
2056 (scol (if named
2057 (if (and name (not (string-match "^LR[0-9]+$" name)))
2058 name
2059 ref)
2060 (int-to-string (org-table-current-column))))
2061 (dummy (and (or nameass refass) (not named)
2062 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2063 (error "Abort")))
2064 (name (or name ref))
2065 (org-table-may-need-update nil)
2066 (stored (cdr (assoc scol stored-list)))
2067 (eq (cond
2068 ((and stored equation (string-match "^ *=? *$" equation))
2069 stored)
2070 ((stringp equation)
2071 equation)
2072 (t (org-table-formula-from-user
2073 (read-string
2074 (org-table-formula-to-user
2075 (format "%s formula %s%s="
2076 (if named "Field" "Column")
2077 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2078 scol))
2079 (if stored (org-table-formula-to-user stored) "")
2080 'org-table-formula-history
2081 )))))
2082 mustsave)
2083 (when (not (string-match "\\S-" eq))
2084 ;; remove formula
2085 (setq stored-list (delq (assoc scol stored-list) stored-list))
2086 (org-table-store-formulas stored-list)
2087 (error "Formula removed"))
2088 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2089 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2090 (if (and name (not named))
2091 ;; We set the column equation, delete the named one.
2092 (setq stored-list (delq (assoc name stored-list) stored-list)
2093 mustsave t))
2094 (if stored
2095 (setcdr (assoc scol stored-list) eq)
2096 (setq stored-list (cons (cons scol eq) stored-list)))
2097 (if (or mustsave (not (equal stored eq)))
2098 (org-table-store-formulas stored-list))
2099 eq))
2101 (defun org-table-store-formulas (alist)
2102 "Store the list of formulas below the current table."
2103 (setq alist (sort alist 'org-table-formula-less-p))
2104 (let ((case-fold-search t))
2105 (save-excursion
2106 (goto-char (org-table-end))
2107 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2108 (progn
2109 ;; don't overwrite TBLFM, we might use text properties to store stuff
2110 (goto-char (match-beginning 3))
2111 (delete-region (match-beginning 3) (match-end 0)))
2112 (org-indent-line)
2113 (insert (or (match-string 2) "#+TBLFM:")))
2114 (insert " "
2115 (mapconcat (lambda (x)
2116 (concat
2117 (if (equal (string-to-char (car x)) ?@) "" "$")
2118 (car x) "=" (cdr x)))
2119 alist "::")
2120 "\n"))))
2122 (defsubst org-table-formula-make-cmp-string (a)
2123 (when (string-match "\\`$[<>]" a)
2124 (let ((arrow (string-to-char (substring a 1))))
2125 ;; Fake a high number to make sure this is sorted at the end.
2126 (setq a (org-table-formula-handle-first/last-rc a))
2127 (setq a (format "$%d" (+ 10000
2128 (if (= arrow ?<) -1000 0)
2129 (string-to-number (substring a 1)))))))
2130 (when (string-match
2131 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2133 (concat
2134 (if (match-end 2)
2135 (format "@%05d" (string-to-number (match-string 2 a))) "")
2136 (if (match-end 4)
2137 (format "$%05d" (string-to-number (match-string 4 a))) "")
2138 (if (match-end 5)
2139 (concat "@@" (match-string 5 a))))))
2141 (defun org-table-formula-less-p (a b)
2142 "Compare two formulas for sorting."
2143 (let ((as (org-table-formula-make-cmp-string (car a)))
2144 (bs (org-table-formula-make-cmp-string (car b))))
2145 (and as bs (string< as bs))))
2147 (defun org-table-get-stored-formulas (&optional noerror)
2148 "Return an alist with the stored formulas directly after current table."
2149 (interactive)
2150 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2151 (save-excursion
2152 (goto-char (org-table-end))
2153 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2154 (setq strings (org-split-string (org-match-string-no-properties 2)
2155 " *:: *"))
2156 (while (setq string (pop strings))
2157 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2158 (setq scol (if (match-end 2)
2159 (match-string 2 string)
2160 (match-string 1 string))
2161 scol (if (member (string-to-char scol) '(?< ?>))
2162 (concat "$" scol) scol)
2163 eq (match-string 3 string)
2164 eq-alist (cons (cons scol eq) eq-alist))
2165 (if (member scol seen)
2166 (if noerror
2167 (progn
2168 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2169 (ding)
2170 (sit-for 2))
2171 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2172 (push scol seen))))))
2173 (nreverse eq-alist)))
2175 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2176 "Modify the equations after the table structure has been edited.
2177 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2178 For all numbers larger than LIMIT, shift them by DELTA."
2179 (save-excursion
2180 (goto-char (org-table-end))
2181 (when (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2182 (let ((msg "The formulas in #+TBLFM have been updated")
2183 (re (concat key "\\([0-9]+\\)"))
2184 (re2
2185 (when remove
2186 (if (or (equal key "$") (equal key "$LR"))
2187 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2188 (regexp-quote key) remove)
2189 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2190 s n a)
2191 (when remove
2192 (while (re-search-forward re2 (point-at-eol) t)
2193 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2194 (if (equal (char-before (match-beginning 0)) ?.)
2195 (error "Change makes TBLFM term %s invalid, use undo to recover"
2196 (match-string 0))
2197 (replace-match "")))))
2198 (while (re-search-forward re (point-at-eol) t)
2199 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2200 (setq s (match-string 1) n (string-to-number s))
2201 (cond
2202 ((setq a (assoc s replace))
2203 (replace-match (concat key (cdr a)) t t)
2204 (message msg))
2205 ((and limit (> n limit))
2206 (replace-match (concat key (int-to-string (+ n delta))) t t)
2207 (message msg)))))))))
2209 (defun org-table-get-specials ()
2210 "Get the column names and local parameters for this table."
2211 (save-excursion
2212 (let ((beg (org-table-begin)) (end (org-table-end))
2213 names name fields fields1 field cnt
2214 c v l line col types dlines hlines last-dline)
2215 (setq org-table-column-names nil
2216 org-table-local-parameters nil
2217 org-table-named-field-locations nil
2218 org-table-current-begin-line nil
2219 org-table-current-begin-pos nil
2220 org-table-current-line-types nil
2221 org-table-current-ncol 0)
2222 (goto-char beg)
2223 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2224 (setq names (org-split-string (match-string 1) " *| *")
2225 cnt 1)
2226 (while (setq name (pop names))
2227 (setq cnt (1+ cnt))
2228 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
2229 (push (cons name (int-to-string cnt)) org-table-column-names))))
2230 (setq org-table-column-names (nreverse org-table-column-names))
2231 (setq org-table-column-name-regexp
2232 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2233 (goto-char beg)
2234 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2235 (setq fields (org-split-string (match-string 1) " *| *"))
2236 (while (setq field (pop fields))
2237 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2238 (push (cons (match-string 1 field) (match-string 2 field))
2239 org-table-local-parameters))))
2240 (goto-char beg)
2241 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2242 (setq c (match-string 1)
2243 fields (org-split-string (match-string 2) " *| *"))
2244 (save-excursion
2245 (beginning-of-line (if (equal c "_") 2 0))
2246 (setq line (org-current-line) col 1)
2247 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2248 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2249 (while (and fields1 (setq field (pop fields)))
2250 (setq v (pop fields1) col (1+ col))
2251 (when (and (stringp field) (stringp v)
2252 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
2253 (push (cons field v) org-table-local-parameters)
2254 (push (list field line col) org-table-named-field-locations))))
2255 ;; Analyse the line types
2256 (goto-char beg)
2257 (setq org-table-current-begin-line (org-current-line)
2258 org-table-current-begin-pos (point)
2259 l org-table-current-begin-line)
2260 (while (looking-at "[ \t]*|\\(-\\)?")
2261 (push (if (match-end 1) 'hline 'dline) types)
2262 (if (match-end 1) (push l hlines) (push l dlines))
2263 (beginning-of-line 2)
2264 (setq l (1+ l)))
2265 (push 'hline types) ;; add an imaginary extra hline to the end
2266 (setq org-table-current-line-types (apply 'vector (nreverse types))
2267 last-dline (car dlines)
2268 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2269 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2270 (org-goto-line last-dline)
2271 (let* ((l last-dline)
2272 (fields (org-split-string
2273 (buffer-substring (point-at-bol) (point-at-eol))
2274 "[ \t]*|[ \t]*"))
2275 (nfields (length fields))
2276 al al2)
2277 (setq org-table-current-ncol nfields)
2278 (loop for i from 1 to nfields do
2279 (push (list (format "LR%d" i) l i) al)
2280 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2281 (setq org-table-named-field-locations
2282 (append org-table-named-field-locations al))
2283 (setq org-table-local-parameters
2284 (append org-table-local-parameters al2))))))
2286 (defun org-table-maybe-eval-formula ()
2287 "Check if the current field starts with \"=\" or \":=\".
2288 If yes, store the formula and apply it."
2289 ;; We already know we are in a table. Get field will only return a formula
2290 ;; when appropriate. It might return a separator line, but no problem.
2291 (when org-table-formula-evaluate-inline
2292 (let* ((field (org-trim (or (org-table-get-field) "")))
2293 named eq)
2294 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2295 (setq named (equal (string-to-char field) ?:)
2296 eq (match-string 1 field))
2297 (if (or (fboundp 'calc-eval)
2298 (equal (substring eq 0 (min 2 (length eq))) "'("))
2299 (org-table-eval-formula (if named '(4) nil)
2300 (org-table-formula-from-user eq))
2301 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2303 (defvar org-recalc-commands nil
2304 "List of commands triggering the recalculation of a line.
2305 Will be filled automatically during use.")
2307 (defvar org-recalc-marks
2308 '((" " . "Unmarked: no special line, no automatic recalculation")
2309 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2310 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2311 ("!" . "Column name definition line. Reference in formula as $name.")
2312 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2313 ("_" . "Names for values in row below this one.")
2314 ("^" . "Names for values in row above this one.")))
2316 (defun org-table-rotate-recalc-marks (&optional newchar)
2317 "Rotate the recalculation mark in the first column.
2318 If in any row, the first field is not consistent with a mark,
2319 insert a new column for the markers.
2320 When there is an active region, change all the lines in the region,
2321 after prompting for the marking character.
2322 After each change, a message will be displayed indicating the meaning
2323 of the new mark."
2324 (interactive)
2325 (unless (org-at-table-p) (error "Not at a table"))
2326 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2327 (beg (org-table-begin))
2328 (end (org-table-end))
2329 (l (org-current-line))
2330 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2331 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2332 (have-col
2333 (save-excursion
2334 (goto-char beg)
2335 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2336 (col (org-table-current-column))
2337 (forcenew (car (assoc newchar org-recalc-marks)))
2338 epos new)
2339 (when l1
2340 (message "Change region to what mark? Type # * ! $ or SPC: ")
2341 (setq newchar (char-to-string (read-char-exclusive))
2342 forcenew (car (assoc newchar org-recalc-marks))))
2343 (if (and newchar (not forcenew))
2344 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2345 newchar))
2346 (if l1 (org-goto-line l1))
2347 (save-excursion
2348 (beginning-of-line 1)
2349 (unless (looking-at org-table-dataline-regexp)
2350 (error "Not at a table data line")))
2351 (unless have-col
2352 (org-table-goto-column 1)
2353 (org-table-insert-column)
2354 (org-table-goto-column (1+ col)))
2355 (setq epos (point-at-eol))
2356 (save-excursion
2357 (beginning-of-line 1)
2358 (org-table-get-field
2359 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2360 (concat " "
2361 (setq new (or forcenew
2362 (cadr (member (match-string 1) marks))))
2363 " ")
2364 " # ")))
2365 (if (and l1 l2)
2366 (progn
2367 (org-goto-line l1)
2368 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2369 (and (looking-at org-table-dataline-regexp)
2370 (org-table-get-field 1 (concat " " new " "))))
2371 (org-goto-line l1)))
2372 (if (not (= epos (point-at-eol))) (org-table-align))
2373 (org-goto-line l)
2374 (and (org-called-interactively-p 'interactive)
2375 (message "%s" (cdr (assoc new org-recalc-marks))))))
2377 (defun org-table-maybe-recalculate-line ()
2378 "Recompute the current line if marked for it, and if we haven't just done it."
2379 (interactive)
2380 (and org-table-allow-automatic-line-recalculation
2381 (not (and (memq last-command org-recalc-commands)
2382 (equal org-last-recalc-line (org-current-line))))
2383 (save-excursion (beginning-of-line 1)
2384 (looking-at org-table-auto-recalculate-regexp))
2385 (org-table-recalculate) t))
2387 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2388 (defsubst org-set-calc-mode (var &optional value)
2389 (if (stringp var)
2390 (setq var (assoc var '(("D" calc-angle-mode deg)
2391 ("R" calc-angle-mode rad)
2392 ("F" calc-prefer-frac t)
2393 ("S" calc-symbolic-mode t)))
2394 value (nth 2 var) var (nth 1 var)))
2395 (if (memq var org-tbl-calc-modes)
2396 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2397 (cons var (cons value org-tbl-calc-modes)))
2398 org-tbl-calc-modes)
2400 (defun org-table-eval-formula (&optional arg equation
2401 suppress-align suppress-const
2402 suppress-store suppress-analysis)
2403 "Replace the table field value at the cursor by the result of a calculation.
2405 This function makes use of Dave Gillespie's Calc package, in my view the
2406 most exciting program ever written for GNU Emacs. So you need to have Calc
2407 installed in order to use this function.
2409 In a table, this command replaces the value in the current field with the
2410 result of a formula. It also installs the formula as the \"current\" column
2411 formula, by storing it in a special line below the table. When called
2412 with a `C-u' prefix, the current field must be a named field, and the
2413 formula is installed as valid in only this specific field.
2415 When called with two `C-u' prefixes, insert the active equation
2416 for the field back into the current field, so that it can be
2417 edited there. This is useful in order to use \\[org-table-show-reference]
2418 to check the referenced fields.
2420 When called, the command first prompts for a formula, which is read in
2421 the minibuffer. Previously entered formulas are available through the
2422 history list, and the last used formula is offered as a default.
2423 These stored formulas are adapted correctly when moving, inserting, or
2424 deleting columns with the corresponding commands.
2426 The formula can be any algebraic expression understood by the Calc package.
2427 For details, see the Org-mode manual.
2429 This function can also be called from Lisp programs and offers
2430 additional arguments: EQUATION can be the formula to apply. If this
2431 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2432 used to speed-up recursive calls by by-passing unnecessary aligns.
2433 SUPPRESS-CONST suppresses the interpretation of constants in the
2434 formula, assuming that this has been done already outside the function.
2435 SUPPRESS-STORE means the formula should not be stored, either because
2436 it is already stored, or because it is a modified equation that should
2437 not overwrite the stored one."
2438 (interactive "P")
2439 (org-table-check-inside-data-field)
2440 (or suppress-analysis (org-table-get-specials))
2441 (if (equal arg '(16))
2442 (let ((eq (org-table-current-field-formula)))
2443 (or eq (error "No equation active for current field"))
2444 (org-table-get-field nil eq)
2445 (org-table-align)
2446 (setq org-table-may-need-update t))
2447 (let* (fields
2448 (ndown (if (integerp arg) arg 1))
2449 (org-table-automatic-realign nil)
2450 (case-fold-search nil)
2451 (down (> ndown 1))
2452 (formula (if (and equation suppress-store)
2453 equation
2454 (org-table-get-formula equation (equal arg '(4)))))
2455 (n0 (org-table-current-column))
2456 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2457 (numbers nil) ; was a variable, now fixed default
2458 (keep-empty nil)
2459 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2460 duration duration-output-format)
2461 ;; Parse the format string. Since we have a lot of modes, this is
2462 ;; a lot of work. However, I think calc still uses most of the time.
2463 (if (string-match ";" formula)
2464 (let ((tmp (org-split-string formula ";")))
2465 (setq formula (car tmp)
2466 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2467 (nth 1 tmp)))
2468 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2469 (setq c (string-to-char (match-string 1 fmt))
2470 n (string-to-number (match-string 2 fmt)))
2471 (if (= c ?p)
2472 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2473 (setq org-tbl-calc-modes
2474 (org-set-calc-mode
2475 'calc-float-format
2476 (list (cdr (assoc c '((?n . float) (?f . fix)
2477 (?s . sci) (?e . eng))))
2478 n))))
2479 (setq fmt (replace-match "" t t fmt)))
2480 (if (string-match "T" fmt)
2481 (setq duration t numbers t
2482 duration-output-format nil
2483 fmt (replace-match "" t t fmt)))
2484 (if (string-match "t" fmt)
2485 (setq duration t
2486 duration-output-format org-table-duration-custom-format
2487 numbers t
2488 fmt (replace-match "" t t fmt)))
2489 (if (string-match "N" fmt)
2490 (setq numbers t
2491 fmt (replace-match "" t t fmt)))
2492 (if (string-match "L" fmt)
2493 (setq literal t
2494 fmt (replace-match "" t t fmt)))
2495 (if (string-match "E" fmt)
2496 (setq keep-empty t
2497 fmt (replace-match "" t t fmt)))
2498 (while (string-match "[DRFS]" fmt)
2499 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2500 (setq fmt (replace-match "" t t fmt)))
2501 (unless (string-match "\\S-" fmt)
2502 (setq fmt nil))))
2503 (if (and (not suppress-const) org-table-formula-use-constants)
2504 (setq formula (org-table-formula-substitute-names formula)))
2505 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2506 (while (> ndown 0)
2507 (setq fields (org-split-string
2508 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2509 " *| *"))
2510 ;; replace fields with duration values if relevant
2511 (if duration
2512 (setq fields
2513 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2514 fields)))
2515 (if (eq numbers t)
2516 (setq fields (mapcar
2517 (lambda (x) (number-to-string (string-to-number x)))
2518 fields)))
2519 (setq ndown (1- ndown))
2520 (setq form (copy-sequence formula)
2521 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2522 (if (and lispp literal) (setq lispp 'literal))
2524 ;; Insert row and column number of formula result field
2525 (while (string-match "[@$]#" form)
2526 (setq form
2527 (replace-match
2528 (format "%d"
2529 (save-match-data
2530 (if (equal (substring form (match-beginning 0)
2531 (1+ (match-beginning 0)))
2532 "@")
2533 (org-table-current-dline)
2534 (org-table-current-column))))
2535 t t form)))
2537 ;; Check for old vertical references
2538 (setq form (org-table-rewrite-old-row-references form))
2539 ;; Insert remote references
2540 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2541 (setq form
2542 (replace-match
2543 (save-match-data
2544 (org-table-make-reference
2545 (let ((rmtrng (org-table-get-remote-range
2546 (match-string 1 form) (match-string 2 form))))
2547 (if duration
2548 (if (listp rmtrng)
2549 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2550 (org-table-time-string-to-seconds rmtrng))
2551 rmtrng))
2552 keep-empty numbers lispp))
2553 t t form)))
2554 ;; Insert complex ranges
2555 (while (and (string-match org-table-range-regexp form)
2556 (> (length (match-string 0 form)) 1))
2557 (setq formrg (save-match-data
2558 (org-table-get-range (match-string 0 form) nil n0)))
2559 (setq formrpl
2560 (save-match-data
2561 (org-table-make-reference
2562 ;; possibly handle durations
2563 (if duration
2564 (if (listp formrg)
2565 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2566 (org-table-time-string-to-seconds formrg))
2567 formrg)
2568 keep-empty numbers lispp)))
2569 (if (not (save-match-data
2570 (string-match (regexp-quote form) formrpl)))
2571 (setq form (replace-match formrpl t t form))
2572 (error "Spreadsheet error: invalid reference \"%s\"" form)))
2573 ;; Insert simple ranges
2574 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2575 (setq form
2576 (replace-match
2577 (save-match-data
2578 (org-table-make-reference
2579 (org-sublist
2580 fields (string-to-number (match-string 1 form))
2581 (string-to-number (match-string 2 form)))
2582 keep-empty numbers lispp))
2583 t t form)))
2584 (setq form0 form)
2585 ;; Insert the references to fields in same row
2586 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2587 (setq n (+ (string-to-number (match-string 1 form))
2588 (if (match-end 2) n0 0))
2589 x (nth (1- (if (= n 0) n0 (max n 1))) fields))
2590 (unless x (error "Invalid field specifier \"%s\""
2591 (match-string 0 form)))
2592 (setq form (replace-match
2593 (save-match-data
2594 (org-table-make-reference x nil numbers lispp))
2595 t t form)))
2597 (if lispp
2598 (setq ev (condition-case nil
2599 (eval (eval (read form)))
2600 (error "#ERROR"))
2601 ev (if (numberp ev) (number-to-string ev) ev)
2602 ev (if duration (org-table-time-seconds-to-string
2603 (string-to-number ev)
2604 duration-output-format) ev))
2605 (or (fboundp 'calc-eval)
2606 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2607 ;; "Inactivate" time-stamps so that Calc can handle them
2608 (setq form (replace-regexp-in-string org-ts-regexp3 "<\\1>" form))
2609 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2610 form
2611 (calc-eval (cons form org-tbl-calc-modes) (if numbers 'num)))
2612 ev (if duration (org-table-time-seconds-to-string
2613 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2614 (string-to-number (org-table-time-string-to-seconds ev))
2615 (string-to-number ev))
2616 duration-output-format)
2617 ev)))
2619 (when org-table-formula-debug
2620 (with-output-to-temp-buffer "*Substitution History*"
2621 (princ (format "Substitution history of formula
2622 Orig: %s
2623 $xyz-> %s
2624 @r$c-> %s
2625 $1-> %s\n" orig formula form0 form))
2626 (if (listp ev)
2627 (princ (format " %s^\nError: %s"
2628 (make-string (car ev) ?\-) (nth 1 ev)))
2629 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2630 ev (or fmt "NONE")
2631 (if fmt (format fmt (string-to-number ev)) ev)))))
2632 (setq bw (get-buffer-window "*Substitution History*"))
2633 (org-fit-window-to-buffer bw)
2634 (unless (and (org-called-interactively-p 'any) (not ndown))
2635 (unless (let (inhibit-redisplay)
2636 (y-or-n-p "Debugging Formula. Continue to next? "))
2637 (org-table-align)
2638 (error "Abort"))
2639 (delete-window bw)
2640 (message "")))
2641 (if (listp ev) (setq fmt nil ev "#ERROR"))
2642 (org-table-justify-field-maybe
2643 (format org-table-formula-field-format
2644 (if fmt (format fmt (string-to-number ev)) ev)))
2645 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2646 (call-interactively 'org-return)
2647 (setq ndown 0)))
2648 (and down (org-table-maybe-recalculate-line))
2649 (or suppress-align (and org-table-may-need-update
2650 (org-table-align))))))
2652 (defun org-table-put-field-property (prop value)
2653 (save-excursion
2654 (put-text-property (progn (skip-chars-backward "^|") (point))
2655 (progn (skip-chars-forward "^|") (point))
2656 prop value)))
2658 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2659 "Get a calc vector from a column, according to descriptor DESC.
2660 Optional arguments TBEG and COL can give the beginning of the table and
2661 the current column, to avoid unnecessary parsing.
2663 HIGHLIGHT means just highlight the range.
2665 When CORNERS-ONLY is set, only return the corners of the range as
2666 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2667 in the buffer and column1 and column2 are table column numbers."
2668 (if (not (equal (string-to-char desc) ?@))
2669 (setq desc (concat "@" desc)))
2670 (save-excursion
2671 (or tbeg (setq tbeg (org-table-begin)))
2672 (or col (setq col (org-table-current-column)))
2673 (let ((thisline (org-current-line))
2674 beg end c1 c2 r1 r2 rangep tmp)
2675 (unless (string-match org-table-range-regexp desc)
2676 (error "Invalid table range specifier `%s'" desc))
2677 (setq rangep (match-end 3)
2678 r1 (and (match-end 1) (match-string 1 desc))
2679 r2 (and (match-end 4) (match-string 4 desc))
2680 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2681 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2683 (and c1 (setq c1 (+ (string-to-number c1)
2684 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2685 (and c2 (setq c2 (+ (string-to-number c2)
2686 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2687 (if (equal r1 "") (setq r1 nil))
2688 (if (equal r2 "") (setq r2 nil))
2689 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2690 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2691 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2692 (if (not r1) (setq r1 thisline))
2693 (if (not r2) (setq r2 thisline))
2694 (if (or (not c1) (= 0 c1)) (setq c1 col))
2695 (if (or (not c2) (= 0 c2)) (setq c2 col))
2696 (if (and (not corners-only)
2697 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2698 ;; just one field
2699 (progn
2700 (org-goto-line r1)
2701 (while (not (looking-at org-table-dataline-regexp))
2702 (beginning-of-line 2))
2703 (prog1 (org-trim (org-table-get-field c1))
2704 (if highlight (org-table-highlight-rectangle (point) (point)))))
2705 ;; A range, return a vector
2706 ;; First sort the numbers to get a regular rectangle
2707 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2708 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2709 (if corners-only
2710 ;; Only return the corners of the range
2711 (list r1 c1 r2 c2)
2712 ;; Copy the range values into a list
2713 (org-goto-line r1)
2714 (while (not (looking-at org-table-dataline-regexp))
2715 (beginning-of-line 2))
2716 (org-table-goto-column c1)
2717 (setq beg (point))
2718 (org-goto-line r2)
2719 (while (not (looking-at org-table-dataline-regexp))
2720 (beginning-of-line 0))
2721 (org-table-goto-column c2)
2722 (setq end (point))
2723 (if highlight
2724 (org-table-highlight-rectangle
2725 beg (progn (skip-chars-forward "^|\n") (point))))
2726 ;; return string representation of calc vector
2727 (mapcar 'org-trim
2728 (apply 'append (org-table-copy-region beg end))))))))
2730 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2731 "Analyze descriptor DESC and retrieve the corresponding line number.
2732 The cursor is currently in line CLINE, the table begins in line BLINE,
2733 and TABLE is a vector with line types."
2734 (if (string-match "^[0-9]+$" desc)
2735 (aref org-table-dlines (string-to-number desc))
2736 (setq cline (or cline (org-current-line))
2737 bline (or bline org-table-current-begin-line)
2738 table (or table org-table-current-line-types))
2739 (if (or
2740 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2741 ;; 1 2 3 4 5 6
2742 (and (not (match-end 3)) (not (match-end 6)))
2743 (and (match-end 3) (match-end 6) (not (match-end 5))))
2744 (error "Invalid row descriptor `%s'" desc))
2745 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2746 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2747 (odir (and (match-end 5) (match-string 5 desc)))
2748 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2749 (i (- cline bline))
2750 (rel (and (match-end 6)
2751 (or (and (match-end 1) (not (match-end 3)))
2752 (match-end 5)))))
2753 (if (and hn (not hdir))
2754 (progn
2755 (setq i 0 hdir "+")
2756 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2757 (if (and (not hn) on (not odir))
2758 (error "Should never happen");;(aref org-table-dlines on)
2759 (if (and hn (> hn 0))
2760 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2761 nil hn cline desc)))
2762 (if on
2763 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2764 rel on cline desc)))
2765 (+ bline i)))))
2767 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2768 "FIXME: Needs more documentation."
2769 (let ((l (length table)))
2770 (while (> n 0)
2771 (while (and (setq i (+ i (if backwards -1 1)))
2772 (>= i 0) (< i l)
2773 (not (eq (aref table i) type))
2774 (if (and relative (eq (aref table i) 'hline))
2775 (cond
2776 ((eq org-table-relative-ref-may-cross-hline t) t)
2777 ((eq org-table-relative-ref-may-cross-hline 'error)
2778 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2779 (t (setq i (- i (if backwards -1 1))
2780 n 1)
2781 nil))
2782 t)))
2783 (setq n (1- n)))
2784 (if (or (< i 0) (>= i l))
2785 (error "Row descriptor %s used in line %d leads outside table"
2786 desc cline)
2787 i)))
2789 (defun org-table-rewrite-old-row-references (s)
2790 (if (string-match "&[-+0-9I]" s)
2791 (error "Formula contains old &row reference, please rewrite using @-syntax")
2794 (defun org-table-make-reference (elements keep-empty numbers lispp)
2795 "Convert list ELEMENTS to something appropriate to insert into formula.
2796 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2797 NUMBERS indicates that everything should be converted to numbers.
2798 LISPP means to return something appropriate for a Lisp list."
2799 (if (stringp elements) ; just a single val
2800 (if lispp
2801 (if (eq lispp 'literal)
2802 elements
2803 (prin1-to-string (if numbers (string-to-number elements) elements)))
2804 (if (equal elements "") (setq elements "0"))
2805 (if numbers (setq elements (number-to-string (string-to-number elements))))
2806 (concat "(" elements ")"))
2807 (unless keep-empty
2808 (setq elements
2809 (delq nil
2810 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2811 elements))))
2812 (setq elements (or elements '("0")))
2813 (if lispp
2814 (mapconcat
2815 (lambda (x)
2816 (if (eq lispp 'literal)
2818 (prin1-to-string (if numbers (string-to-number x) x))))
2819 elements " ")
2820 (concat "[" (mapconcat
2821 (lambda (x)
2822 (if numbers (number-to-string (string-to-number x)) x))
2823 elements
2824 ",") "]"))))
2826 (defun org-table-recalculate (&optional all noalign)
2827 "Recalculate the current table line by applying all stored formulas.
2828 With prefix arg ALL, do this for all lines in the table.
2829 With the prefix argument ALL is `(16)' \
2830 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2831 it is the symbol `iterate', recompute the table until it no longer changes.
2832 If NOALIGN is not nil, do not re-align the table after the computations
2833 are done. This is typically used internally to save time, if it is
2834 known that the table will be realigned a little later anyway."
2835 (interactive "P")
2836 (or (memq this-command org-recalc-commands)
2837 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2838 (unless (org-at-table-p) (error "Not at a table"))
2839 (if (or (eq all 'iterate) (equal all '(16)))
2840 (org-table-iterate)
2841 (org-table-get-specials)
2842 (let* ((eqlist (sort (org-table-get-stored-formulas)
2843 (lambda (a b) (string< (car a) (car b)))))
2844 (eqlist1 (copy-sequence eqlist))
2845 (inhibit-redisplay (not debug-on-error))
2846 (line-re org-table-dataline-regexp)
2847 (thisline (org-current-line))
2848 (thiscol (org-table-current-column))
2849 seen-fields lhs1
2850 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
2851 ;; Insert constants in all formulas
2852 (setq eqlist
2853 (mapcar (lambda (x)
2854 (when (string-match "\\`$[<>]" (car x))
2855 (setq lhs1 (car x))
2856 (setq x (cons (substring
2857 (org-table-formula-handle-first/last-rc
2858 (car x)) 1)
2859 (cdr x)))
2860 (if (assoc (car x) eqlist1)
2861 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2862 lhs1 (car x))))
2863 (cons
2864 (org-table-formula-handle-first/last-rc (car x))
2865 (org-table-formula-substitute-names
2866 (org-table-formula-handle-first/last-rc (cdr x)))))
2867 eqlist))
2868 ;; Split the equation list
2869 (while (setq eq (pop eqlist))
2870 (if (<= (string-to-char (car eq)) ?9)
2871 (push eq eqlnum)
2872 (push eq eqlname)))
2873 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2874 ;; Expand ranges in lhs of formulas
2875 (setq eqlname (org-table-expand-lhs-ranges eqlname))
2877 ;; Get the correct line range to process
2878 (if all
2879 (progn
2880 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2881 (goto-char (setq beg (org-table-begin)))
2882 (if (re-search-forward org-table-calculate-mark-regexp end t)
2883 ;; This is a table with marked lines, compute selected lines
2884 (setq line-re org-table-recalculate-regexp)
2885 ;; Move forward to the first non-header line
2886 (if (and (re-search-forward org-table-dataline-regexp end t)
2887 (re-search-forward org-table-hline-regexp end t)
2888 (re-search-forward org-table-dataline-regexp end t))
2889 (setq beg (match-beginning 0))
2890 nil))) ;; just leave beg where it is
2891 (setq beg (point-at-bol)
2892 end (move-marker (make-marker) (1+ (point-at-eol)))))
2893 (goto-char beg)
2894 (and all (message "Re-applying formulas to full table..."))
2896 ;; First find the named fields, and mark them untouchable.
2897 ;; Also check if several field/range formulas try to set the same field.
2898 (remove-text-properties beg end '(org-untouchable t))
2899 (while (setq eq (pop eqlname))
2900 (setq name (car eq)
2901 a (assoc name org-table-named-field-locations))
2902 (setq name1 name)
2903 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
2904 (nth 2 a))))
2905 (when (member name1 seen-fields)
2906 (error "Several field/range formulas try to set %s" name1))
2907 (push name1 seen-fields)
2909 (and (not a)
2910 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2911 (setq a (list name
2912 (condition-case nil
2913 (aref org-table-dlines
2914 (string-to-number (match-string 1 name)))
2915 (error (error "Invalid row number in %s"
2916 name)))
2917 (string-to-number (match-string 2 name)))))
2918 (when (and a (or all (equal (nth 1 a) thisline)))
2919 (message "Re-applying formula to field: %s" name)
2920 (org-goto-line (nth 1 a))
2921 (org-table-goto-column (nth 2 a))
2922 (push (append a (list (cdr eq))) eqlname1)
2923 (org-table-put-field-property :org-untouchable t)))
2924 (setq eqlname1 (nreverse eqlname1))
2926 ;; Now evaluate the column formulas, but skip fields covered by
2927 ;; field formulas
2928 (goto-char beg)
2929 (while (re-search-forward line-re end t)
2930 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2931 ;; Unprotected line, recalculate
2932 (and all (message "Re-applying formulas to full table...(line %d)"
2933 (setq cnt (1+ cnt))))
2934 (setq org-last-recalc-line (org-current-line))
2935 (setq eql eqlnum)
2936 (while (setq entry (pop eql))
2937 (org-goto-line org-last-recalc-line)
2938 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2939 (unless (get-text-property (point) :org-untouchable)
2940 (org-table-eval-formula nil (cdr entry)
2941 'noalign 'nocst 'nostore 'noanalysis)))))
2943 ;; Now evaluate the field formulas
2944 (while (setq eq (pop eqlname1))
2945 (message "Re-applying formula to field: %s" (car eq))
2946 (org-goto-line (nth 1 eq))
2947 (org-table-goto-column (nth 2 eq))
2948 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
2949 'nostore 'noanalysis))
2951 (org-goto-line thisline)
2952 (org-table-goto-column thiscol)
2953 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
2954 (or noalign (and org-table-may-need-update (org-table-align))
2955 (and all (message "Re-applying formulas to %d lines...done" cnt)))
2957 ;; back to initial position
2958 (message "Re-applying formulas...done")
2959 (org-goto-line thisline)
2960 (org-table-goto-column thiscol)
2961 (or noalign (and org-table-may-need-update (org-table-align))
2962 (and all (message "Re-applying formulas...done"))))))
2964 (defun org-table-iterate (&optional arg)
2965 "Recalculate the table until it does not change anymore.
2966 The maximum number of iterations is 10, but you can choose a different value
2967 with the prefix ARG."
2968 (interactive "P")
2969 (let ((imax (if arg (prefix-numeric-value arg) 10))
2970 (i 0)
2971 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2972 thistbl)
2973 (catch 'exit
2974 (while (< i imax)
2975 (setq i (1+ i))
2976 (org-table-recalculate 'all)
2977 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
2978 (if (not (string= lasttbl thistbl))
2979 (setq lasttbl thistbl)
2980 (if (> i 1)
2981 (message "Convergence after %d iterations" i)
2982 (message "Table was already stable"))
2983 (throw 'exit t)))
2984 (error "No convergence after %d iterations" i))))
2986 ;;;###autoload
2987 (defun org-table-recalculate-buffer-tables ()
2988 "Recalculate all tables in the current buffer."
2989 (interactive)
2990 (save-excursion
2991 (save-restriction
2992 (widen)
2993 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
2995 ;;;###autoload
2996 (defun org-table-iterate-buffer-tables ()
2997 "Iterate all tables in the buffer, to converge inter-table dependencies."
2998 (interactive)
2999 (let* ((imax 10)
3000 (checksum (md5 (buffer-string)))
3003 (i imax))
3004 (save-excursion
3005 (save-restriction
3006 (widen)
3007 (catch 'exit
3008 (while (> i 0)
3009 (setq i (1- i))
3010 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3011 (if (equal checksum (setq c1 (md5 (buffer-string))))
3012 (progn
3013 (message "Convergence after %d iterations" (- imax i))
3014 (throw 'exit t))
3015 (setq checksum c1)))
3016 (error "No convergence after %d iterations" imax))))))
3018 (defun org-table-expand-lhs-ranges (equations)
3019 "Expand list of formulas.
3020 If some of the RHS in the formulas are ranges or a row reference, expand
3021 them to individual field equations for each field."
3022 (let (e res lhs rhs range r1 r2 c1 c2)
3023 (while (setq e (pop equations))
3024 (setq lhs (car e) rhs (cdr e))
3025 (cond
3026 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3027 ;; This just refers to one fixed field
3028 (push e res))
3029 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3030 ;; This just refers to one fixed named field
3031 (push e res))
3032 ((string-match "^@[0-9]+$" lhs)
3033 (loop for ic from 1 to org-table-current-ncol do
3034 (push (cons (format "%s$%d" lhs ic) rhs) res)
3035 (put-text-property 0 (length (caar res))
3036 :orig-eqn e (caar res))))
3038 (setq range (org-table-get-range lhs org-table-current-begin-pos
3039 1 nil 'corners))
3040 (setq r1 (nth 0 range) c1 (nth 1 range)
3041 r2 (nth 2 range) c2 (nth 3 range))
3042 (setq r1 (org-table-line-to-dline r1))
3043 (setq r2 (org-table-line-to-dline r2 'above))
3044 (loop for ir from r1 to r2 do
3045 (loop for ic from c1 to c2 do
3046 (push (cons (format "@%d$%d" ir ic) rhs) res)
3047 (put-text-property 0 (length (caar res))
3048 :orig-eqn e (caar res)))))))
3049 (nreverse res)))
3051 (defun org-table-formula-handle-first/last-rc (s)
3052 "Replace @<, @>, $<, $> with first/last row/column of the table.
3053 So @< and $< will always be replaced with @1 and $1, respectively.
3054 The advantage of these special markers are that structure editing of
3055 the table will not change them, while @1 and $1 will be modified
3056 when a line/row is swapped out of that privileged position. So for
3057 formulas that use a range of rows or columns, it may often be better
3058 to anchor the formula with \"I\" row markers, or to offset from the
3059 borders of the table using the @< @> $< $> makers."
3060 (let (n nmax len char (start 0))
3061 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3062 s start)
3063 (if (match-end 3)
3064 (setq start (match-end 3))
3065 (setq nmax (if (equal (match-string 1 s) "@")
3066 (1- (length org-table-dlines))
3067 org-table-current-ncol)
3068 len (- (match-end 2) (match-beginning 2))
3069 char (string-to-char (match-string 2 s))
3070 n (if (= char ?<)
3072 (- nmax len -1)))
3073 (if (or (< n 1) (> n nmax))
3074 (error "Reference \"%s\" in expression \"%s\" points outside table"
3075 (match-string 0 s) s))
3076 (setq start (match-beginning 0))
3077 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3080 (defun org-table-formula-substitute-names (f)
3081 "Replace $const with values in string F."
3082 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3083 ;; First, check for column names
3084 (while (setq start (string-match org-table-column-name-regexp f start))
3085 (setq start (1+ start))
3086 (setq a (assoc (match-string 1 f) org-table-column-names))
3087 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3088 ;; Parameters and constants
3089 (setq start 0)
3090 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3091 (if (match-end 2)
3092 (setq start (match-end 2))
3093 (setq start (1+ start))
3094 (if (setq a (save-match-data
3095 (org-table-get-constant (match-string 1 f))))
3096 (setq f (replace-match
3097 (concat (if pp "(") a (if pp ")")) t t f)))))
3098 (if org-table-formula-debug
3099 (put-text-property 0 (length f) :orig-formula f1 f))
3102 (defun org-table-get-constant (const)
3103 "Find the value for a parameter or constant in a formula.
3104 Parameters get priority."
3105 (or (cdr (assoc const org-table-local-parameters))
3106 (cdr (assoc const org-table-formula-constants-local))
3107 (cdr (assoc const org-table-formula-constants))
3108 (and (fboundp 'constants-get) (constants-get const))
3109 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3110 (org-entry-get nil (substring const 5) 'inherit))
3111 "#UNDEFINED_NAME"))
3113 (defvar org-table-fedit-map
3114 (let ((map (make-sparse-keymap)))
3115 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3116 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3117 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3118 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3119 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3120 (org-defkey map "\C-c?" 'org-table-show-reference)
3121 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3122 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3123 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3124 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3125 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3126 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3127 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3128 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3129 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3130 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3131 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3132 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3133 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3134 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3135 map))
3137 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3138 '("Edit-Formulas"
3139 ["Finish and Install" org-table-fedit-finish t]
3140 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3141 ["Abort" org-table-fedit-abort t]
3142 "--"
3143 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3144 ["Complete Lisp Symbol" lisp-complete-symbol t]
3145 "--"
3146 "Shift Reference at Point"
3147 ["Up" org-table-fedit-ref-up t]
3148 ["Down" org-table-fedit-ref-down t]
3149 ["Left" org-table-fedit-ref-left t]
3150 ["Right" org-table-fedit-ref-right t]
3152 "Change Test Row for Column Formulas"
3153 ["Up" org-table-fedit-line-up t]
3154 ["Down" org-table-fedit-line-down t]
3155 "--"
3156 ["Scroll Table Window" org-table-fedit-scroll t]
3157 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3158 ["Show Table Grid" org-table-fedit-toggle-coordinates
3159 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3160 org-table-overlay-coordinates)]
3161 "--"
3162 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3163 :style toggle :selected org-table-buffer-is-an]))
3165 (defvar org-pos)
3167 (defun org-table-edit-formulas ()
3168 "Edit the formulas of the current table in a separate buffer."
3169 (interactive)
3170 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3171 (beginning-of-line 0))
3172 (unless (org-at-table-p) (error "Not at a table"))
3173 (org-table-get-specials)
3174 (let ((key (org-table-current-field-formula 'key 'noerror))
3175 (eql (sort (org-table-get-stored-formulas 'noerror)
3176 'org-table-formula-less-p))
3177 (pos (move-marker (make-marker) (point)))
3178 (startline 1)
3179 (wc (current-window-configuration))
3180 (sel-win (selected-window))
3181 (titles '((column . "# Column Formulas\n")
3182 (field . "# Field and Range Formulas\n")
3183 (named . "# Named Field Formulas\n")))
3184 entry s type title)
3185 (org-switch-to-buffer-other-window "*Edit Formulas*")
3186 (erase-buffer)
3187 ;; Keep global-font-lock-mode from turning on font-lock-mode
3188 (let ((font-lock-global-modes '(not fundamental-mode)))
3189 (fundamental-mode))
3190 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3191 (org-set-local 'org-pos pos)
3192 (org-set-local 'org-window-configuration wc)
3193 (org-set-local 'org-selected-window sel-win)
3194 (use-local-map org-table-fedit-map)
3195 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3196 (easy-menu-add org-table-fedit-menu)
3197 (setq startline (org-current-line))
3198 (while (setq entry (pop eql))
3199 (setq type (cond
3200 ((string-match "\\`$[<>]" (car entry)) 'column)
3201 ((equal (string-to-char (car entry)) ?@) 'field)
3202 ((string-match "^[0-9]" (car entry)) 'column)
3203 (t 'named)))
3204 (when (setq title (assq type titles))
3205 (or (bobp) (insert "\n"))
3206 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3207 (setq titles (remove title titles)))
3208 (if (equal key (car entry)) (setq startline (org-current-line)))
3209 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3210 (car entry) " = " (cdr entry) "\n"))
3211 (remove-text-properties 0 (length s) '(face nil) s)
3212 (insert s))
3213 (if (eq org-table-use-standard-references t)
3214 (org-table-fedit-toggle-ref-type))
3215 (org-goto-line startline)
3216 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3218 (defun org-table-fedit-post-command ()
3219 (when (not (memq this-command '(lisp-complete-symbol)))
3220 (let ((win (selected-window)))
3221 (save-excursion
3222 (condition-case nil
3223 (org-table-show-reference)
3224 (error nil))
3225 (select-window win)))))
3227 (defun org-table-formula-to-user (s)
3228 "Convert a formula from internal to user representation."
3229 (if (eq org-table-use-standard-references t)
3230 (org-table-convert-refs-to-an s)
3233 (defun org-table-formula-from-user (s)
3234 "Convert a formula from user to internal representation."
3235 (if org-table-use-standard-references
3236 (org-table-convert-refs-to-rc s)
3239 (defun org-table-convert-refs-to-rc (s)
3240 "Convert spreadsheet references from A7 to @7$28.
3241 Works for single references, but also for entire formulas and even the
3242 full TBLFM line."
3243 (let ((start 0))
3244 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3245 (cond
3246 ((match-end 3)
3247 ;; format match, just advance
3248 (setq start (match-end 0)))
3249 ((and (> (match-beginning 0) 0)
3250 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3251 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3252 ;; 3.e5 or something like this.
3253 (setq start (match-end 0)))
3254 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3255 ;; (member (match-string 1 s)
3256 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3258 ;; function name, just advance
3259 (setq start (match-end 0)))
3261 (setq start (match-beginning 0)
3262 s (replace-match
3263 (if (equal (match-string 2 s) "&")
3264 (format "$%d" (org-letters-to-number (match-string 1 s)))
3265 (format "@%d$%d"
3266 (string-to-number (match-string 2 s))
3267 (org-letters-to-number (match-string 1 s))))
3268 t t s)))))
3271 (defun org-table-convert-refs-to-an (s)
3272 "Convert spreadsheet references from to @7$28 to AB7.
3273 Works for single references, but also for entire formulas and even the
3274 full TBLFM line."
3275 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3276 (setq s (replace-match
3277 (format "%s%d"
3278 (org-number-to-letters
3279 (string-to-number (match-string 2 s)))
3280 (string-to-number (match-string 1 s)))
3281 t t s)))
3282 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3283 (setq s (replace-match (concat "\\1"
3284 (org-number-to-letters
3285 (string-to-number (match-string 2 s))) "&")
3286 t nil s)))
3289 (defun org-letters-to-number (s)
3290 "Convert a base 26 number represented by letters into an integer.
3291 For example: AB -> 28."
3292 (let ((n 0))
3293 (setq s (upcase s))
3294 (while (> (length s) 0)
3295 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3296 s (substring s 1)))
3299 (defun org-number-to-letters (n)
3300 "Convert an integer into a base 26 number represented by letters.
3301 For example: 28 -> AB."
3302 (let ((s ""))
3303 (while (> n 0)
3304 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3305 n (/ (1- n) 26)))
3308 (defun org-table-time-string-to-seconds (s)
3309 "Convert a time string into numerical duration in seconds.
3310 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3311 If S is a string representing a number, keep this number."
3312 (if (equal s "")
3314 (let (hour minus min sec res)
3315 (cond
3316 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3317 (setq minus (< 0 (length (match-string 1 s)))
3318 hour (string-to-number (match-string 2 s))
3319 min (string-to-number (match-string 3 s))
3320 sec (string-to-number (match-string 4 s)))
3321 (if minus
3322 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3323 (setq res (+ (* hour 3600) (* min 60) sec))))
3324 ((and (not (string-match org-ts-regexp-both s))
3325 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3326 (setq minus (< 0 (length (match-string 1 s)))
3327 hour (string-to-number (match-string 2 s))
3328 min (string-to-number (match-string 3 s)))
3329 (if minus
3330 (setq res (- (+ (* hour 3600) (* min 60))))
3331 (setq res (+ (* hour 3600) (* min 60)))))
3332 (t (setq res (string-to-number s))))
3333 (number-to-string res))))
3335 (defun org-table-time-seconds-to-string (secs &optional output-format)
3336 "Convert a number of seconds to a time string.
3337 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3338 minutes or seconds."
3339 (let* ((secs0 (abs secs))
3340 (res
3341 (cond ((eq output-format 'days)
3342 (format "%.3f" (/ (float secs0) 86400)))
3343 ((eq output-format 'hours)
3344 (format "%.2f" (/ (float secs0) 3600)))
3345 ((eq output-format 'minutes)
3346 (format "%.1f" (/ (float secs0) 60)))
3347 ((eq output-format 'seconds)
3348 (format "%d" secs0))
3349 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3350 (if (< secs 0) (concat "-" res) res)))
3352 (defun org-table-fedit-convert-buffer (function)
3353 "Convert all references in this buffer, using FUNCTION."
3354 (let ((line (org-current-line)))
3355 (goto-char (point-min))
3356 (while (not (eobp))
3357 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3358 (delete-region (point) (point-at-eol))
3359 (or (eobp) (forward-char 1)))
3360 (org-goto-line line)))
3362 (defun org-table-fedit-toggle-ref-type ()
3363 "Convert all references in the buffer from B3 to @3$2 and back."
3364 (interactive)
3365 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3366 (org-table-fedit-convert-buffer
3367 (if org-table-buffer-is-an
3368 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3369 (message "Reference type switched to %s"
3370 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3372 (defun org-table-fedit-ref-up ()
3373 "Shift the reference at point one row/hline up."
3374 (interactive)
3375 (org-table-fedit-shift-reference 'up))
3376 (defun org-table-fedit-ref-down ()
3377 "Shift the reference at point one row/hline down."
3378 (interactive)
3379 (org-table-fedit-shift-reference 'down))
3380 (defun org-table-fedit-ref-left ()
3381 "Shift the reference at point one field to the left."
3382 (interactive)
3383 (org-table-fedit-shift-reference 'left))
3384 (defun org-table-fedit-ref-right ()
3385 "Shift the reference at point one field to the right."
3386 (interactive)
3387 (org-table-fedit-shift-reference 'right))
3389 (defun org-table-fedit-shift-reference (dir)
3390 (cond
3391 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3392 (if (memq dir '(left right))
3393 (org-rematch-and-replace 1 (eq dir 'left))
3394 (error "Cannot shift reference in this direction")))
3395 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3396 ;; A B3-like reference
3397 (if (memq dir '(up down))
3398 (org-rematch-and-replace 2 (eq dir 'up))
3399 (org-rematch-and-replace 1 (eq dir 'left))))
3400 ((org-at-regexp-p
3401 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3402 ;; An internal reference
3403 (if (memq dir '(up down))
3404 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3405 (org-rematch-and-replace 5 (eq dir 'left))))))
3407 (defun org-rematch-and-replace (n &optional decr hline)
3408 "Re-match the group N, and replace it with the shifted reference."
3409 (or (match-end n) (error "Cannot shift reference in this direction"))
3410 (goto-char (match-beginning n))
3411 (and (looking-at (regexp-quote (match-string n)))
3412 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3413 t t)))
3415 (defun org-table-shift-refpart (ref &optional decr hline)
3416 "Shift a reference part REF.
3417 If DECR is set, decrease the references row/column, else increase.
3418 If HLINE is set, this may be a hline reference, it certainly is not
3419 a translation reference."
3420 (save-match-data
3421 (let* ((sign (string-match "^[-+]" ref)) n)
3423 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3424 (cond
3425 ((and hline (string-match "^I+" ref))
3426 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3427 (setq n (+ n (if decr -1 1)))
3428 (if (= n 0) (setq n (+ n (if decr -1 1))))
3429 (if sign
3430 (setq sign (if (< n 0) "-" "+") n (abs n))
3431 (setq n (max 1 n)))
3432 (concat sign (make-string n ?I)))
3434 ((string-match "^[0-9]+" ref)
3435 (setq n (string-to-number (concat sign ref)))
3436 (setq n (+ n (if decr -1 1)))
3437 (if sign
3438 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3439 (number-to-string (max 1 n))))
3441 ((string-match "^[a-zA-Z]+" ref)
3442 (org-number-to-letters
3443 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3445 (t (error "Cannot shift reference"))))))
3447 (defun org-table-fedit-toggle-coordinates ()
3448 "Toggle the display of coordinates in the referenced table."
3449 (interactive)
3450 (let ((pos (marker-position org-pos)))
3451 (with-current-buffer (marker-buffer org-pos)
3452 (save-excursion
3453 (goto-char pos)
3454 (org-table-toggle-coordinate-overlays)))))
3456 (defun org-table-fedit-finish (&optional arg)
3457 "Parse the buffer for formula definitions and install them.
3458 With prefix ARG, apply the new formulas to the table."
3459 (interactive "P")
3460 (org-table-remove-rectangle-highlight)
3461 (if org-table-use-standard-references
3462 (progn
3463 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3464 (setq org-table-buffer-is-an nil)))
3465 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3466 (goto-char (point-min))
3467 (while (re-search-forward
3468 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3469 nil t)
3470 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3471 form (match-string 3))
3472 (setq form (org-trim form))
3473 (when (not (equal form ""))
3474 (while (string-match "[ \t]*\n[ \t]*" form)
3475 (setq form (replace-match " " t t form)))
3476 (when (assoc var eql)
3477 (error "Double formulas for %s" var))
3478 (push (cons var form) eql)))
3479 (setq org-pos nil)
3480 (set-window-configuration org-window-configuration)
3481 (select-window sel-win)
3482 (goto-char pos)
3483 (unless (org-at-table-p)
3484 (error "Lost table position - cannot install formulas"))
3485 (org-table-store-formulas eql)
3486 (move-marker pos nil)
3487 (kill-buffer "*Edit Formulas*")
3488 (if arg
3489 (org-table-recalculate 'all)
3490 (message "New formulas installed - press C-u C-c C-c to apply."))))
3492 (defun org-table-fedit-abort ()
3493 "Abort editing formulas, without installing the changes."
3494 (interactive)
3495 (org-table-remove-rectangle-highlight)
3496 (let ((pos org-pos) (sel-win org-selected-window))
3497 (set-window-configuration org-window-configuration)
3498 (select-window sel-win)
3499 (goto-char pos)
3500 (move-marker pos nil)
3501 (message "Formula editing aborted without installing changes")))
3503 (defun org-table-fedit-lisp-indent ()
3504 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3505 (interactive)
3506 (let ((pos (point)) beg end ind)
3507 (beginning-of-line 1)
3508 (cond
3509 ((looking-at "[ \t]")
3510 (goto-char pos)
3511 (call-interactively 'lisp-indent-line))
3512 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3513 ((not (fboundp 'pp-buffer))
3514 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3515 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3516 (goto-char (- (match-end 0) 2))
3517 (setq beg (point))
3518 (setq ind (make-string (current-column) ?\ ))
3519 (condition-case nil (forward-sexp 1)
3520 (error
3521 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3522 (setq end (point))
3523 (save-restriction
3524 (narrow-to-region beg end)
3525 (if (eq last-command this-command)
3526 (progn
3527 (goto-char (point-min))
3528 (setq this-command nil)
3529 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3530 (replace-match " ")))
3531 (pp-buffer)
3532 (untabify (point-min) (point-max))
3533 (goto-char (1+ (point-min)))
3534 (while (re-search-forward "^." nil t)
3535 (beginning-of-line 1)
3536 (insert ind))
3537 (goto-char (point-max))
3538 (backward-delete-char 1)))
3539 (goto-char beg))
3540 (t nil))))
3542 (defvar org-show-positions nil)
3544 (defun org-table-show-reference (&optional local)
3545 "Show the location/value of the $ expression at point."
3546 (interactive)
3547 (org-table-remove-rectangle-highlight)
3548 (catch 'exit
3549 (let ((pos (if local (point) org-pos))
3550 (face2 'highlight)
3551 (org-inhibit-highlight-removal t)
3552 (win (selected-window))
3553 (org-show-positions nil)
3554 var name e what match dest)
3555 (if local (org-table-get-specials))
3556 (setq what (cond
3557 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3558 (setq match (concat (substring (match-string 0) 0 -1)
3559 "$1.."
3560 (substring (match-string 0) 0 -1)
3561 "$100"))
3562 'range)
3563 ((or (org-at-regexp-p org-table-range-regexp2)
3564 (org-at-regexp-p org-table-translate-regexp)
3565 (org-at-regexp-p org-table-range-regexp))
3566 (setq match
3567 (save-match-data
3568 (org-table-convert-refs-to-rc (match-string 0))))
3569 'range)
3570 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3571 ((org-at-regexp-p "\\$[0-9]+") 'column)
3572 ((not local) nil)
3573 (t (error "No reference at point")))
3574 match (and what (or match (match-string 0))))
3575 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3576 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3577 'secondary-selection))
3578 (org-add-hook 'before-change-functions
3579 'org-table-remove-rectangle-highlight)
3580 (if (eq what 'name) (setq var (substring match 1)))
3581 (when (eq what 'range)
3582 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3583 (setq match (org-table-formula-substitute-names match)))
3584 (unless local
3585 (save-excursion
3586 (end-of-line 1)
3587 (re-search-backward "^\\S-" nil t)
3588 (beginning-of-line 1)
3589 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3590 (setq dest
3591 (save-match-data
3592 (org-table-convert-refs-to-rc (match-string 1))))
3593 (org-table-add-rectangle-overlay
3594 (match-beginning 1) (match-end 1) face2))))
3595 (if (and (markerp pos) (marker-buffer pos))
3596 (if (get-buffer-window (marker-buffer pos))
3597 (select-window (get-buffer-window (marker-buffer pos)))
3598 (org-switch-to-buffer-other-window (get-buffer-window
3599 (marker-buffer pos)))))
3600 (goto-char pos)
3601 (org-table-force-dataline)
3602 (when dest
3603 (setq name (substring dest 1))
3604 (cond
3605 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3606 (setq e (assoc name org-table-named-field-locations))
3607 (org-goto-line (nth 1 e))
3608 (org-table-goto-column (nth 2 e)))
3609 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3610 (let ((l (string-to-number (match-string 1 dest)))
3611 (c (string-to-number (match-string 2 dest))))
3612 (org-goto-line (aref org-table-dlines l))
3613 (org-table-goto-column c)))
3614 (t (org-table-goto-column (string-to-number name))))
3615 (move-marker pos (point))
3616 (org-table-highlight-rectangle nil nil face2))
3617 (cond
3618 ((equal dest match))
3619 ((not match))
3620 ((eq what 'range)
3621 (condition-case nil
3622 (save-excursion
3623 (org-table-get-range match nil nil 'highlight))
3624 (error nil)))
3625 ((setq e (assoc var org-table-named-field-locations))
3626 (org-goto-line (nth 1 e))
3627 (org-table-goto-column (nth 2 e))
3628 (org-table-highlight-rectangle (point) (point))
3629 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3630 ((setq e (assoc var org-table-column-names))
3631 (org-table-goto-column (string-to-number (cdr e)))
3632 (org-table-highlight-rectangle (point) (point))
3633 (goto-char (org-table-begin))
3634 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3635 (org-table-end) t)
3636 (progn
3637 (goto-char (match-beginning 1))
3638 (org-table-highlight-rectangle)
3639 (message "Named column (column %s)" (cdr e)))
3640 (error "Column name not found")))
3641 ((eq what 'column)
3642 ;; column number
3643 (org-table-goto-column (string-to-number (substring match 1)))
3644 (org-table-highlight-rectangle (point) (point))
3645 (message "Column %s" (substring match 1)))
3646 ((setq e (assoc var org-table-local-parameters))
3647 (goto-char (org-table-begin))
3648 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3649 (progn
3650 (goto-char (match-beginning 1))
3651 (org-table-highlight-rectangle)
3652 (message "Local parameter."))
3653 (error "Parameter not found")))
3655 (cond
3656 ((not var) (error "No reference at point"))
3657 ((setq e (assoc var org-table-formula-constants-local))
3658 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3659 var (cdr e)))
3660 ((setq e (assoc var org-table-formula-constants))
3661 (message "Constant: $%s=%s in `org-table-formula-constants'."
3662 var (cdr e)))
3663 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3664 (message "Constant: $%s=%s, from `constants.el'%s."
3665 var e (format " (%s units)" constants-unit-system)))
3666 (t (error "Undefined name $%s" var)))))
3667 (goto-char pos)
3668 (when (and org-show-positions
3669 (not (memq this-command '(org-table-fedit-scroll
3670 org-table-fedit-scroll-down))))
3671 (push pos org-show-positions)
3672 (push org-table-current-begin-pos org-show-positions)
3673 (let ((min (apply 'min org-show-positions))
3674 (max (apply 'max org-show-positions)))
3675 (goto-char min) (recenter 0)
3676 (goto-char max)
3677 (or (pos-visible-in-window-p max) (recenter -1))))
3678 (select-window win))))
3680 (defun org-table-force-dataline ()
3681 "Make sure the cursor is in a dataline in a table."
3682 (unless (save-excursion
3683 (beginning-of-line 1)
3684 (looking-at org-table-dataline-regexp))
3685 (let* ((re org-table-dataline-regexp)
3686 (p1 (save-excursion (re-search-forward re nil 'move)))
3687 (p2 (save-excursion (re-search-backward re nil 'move))))
3688 (cond ((and p1 p2)
3689 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3690 p1 p2)))
3691 ((or p1 p2) (goto-char (or p1 p2)))
3692 (t (error "No table dataline around here"))))))
3694 (defun org-table-fedit-line-up ()
3695 "Move cursor one line up in the window showing the table."
3696 (interactive)
3697 (org-table-fedit-move 'previous-line))
3699 (defun org-table-fedit-line-down ()
3700 "Move cursor one line down in the window showing the table."
3701 (interactive)
3702 (org-table-fedit-move 'next-line))
3704 (defun org-table-fedit-move (command)
3705 "Move the cursor in the window showing the table.
3706 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3707 (let ((org-table-allow-automatic-line-recalculation nil)
3708 (pos org-pos) (win (selected-window)) p)
3709 (select-window (get-buffer-window (marker-buffer org-pos)))
3710 (setq p (point))
3711 (call-interactively command)
3712 (while (and (org-at-table-p)
3713 (org-at-table-hline-p))
3714 (call-interactively command))
3715 (or (org-at-table-p) (goto-char p))
3716 (move-marker pos (point))
3717 (select-window win)))
3719 (defun org-table-fedit-scroll (N)
3720 (interactive "p")
3721 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3722 (scroll-other-window N)))
3724 (defun org-table-fedit-scroll-down (N)
3725 (interactive "p")
3726 (org-table-fedit-scroll (- N)))
3728 (defvar org-table-rectangle-overlays nil)
3730 (defun org-table-add-rectangle-overlay (beg end &optional face)
3731 "Add a new overlay."
3732 (let ((ov (make-overlay beg end)))
3733 (overlay-put ov 'face (or face 'secondary-selection))
3734 (push ov org-table-rectangle-overlays)))
3736 (defun org-table-highlight-rectangle (&optional beg end face)
3737 "Highlight rectangular region in a table."
3738 (setq beg (or beg (point)) end (or end (point)))
3739 (let ((b (min beg end))
3740 (e (max beg end))
3741 l1 c1 l2 c2 tmp)
3742 (and (boundp 'org-show-positions)
3743 (setq org-show-positions (cons b (cons e org-show-positions))))
3744 (goto-char (min beg end))
3745 (setq l1 (org-current-line)
3746 c1 (org-table-current-column))
3747 (goto-char (max beg end))
3748 (setq l2 (org-current-line)
3749 c2 (org-table-current-column))
3750 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3751 (org-goto-line l1)
3752 (beginning-of-line 1)
3753 (loop for line from l1 to l2 do
3754 (when (looking-at org-table-dataline-regexp)
3755 (org-table-goto-column c1)
3756 (skip-chars-backward "^|\n") (setq beg (point))
3757 (org-table-goto-column c2)
3758 (skip-chars-forward "^|\n") (setq end (point))
3759 (org-table-add-rectangle-overlay beg end face))
3760 (beginning-of-line 2))
3761 (goto-char b))
3762 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3764 (defun org-table-remove-rectangle-highlight (&rest ignore)
3765 "Remove the rectangle overlays."
3766 (unless org-inhibit-highlight-removal
3767 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3768 (mapc 'delete-overlay org-table-rectangle-overlays)
3769 (setq org-table-rectangle-overlays nil)))
3771 (defvar org-table-coordinate-overlays nil
3772 "Collects the coordinate grid overlays, so that they can be removed.")
3773 (make-variable-buffer-local 'org-table-coordinate-overlays)
3775 (defun org-table-overlay-coordinates ()
3776 "Add overlays to the table at point, to show row/column coordinates."
3777 (interactive)
3778 (mapc 'delete-overlay org-table-coordinate-overlays)
3779 (setq org-table-coordinate-overlays nil)
3780 (save-excursion
3781 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3782 (goto-char (org-table-begin))
3783 (while (org-at-table-p)
3784 (setq eol (point-at-eol))
3785 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3786 (push ov org-table-coordinate-overlays)
3787 (setq hline (looking-at org-table-hline-regexp))
3788 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3789 (format "%4d" (setq id (1+ id)))))
3790 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3791 (when hline
3792 (setq ic 0)
3793 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3794 (setq beg (1+ (match-beginning 0))
3795 ic (1+ ic)
3796 s1 (concat "$" (int-to-string ic))
3797 s2 (org-number-to-letters ic)
3798 str (if (eq org-table-use-standard-references t) s2 s1))
3799 (setq ov (make-overlay beg (+ beg (length str))))
3800 (push ov org-table-coordinate-overlays)
3801 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3802 (beginning-of-line 2)))))
3804 (defun org-table-toggle-coordinate-overlays ()
3805 "Toggle the display of Row/Column numbers in tables."
3806 (interactive)
3807 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3808 (message "Tables Row/Column numbers display turned %s"
3809 (if org-table-overlay-coordinates "on" "off"))
3810 (if (and (org-at-table-p) org-table-overlay-coordinates)
3811 (org-table-align))
3812 (unless org-table-overlay-coordinates
3813 (mapc 'delete-overlay org-table-coordinate-overlays)
3814 (setq org-table-coordinate-overlays nil)))
3816 (defun org-table-toggle-formula-debugger ()
3817 "Toggle the formula debugger in tables."
3818 (interactive)
3819 (setq org-table-formula-debug (not org-table-formula-debug))
3820 (message "Formula debugging has been turned %s"
3821 (if org-table-formula-debug "on" "off")))
3823 ;;; The orgtbl minor mode
3825 ;; Define a minor mode which can be used in other modes in order to
3826 ;; integrate the org-mode table editor.
3828 ;; This is really a hack, because the org-mode table editor uses several
3829 ;; keys which normally belong to the major mode, for example the TAB and
3830 ;; RET keys. Here is how it works: The minor mode defines all the keys
3831 ;; necessary to operate the table editor, but wraps the commands into a
3832 ;; function which tests if the cursor is currently inside a table. If that
3833 ;; is the case, the table editor command is executed. However, when any of
3834 ;; those keys is used outside a table, the function uses `key-binding' to
3835 ;; look up if the key has an associated command in another currently active
3836 ;; keymap (minor modes, major mode, global), and executes that command.
3837 ;; There might be problems if any of the keys used by the table editor is
3838 ;; otherwise used as a prefix key.
3840 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3841 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3842 ;; addresses this by checking explicitly for both bindings.
3844 ;; The optimized version (see variable `orgtbl-optimized') takes over
3845 ;; all keys which are bound to `self-insert-command' in the *global map*.
3846 ;; Some modes bind other commands to simple characters, for example
3847 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3848 ;; active, this binding is ignored inside tables and replaced with a
3849 ;; modified self-insert.
3852 (defvar orgtbl-mode-map (make-keymap)
3853 "Keymap for `orgtbl-mode'.")
3855 ;;;###autoload
3856 (defun turn-on-orgtbl ()
3857 "Unconditionally turn on `orgtbl-mode'."
3858 (orgtbl-mode 1))
3860 (defvar org-old-auto-fill-inhibit-regexp nil
3861 "Local variable used by `orgtbl-mode'.")
3863 (defconst orgtbl-line-start-regexp
3864 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
3865 "Matches a line belonging to an orgtbl.")
3867 (defconst orgtbl-extra-font-lock-keywords
3868 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3869 0 (quote 'org-table) 'prepend))
3870 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3872 ;; Install it as a minor mode.
3873 (put 'orgtbl-mode :included t)
3874 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3876 ;;;###autoload
3877 (define-minor-mode orgtbl-mode
3878 "The `org-mode' table editor as a minor mode for use in other modes."
3879 :lighter " OrgTbl" :keymap orgtbl-mode-map
3880 (org-load-modules-maybe)
3881 (cond
3882 ((derived-mode-p 'org-mode)
3883 ;; Exit without error, in case some hook functions calls this
3884 ;; by accident in org-mode.
3885 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3886 (orgtbl-mode
3887 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3888 ;; Make sure we are first in minor-mode-map-alist
3889 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3890 ;; FIXME: maybe it should use emulation-mode-map-alists?
3891 (and c (setq minor-mode-map-alist
3892 (cons c (delq c minor-mode-map-alist)))))
3893 (org-set-local (quote org-table-may-need-update) t)
3894 (org-add-hook 'before-change-functions 'org-before-change-function
3895 nil 'local)
3896 (org-set-local 'org-old-auto-fill-inhibit-regexp
3897 auto-fill-inhibit-regexp)
3898 (org-set-local 'auto-fill-inhibit-regexp
3899 (if auto-fill-inhibit-regexp
3900 (concat orgtbl-line-start-regexp "\\|"
3901 auto-fill-inhibit-regexp)
3902 orgtbl-line-start-regexp))
3903 (add-to-invisibility-spec '(org-cwidth))
3904 (when (fboundp 'font-lock-add-keywords)
3905 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3906 (org-restart-font-lock))
3907 (easy-menu-add orgtbl-mode-menu))
3909 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3910 (org-table-cleanup-narrow-column-properties)
3911 (org-remove-from-invisibility-spec '(org-cwidth))
3912 (remove-hook 'before-change-functions 'org-before-change-function t)
3913 (when (fboundp 'font-lock-remove-keywords)
3914 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3915 (org-restart-font-lock))
3916 (easy-menu-remove orgtbl-mode-menu)
3917 (force-mode-line-update 'all))))
3919 (defun org-table-cleanup-narrow-column-properties ()
3920 "Remove all properties related to narrow-column invisibility."
3921 (let ((s (point-min)))
3922 (while (setq s (text-property-any s (point-max)
3923 'display org-narrow-column-arrow))
3924 (remove-text-properties s (1+ s) '(display t)))
3925 (setq s (point-min))
3926 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3927 (remove-text-properties s (1+ s) '(org-cwidth t)))
3928 (setq s (point-min))
3929 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3930 (remove-text-properties s (1+ s) '(invisible t)))))
3932 (defun orgtbl-make-binding (fun n &rest keys)
3933 "Create a function for binding in the table minor mode.
3934 FUN is the command to call inside a table. N is used to create a unique
3935 command name. KEYS are keys that should be checked in for a command
3936 to execute outside of tables."
3937 (eval
3938 (list 'defun
3939 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3940 '(arg)
3941 (concat "In tables, run `" (symbol-name fun) "'.\n"
3942 "Outside of tables, run the binding of `"
3943 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3944 "'.")
3945 '(interactive "p")
3946 (list 'if
3947 '(org-at-table-p)
3948 (list 'call-interactively (list 'quote fun))
3949 (list 'let '(orgtbl-mode)
3950 (list 'call-interactively
3951 (append '(or)
3952 (mapcar (lambda (k)
3953 (list 'key-binding k))
3954 keys)
3955 '('orgtbl-error))))))))
3957 (defun orgtbl-error ()
3958 "Error when there is no default binding for a table key."
3959 (interactive)
3960 (error "This key has no function outside tables"))
3962 (defun orgtbl-setup ()
3963 "Setup orgtbl keymaps."
3964 (let ((nfunc 0)
3965 (bindings
3966 '(([(meta shift left)] org-table-delete-column)
3967 ([(meta left)] org-table-move-column-left)
3968 ([(meta right)] org-table-move-column-right)
3969 ([(meta shift right)] org-table-insert-column)
3970 ([(meta shift up)] org-table-kill-row)
3971 ([(meta shift down)] org-table-insert-row)
3972 ([(meta up)] org-table-move-row-up)
3973 ([(meta down)] org-table-move-row-down)
3974 ("\C-c\C-w" org-table-cut-region)
3975 ("\C-c\M-w" org-table-copy-region)
3976 ("\C-c\C-y" org-table-paste-rectangle)
3977 ("\C-c\C-w" org-table-wrap-region)
3978 ("\C-c-" org-table-insert-hline)
3979 ("\C-c}" org-table-toggle-coordinate-overlays)
3980 ("\C-c{" org-table-toggle-formula-debugger)
3981 ("\C-m" org-table-next-row)
3982 ([(shift return)] org-table-copy-down)
3983 ("\C-c?" org-table-field-info)
3984 ("\C-c " org-table-blank-field)
3985 ("\C-c+" org-table-sum)
3986 ("\C-c=" org-table-eval-formula)
3987 ("\C-c'" org-table-edit-formulas)
3988 ("\C-c`" org-table-edit-field)
3989 ("\C-c*" org-table-recalculate)
3990 ("\C-c^" org-table-sort-lines)
3991 ("\M-a" org-table-beginning-of-field)
3992 ("\M-e" org-table-end-of-field)
3993 ([(control ?#)] org-table-rotate-recalc-marks)))
3994 elt key fun cmd)
3995 (while (setq elt (pop bindings))
3996 (setq nfunc (1+ nfunc))
3997 (setq key (org-key (car elt))
3998 fun (nth 1 elt)
3999 cmd (orgtbl-make-binding fun nfunc key))
4000 (org-defkey orgtbl-mode-map key cmd))
4002 ;; Special treatment needed for TAB and RET
4003 (org-defkey orgtbl-mode-map [(return)]
4004 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4005 (org-defkey orgtbl-mode-map "\C-m"
4006 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4008 (org-defkey orgtbl-mode-map [(tab)]
4009 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4010 (org-defkey orgtbl-mode-map "\C-i"
4011 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4013 (org-defkey orgtbl-mode-map [(shift tab)]
4014 (orgtbl-make-binding 'org-table-previous-field 104
4015 [(shift tab)] [(tab)] "\C-i"))
4018 (unless (featurep 'xemacs)
4019 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4020 (orgtbl-make-binding 'org-table-previous-field 107
4021 [S-iso-lefttab] [backtab] [(shift tab)]
4022 [(tab)] "\C-i")))
4024 (org-defkey orgtbl-mode-map [backtab]
4025 (orgtbl-make-binding 'org-table-previous-field 108
4026 [backtab] [S-iso-lefttab] [(shift tab)]
4027 [(tab)] "\C-i"))
4029 (org-defkey orgtbl-mode-map "\M-\C-m"
4030 (orgtbl-make-binding 'org-table-wrap-region 105
4031 "\M-\C-m" [(meta return)]))
4032 (org-defkey orgtbl-mode-map [(meta return)]
4033 (orgtbl-make-binding 'org-table-wrap-region 106
4034 [(meta return)] "\M-\C-m"))
4036 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4037 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4039 (when orgtbl-optimized
4040 ;; If the user wants maximum table support, we need to hijack
4041 ;; some standard editing functions
4042 (org-remap orgtbl-mode-map
4043 'self-insert-command 'orgtbl-self-insert-command
4044 'delete-char 'org-delete-char
4045 'delete-backward-char 'org-delete-backward-char)
4046 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4047 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4048 '("OrgTbl"
4049 ["Create or convert" org-table-create-or-convert-from-region
4050 :active (not (org-at-table-p)) :keys "C-c |" ]
4051 "--"
4052 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4053 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4054 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4055 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4056 "--"
4057 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4058 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4059 ["Copy Field from Above"
4060 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4061 "--"
4062 ("Column"
4063 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4064 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4065 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4066 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4067 ("Row"
4068 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4069 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4070 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4071 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4072 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4073 "--"
4074 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4075 ("Rectangle"
4076 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4077 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4078 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4079 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4080 "--"
4081 ("Radio tables"
4082 ["Insert table template" orgtbl-insert-radio-table
4083 (assq major-mode orgtbl-radio-table-templates)]
4084 ["Comment/uncomment table" orgtbl-toggle-comment t])
4085 "--"
4086 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4087 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4088 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4089 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4090 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4091 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4092 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4093 ["Sum Column/Rectangle" org-table-sum
4094 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4095 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4096 ["Debug Formulas"
4097 org-table-toggle-formula-debugger :active (org-at-table-p)
4098 :keys "C-c {"
4099 :style toggle :selected org-table-formula-debug]
4100 ["Show Col/Row Numbers"
4101 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4102 :keys "C-c }"
4103 :style toggle :selected org-table-overlay-coordinates]
4107 (defun orgtbl-ctrl-c-ctrl-c (arg)
4108 "If the cursor is inside a table, realign the table.
4109 If it is a table to be sent away to a receiver, do it.
4110 With prefix arg, also recompute table."
4111 (interactive "P")
4112 (let ((case-fold-search t) (pos (point)) action consts-str consts cst const-str)
4113 (save-excursion
4114 (beginning-of-line 1)
4115 (setq action (cond
4116 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4117 ((looking-at "[ \t]*|") pos)
4118 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4119 (cond
4120 ((integerp action)
4121 (goto-char action)
4122 (org-table-maybe-eval-formula)
4123 (if arg
4124 (call-interactively 'org-table-recalculate)
4125 (org-table-maybe-recalculate-line))
4126 (call-interactively 'org-table-align)
4127 (when (orgtbl-send-table 'maybe)
4128 (run-hooks 'orgtbl-after-send-table-hook)))
4129 ((eq action 'recalc)
4130 (save-excursion
4131 (goto-char (point-min))
4132 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4133 (setq const-str (substring-no-properties (match-string 1)))
4134 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4135 (when consts
4136 (let (e)
4137 (while (setq e (pop consts))
4138 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4139 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4140 (setq org-table-formula-constants-local cst)))))
4141 (save-excursion
4142 (beginning-of-line 1)
4143 (skip-chars-backward " \r\n\t")
4144 (if (org-at-table-p)
4145 (org-call-with-arg 'org-table-recalculate t))))
4146 (t (let (orgtbl-mode)
4147 (call-interactively (key-binding "\C-c\C-c")))))))
4149 (defun orgtbl-create-or-convert-from-region (arg)
4150 "Create table or convert region to table, if no conflicting binding.
4151 This installs the table binding `C-c |', but only if there is no
4152 conflicting binding to this key outside orgtbl-mode."
4153 (interactive "P")
4154 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4155 (if cmd
4156 (call-interactively cmd)
4157 (call-interactively 'org-table-create-or-convert-from-region))))
4159 (defun orgtbl-tab (arg)
4160 "Justification and field motion for `orgtbl-mode'."
4161 (interactive "P")
4162 (if arg (org-table-edit-field t)
4163 (org-table-justify-field-maybe)
4164 (org-table-next-field)))
4166 (defun orgtbl-ret ()
4167 "Justification and field motion for `orgtbl-mode'."
4168 (interactive)
4169 (if (bobp)
4170 (newline)
4171 (org-table-justify-field-maybe)
4172 (org-table-next-row)))
4174 (defun orgtbl-self-insert-command (N)
4175 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4176 If the cursor is in a table looking at whitespace, the whitespace is
4177 overwritten, and the table is not marked as requiring realignment."
4178 (interactive "p")
4179 (if (and (org-at-table-p)
4181 (and org-table-auto-blank-field
4182 (member last-command
4183 '(orgtbl-hijacker-command-100
4184 orgtbl-hijacker-command-101
4185 orgtbl-hijacker-command-102
4186 orgtbl-hijacker-command-103
4187 orgtbl-hijacker-command-104
4188 orgtbl-hijacker-command-105
4189 yas/expand))
4190 (org-table-blank-field))
4192 (eq N 1)
4193 (looking-at "[^|\n]* +|"))
4194 (let (org-table-may-need-update)
4195 (goto-char (1- (match-end 0)))
4196 (backward-delete-char 1)
4197 (goto-char (match-beginning 0))
4198 (self-insert-command N))
4199 (setq org-table-may-need-update t)
4200 (let* (orgtbl-mode
4202 (cmd (or (key-binding
4203 (or (and (listp function-key-map)
4204 (setq a (assoc last-input-event function-key-map))
4205 (cdr a))
4206 (vector last-input-event)))
4207 'self-insert-command)))
4208 (call-interactively cmd)
4209 (if (and org-self-insert-cluster-for-undo
4210 (eq cmd 'self-insert-command))
4211 (if (not (eq last-command 'orgtbl-self-insert-command))
4212 (setq org-self-insert-command-undo-counter 1)
4213 (if (>= org-self-insert-command-undo-counter 20)
4214 (setq org-self-insert-command-undo-counter 1)
4215 (and (> org-self-insert-command-undo-counter 0)
4216 buffer-undo-list
4217 (not (cadr buffer-undo-list)) ; remove nil entry
4218 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4219 (setq org-self-insert-command-undo-counter
4220 (1+ org-self-insert-command-undo-counter))))))))
4222 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4223 "Regular expression matching exponentials as produced by calc.")
4225 (defun orgtbl-export (table target)
4226 (require 'org-exp)
4227 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4228 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4229 org-table-last-alignment org-table-last-column-widths
4230 maxcol column)
4231 (if (not (fboundp func))
4232 (error "Cannot export orgtbl table to %s" target))
4233 (setq lines (org-table-clean-before-export lines))
4234 (setq table
4235 (mapcar
4236 (lambda (x)
4237 (if (string-match org-table-hline-regexp x)
4238 'hline
4239 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4240 lines))
4241 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4242 table)))
4243 (loop for i from (1- maxcol) downto 0 do
4244 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4245 (setq column (delq nil column))
4246 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4247 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
4248 (funcall func table nil)))
4250 (defun orgtbl-gather-send-defs ()
4251 "Gather a plist of :name, :transform, :params for each destination before
4252 a radio table."
4253 (save-excursion
4254 (goto-char (org-table-begin))
4255 (let (rtn)
4256 (beginning-of-line 0)
4257 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4258 (let ((name (org-no-properties (match-string 1)))
4259 (transform (intern (match-string 2)))
4260 (params (if (match-end 3)
4261 (read (concat "(" (match-string 3) ")")))))
4262 (push (list :name name :transform transform :params params)
4263 rtn)
4264 (beginning-of-line 0)))
4265 rtn)))
4267 (defun orgtbl-send-replace-tbl (name txt)
4268 "Find and replace table NAME with TXT."
4269 (save-excursion
4270 (goto-char (point-min))
4271 (unless (re-search-forward
4272 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4273 (error "Don't know where to insert translated table"))
4274 (goto-char (match-beginning 0))
4275 (beginning-of-line 2)
4276 (save-excursion
4277 (let ((beg (point)))
4278 (unless (re-search-forward
4279 (concat "END RECEIVE ORGTBL +" name) nil t)
4280 (error "Cannot find end of insertion region"))
4281 (beginning-of-line 1)
4282 (delete-region beg (point))))
4283 (insert txt "\n")))
4285 ;;;###autoload
4286 (defun org-table-to-lisp (&optional txt)
4287 "Convert the table at point to a Lisp structure.
4288 The structure will be a list. Each item is either the symbol `hline'
4289 for a horizontal separator line, or a list of field values as strings.
4290 The table is taken from the parameter TXT, or from the buffer at point."
4291 (unless txt
4292 (unless (org-at-table-p)
4293 (error "No table at point")))
4294 (let* ((txt (or txt
4295 (buffer-substring-no-properties (org-table-begin)
4296 (org-table-end))))
4297 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4299 (mapcar
4300 (lambda (x)
4301 (if (string-match org-table-hline-regexp x)
4302 'hline
4303 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4304 lines)))
4306 (defun orgtbl-send-table (&optional maybe)
4307 "Send a transformed version of this table to the receiver position.
4308 With argument MAYBE, fail quietly if no transformation is defined for
4309 this table."
4310 (interactive)
4311 (catch 'exit
4312 (unless (org-at-table-p) (error "Not at a table"))
4313 ;; when non-interactive, we assume align has just happened.
4314 (when (org-called-interactively-p 'any) (org-table-align))
4315 (let ((dests (orgtbl-gather-send-defs))
4316 (txt (buffer-substring-no-properties (org-table-begin)
4317 (org-table-end)))
4318 (ntbl 0))
4319 (unless dests (if maybe (throw 'exit nil)
4320 (error "Don't know how to transform this table")))
4321 (dolist (dest dests)
4322 (let* ((name (plist-get dest :name))
4323 (transform (plist-get dest :transform))
4324 (params (plist-get dest :params))
4325 (skip (plist-get params :skip))
4326 (skipcols (plist-get params :skipcols))
4327 (no-escape (plist-get params :no-escape))
4329 (lines (org-table-clean-before-export
4330 (nthcdr (or skip 0)
4331 (org-split-string txt "[ \t]*\n[ \t]*"))))
4332 (i0 (if org-table-clean-did-remove-column 2 1))
4333 (lines (if no-escape lines
4334 (mapcar (lambda(l) (replace-regexp-in-string
4335 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4336 (table (mapcar
4337 (lambda (x)
4338 (if (string-match org-table-hline-regexp x)
4339 'hline
4340 (org-remove-by-index
4341 (org-split-string (org-trim x) "\\s-*|\\s-*")
4342 skipcols i0)))
4343 lines))
4344 (fun (if (= i0 2) 'cdr 'identity))
4345 (org-table-last-alignment
4346 (org-remove-by-index (funcall fun org-table-last-alignment)
4347 skipcols i0))
4348 (org-table-last-column-widths
4349 (org-remove-by-index (funcall fun org-table-last-column-widths)
4350 skipcols i0))
4351 (txt (if (fboundp transform)
4352 (funcall transform table params)
4353 (error "No such transformation function %s" transform))))
4354 (orgtbl-send-replace-tbl name txt))
4355 (setq ntbl (1+ ntbl)))
4356 (message "Table converted and installed at %d receiver location%s"
4357 ntbl (if (> ntbl 1) "s" ""))
4358 (if (> ntbl 0)
4359 ntbl
4360 nil))))
4362 (defun org-remove-by-index (list indices &optional i0)
4363 "Remove the elements in LIST with indices in INDICES.
4364 First element has index 0, or I0 if given."
4365 (if (not indices)
4366 list
4367 (if (integerp indices) (setq indices (list indices)))
4368 (setq i0 (1- (or i0 0)))
4369 (delq :rm (mapcar (lambda (x)
4370 (setq i0 (1+ i0))
4371 (if (memq i0 indices) :rm x))
4372 list))))
4374 (defun orgtbl-toggle-comment ()
4375 "Comment or uncomment the orgtbl at point."
4376 (interactive)
4377 (let* ((case-fold-search t)
4378 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4379 (re2 (concat "^" orgtbl-line-start-regexp))
4380 (commented (save-excursion (beginning-of-line 1)
4381 (cond ((looking-at re1) t)
4382 ((looking-at re2) nil)
4383 (t (error "Not at an org table")))))
4384 (re (if commented re1 re2))
4385 beg end)
4386 (save-excursion
4387 (beginning-of-line 1)
4388 (while (looking-at re) (beginning-of-line 0))
4389 (beginning-of-line 2)
4390 (setq beg (point))
4391 (while (looking-at re) (beginning-of-line 2))
4392 (setq end (point)))
4393 (comment-region beg end (if commented '(4) nil))))
4395 (defun orgtbl-insert-radio-table ()
4396 "Insert a radio table template appropriate for this major mode."
4397 (interactive)
4398 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4399 (txt (nth 1 e))
4400 name pos)
4401 (unless e (error "No radio table setup defined for %s" major-mode))
4402 (setq name (read-string "Table name: "))
4403 (while (string-match "%n" txt)
4404 (setq txt (replace-match name t t txt)))
4405 (or (bolp) (insert "\n"))
4406 (setq pos (point))
4407 (insert txt)
4408 (goto-char pos)))
4410 ;; Dynamically bound input and output for table formatting.
4411 (defvar *orgtbl-table* nil
4412 "Carries the current table through formatting routines.")
4413 (defvar *orgtbl-rtn* nil
4414 "Formatting routines push the output lines here.")
4415 ;; Formatting parameters for the current table section.
4416 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4417 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4418 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4419 (defvar *orgtbl-fmt* nil "Format for each entry.")
4420 (defvar *orgtbl-efmt* nil "Format for numbers.")
4421 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4422 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4423 (defvar *orgtbl-lstart* nil "Text starting a row.")
4424 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4425 (defvar *orgtbl-lend* nil "Text ending a row.")
4426 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4428 (defsubst orgtbl-get-fmt (fmt i)
4429 "Retrieve the format from FMT corresponding to the Ith column."
4430 (if (and (not (functionp fmt)) (consp fmt))
4431 (plist-get fmt i)
4432 fmt))
4434 (defsubst orgtbl-apply-fmt (fmt &rest args)
4435 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4436 (cond ((functionp fmt) (apply fmt args))
4437 (fmt (apply 'format fmt args))
4438 (args (car args))
4439 (t args)))
4441 (defsubst orgtbl-eval-str (str)
4442 "If STR is a function, evaluate it with no arguments."
4443 (if (functionp str)
4444 (funcall str)
4445 str))
4447 (defun orgtbl-format-line (line)
4448 "Format LINE as a table row."
4449 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4450 (let* ((i 0)
4451 (line
4452 (mapcar
4453 (lambda (f)
4454 (setq i (1+ i))
4455 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4456 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4457 (orgtbl-apply-fmt efmt (match-string 1 f)
4458 (match-string 2 f))
4459 f)))
4460 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4461 *orgtbl-default-fmt*)
4462 f)))
4463 line)))
4464 (push (if *orgtbl-lfmt*
4465 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4466 (concat (orgtbl-eval-str *orgtbl-lstart*)
4467 (mapconcat 'identity line *orgtbl-sep*)
4468 (orgtbl-eval-str *orgtbl-lend*)))
4469 *orgtbl-rtn*))))
4471 (defun orgtbl-format-section (section-stopper)
4472 "Format lines until the first occurrence of SECTION-STOPPER."
4473 (let (prevline)
4474 (progn
4475 (while (not (eq (car *orgtbl-table*) section-stopper))
4476 (if prevline (orgtbl-format-line prevline))
4477 (setq prevline (pop *orgtbl-table*)))
4478 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4479 (*orgtbl-lend* *orgtbl-llend*)
4480 (*orgtbl-lfmt* *orgtbl-llfmt*))
4481 (orgtbl-format-line prevline))))))
4483 (defun orgtbl-to-generic (table params)
4484 "Convert the orgtbl-mode TABLE to some other format.
4485 This generic routine can be used for many standard cases.
4486 TABLE is a list, each entry either the symbol `hline' for a horizontal
4487 separator line, or a list of fields for that line.
4488 PARAMS is a property list of parameters that can influence the conversion.
4489 For the generic converter, some parameters are obligatory: you need to
4490 specify either :lfmt, or all of (:lstart :lend :sep).
4492 Valid parameters are:
4494 :splice When set to t, return only table body lines, don't wrap
4495 them into :tstart and :tend. Default is nil. When :splice
4496 is non-nil, this also means that the exporter should not look
4497 for and interpret header and footer sections.
4499 :hline String to be inserted on horizontal separation lines.
4500 May be nil to ignore hlines.
4502 :sep Separator between two fields
4503 :remove-nil-lines Do not include lines that evaluate to nil.
4505 Each in the following group may be either a string or a function
4506 of no arguments returning a string:
4508 :tstart String to start the table. Ignored when :splice is t.
4509 :tend String to end the table. Ignored when :splice is t.
4510 :lstart String to start a new table line.
4511 :llstart String to start the last table line, defaults to :lstart.
4512 :lend String to end a table line
4513 :llend String to end the last table line, defaults to :lend.
4515 Each in the following group may be a string, a function of one
4516 argument (the field or line) returning a string, or a plist
4517 mapping columns to either of the above:
4519 :lfmt Format for entire line, with enough %s to capture all fields.
4520 If this is present, :lstart, :lend, and :sep are ignored.
4521 :llfmt Format for the entire last line, defaults to :lfmt.
4522 :fmt A format to be used to wrap the field, should contain
4523 %s for the original field value. For example, to wrap
4524 everything in dollars, you could use :fmt \"$%s$\".
4525 This may also be a property list with column numbers and
4526 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4527 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4528 Same as above, specific for the header lines in the table.
4529 All lines before the first hline are treated as header.
4530 If any of these is not present, the data line value is used.
4532 This may be either a string or a function of two arguments:
4534 :efmt Use this format to print numbers with exponentials.
4535 The format should have %s twice for inserting mantissa
4536 and exponent, for example \"%s\\\\times10^{%s}\". This
4537 may also be a property list with column numbers and
4538 formats. :fmt will still be applied after :efmt.
4540 In addition to this, the parameters :skip and :skipcols are always handled
4541 directly by `orgtbl-send-table'. See manual."
4542 (let* ((splicep (plist-get params :splice))
4543 (hline (plist-get params :hline))
4544 (skipheadrule (plist-get params :skipheadrule))
4545 (remove-nil-linesp (plist-get params :remove-nil-lines))
4546 (remove-newlines (plist-get params :remove-newlines))
4547 (*orgtbl-hline* hline)
4548 (*orgtbl-table* table)
4549 (*orgtbl-sep* (plist-get params :sep))
4550 (*orgtbl-efmt* (plist-get params :efmt))
4551 (*orgtbl-lstart* (plist-get params :lstart))
4552 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4553 (*orgtbl-lend* (plist-get params :lend))
4554 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4555 (*orgtbl-lfmt* (plist-get params :lfmt))
4556 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4557 (*orgtbl-fmt* (plist-get params :fmt))
4558 *orgtbl-rtn*)
4560 ;; Put header
4561 (unless splicep
4562 (when (plist-member params :tstart)
4563 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4564 (if tstart (push tstart *orgtbl-rtn*)))))
4566 ;; Do we have a heading section? If so, format it and handle the
4567 ;; trailing hline.
4568 (if (and (not splicep)
4569 (or (consp (car *orgtbl-table*))
4570 (consp (nth 1 *orgtbl-table*)))
4571 (memq 'hline (cdr *orgtbl-table*)))
4572 (progn
4573 (when (eq 'hline (car *orgtbl-table*))
4574 ;; there is a hline before the first data line
4575 (and hline (push hline *orgtbl-rtn*))
4576 (pop *orgtbl-table*))
4577 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4578 *orgtbl-lstart*))
4579 (*orgtbl-llstart* (or (plist-get params :hllstart)
4580 *orgtbl-llstart*))
4581 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4582 (*orgtbl-llend* (or (plist-get params :hllend)
4583 (plist-get params :hlend) *orgtbl-llend*))
4584 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4585 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4586 (plist-get params :hlfmt) *orgtbl-llfmt*))
4587 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4588 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4589 (orgtbl-format-section 'hline))
4590 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4591 (pop *orgtbl-table*)))
4593 ;; Now format the main section.
4594 (orgtbl-format-section nil)
4596 (unless splicep
4597 (when (plist-member params :tend)
4598 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4599 (if tend (push tend *orgtbl-rtn*)))))
4601 (mapconcat (if remove-newlines
4602 (lambda (tend)
4603 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4604 'identity)
4605 (nreverse (if remove-nil-linesp
4606 (remq nil *orgtbl-rtn*)
4607 *orgtbl-rtn*)) "\n")))
4609 (defun orgtbl-to-tsv (table params)
4610 "Convert the orgtbl-mode table to TAB separated material."
4611 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4612 (defun orgtbl-to-csv (table params)
4613 "Convert the orgtbl-mode table to CSV material.
4614 This does take care of the proper quoting of fields with comma or quotes."
4615 (orgtbl-to-generic table (org-combine-plists
4616 '(:sep "," :fmt org-quote-csv-field)
4617 params)))
4619 (defun orgtbl-to-latex (table params)
4620 "Convert the orgtbl-mode TABLE to LaTeX.
4621 TABLE is a list, each entry either the symbol `hline' for a horizontal
4622 separator line, or a list of fields for that line.
4623 PARAMS is a property list of parameters that can influence the conversion.
4624 Supports all parameters from `orgtbl-to-generic'. Most important for
4625 LaTeX are:
4627 :splice When set to t, return only table body lines, don't wrap
4628 them into a tabular environment. Default is nil.
4630 :fmt A format to be used to wrap the field, should contain %s for the
4631 original field value. For example, to wrap everything in dollars,
4632 use :fmt \"$%s$\". This may also be a property list with column
4633 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4634 The format may also be a function that formats its one argument.
4636 :efmt Format for transforming numbers with exponentials. The format
4637 should have %s twice for inserting mantissa and exponent, for
4638 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4639 This may also be a property list with column numbers and formats.
4640 The format may also be a function that formats its two arguments.
4642 :llend If you find too much space below the last line of a table,
4643 pass a value of \"\" for :llend to suppress the final \\\\.
4645 The general parameters :skip and :skipcols have already been applied when
4646 this function is called."
4647 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4648 org-table-last-alignment ""))
4649 (params2
4650 (list
4651 :tstart (concat "\\begin{tabular}{" alignment "}")
4652 :tend "\\end{tabular}"
4653 :lstart "" :lend " \\\\" :sep " & "
4654 :efmt "%s\\,(%s)" :hline "\\hline")))
4655 (orgtbl-to-generic table (org-combine-plists params2 params))))
4657 (defun orgtbl-to-html (table params)
4658 "Convert the orgtbl-mode TABLE to HTML.
4659 TABLE is a list, each entry either the symbol `hline' for a horizontal
4660 separator line, or a list of fields for that line.
4661 PARAMS is a property list of parameters that can influence the conversion.
4662 Currently this function recognizes the following parameters:
4664 :splice When set to t, return only table body lines, don't wrap
4665 them into a <table> environment. Default is nil.
4667 The general parameters :skip and :skipcols have already been applied when
4668 this function is called. The function does *not* use `orgtbl-to-generic',
4669 so you cannot specify parameters for it."
4670 (let* ((splicep (plist-get params :splice))
4671 (html-table-tag org-export-html-table-tag)
4672 html)
4673 ;; Just call the formatter we already have
4674 ;; We need to make text lines for it, so put the fields back together.
4675 (setq html (org-format-org-table-html
4676 (mapcar
4677 (lambda (x)
4678 (if (eq x 'hline)
4679 "|----+----|"
4680 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4681 table)
4682 splicep))
4683 (if (string-match "\n+\\'" html)
4684 (setq html (replace-match "" t t html)))
4685 html))
4687 (defun orgtbl-to-texinfo (table params)
4688 "Convert the orgtbl-mode TABLE to TeXInfo.
4689 TABLE is a list, each entry either the symbol `hline' for a horizontal
4690 separator line, or a list of fields for that line.
4691 PARAMS is a property list of parameters that can influence the conversion.
4692 Supports all parameters from `orgtbl-to-generic'. Most important for
4693 TeXInfo are:
4695 :splice nil/t When set to t, return only table body lines, don't wrap
4696 them into a multitable environment. Default is nil.
4698 :fmt fmt A format to be used to wrap the field, should contain
4699 %s for the original field value. For example, to wrap
4700 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4701 This may also be a property list with column numbers and
4702 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4703 Each format also may be a function that formats its one
4704 argument.
4706 :cf \"f1 f2..\" The column fractions for the table. By default these
4707 are computed automatically from the width of the columns
4708 under org-mode.
4710 The general parameters :skip and :skipcols have already been applied when
4711 this function is called."
4712 (let* ((total (float (apply '+ org-table-last-column-widths)))
4713 (colfrac (or (plist-get params :cf)
4714 (mapconcat
4715 (lambda (x) (format "%.3f" (/ (float x) total)))
4716 org-table-last-column-widths " ")))
4717 (params2
4718 (list
4719 :tstart (concat "@multitable @columnfractions " colfrac)
4720 :tend "@end multitable"
4721 :lstart "@item " :lend "" :sep " @tab "
4722 :hlstart "@headitem ")))
4723 (orgtbl-to-generic table (org-combine-plists params2 params))))
4725 (defun orgtbl-to-orgtbl (table params)
4726 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4727 Useful when slicing one table into many. The :hline, :sep,
4728 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4729 and :tend suppress strings without splicing; they can be set to
4730 provide ORGTBL directives for the generated table."
4731 (let* ((params2
4732 (list
4733 :remove-newlines t
4734 :tstart nil :tend nil
4735 :hline "|---"
4736 :sep " | "
4737 :lstart "| "
4738 :lend " |"))
4739 (params (org-combine-plists params2 params)))
4740 (with-temp-buffer
4741 (insert (orgtbl-to-generic table params))
4742 (goto-char (point-min))
4743 (while (re-search-forward org-table-hline-regexp nil t)
4744 (org-table-align))
4745 (buffer-substring 1 (buffer-size)))))
4747 (defun orgtbl-to-table.el (table params)
4748 "Convert the orgtbl-mode TABLE into a table.el table."
4749 (with-temp-buffer
4750 (insert (orgtbl-to-orgtbl table params))
4751 (org-table-align)
4752 (replace-regexp-in-string
4753 "-|" "-+"
4754 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4756 (defun orgtbl-to-unicode (table params)
4757 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4758 You need the ascii-art-to-unicode.el package for this. You can download
4759 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4760 (with-temp-buffer
4761 (insert (orgtbl-to-table.el table params))
4762 (goto-char (point-min))
4763 (if (or (featurep 'ascii-art-to-unicode)
4764 (require 'ascii-art-to-unicode nil t))
4765 (aa2u)
4766 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4767 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4768 "Link to ascii-art-to-unicode.el") org-stored-links))
4769 (error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4770 (buffer-string)))
4772 (defun org-table-get-remote-range (name-or-id form)
4773 "Get a field value or a list of values in a range from table at ID.
4775 NAME-OR-ID may be the name of a table in the current file as set by
4776 a \"#+TBLNAME:\" directive. The first table following this line
4777 will then be used. Alternatively, it may be an ID referring to
4778 any entry, also in a different file. In this case, the first table
4779 in that entry will be referenced.
4780 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4781 \"@I$2..@II$2\". All the references must be absolute, not relative.
4783 The return value is either a single string for a single field, or a
4784 list of the fields in the rectangle ."
4785 (save-match-data
4786 (let ((case-fold-search t) (id-loc nil)
4787 ;; Protect a bunch of variables from being overwritten
4788 ;; by the context of the remote table
4789 org-table-column-names org-table-column-name-regexp
4790 org-table-local-parameters org-table-named-field-locations
4791 org-table-current-line-types org-table-current-begin-line
4792 org-table-current-begin-pos org-table-dlines
4793 org-table-current-ncol
4794 org-table-hlines org-table-last-alignment
4795 org-table-last-column-widths org-table-last-alignment
4796 org-table-last-column-widths tbeg
4797 buffer loc)
4798 (setq form (org-table-convert-refs-to-rc form))
4799 (save-excursion
4800 (save-restriction
4801 (widen)
4802 (save-excursion
4803 (goto-char (point-min))
4804 (if (re-search-forward
4805 (concat "^[ \t]*#\\+tblname:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4806 nil t)
4807 (setq buffer (current-buffer) loc (match-beginning 0))
4808 (setq id-loc (org-id-find name-or-id 'marker))
4809 (unless (and id-loc (markerp id-loc))
4810 (error "Can't find remote table \"%s\"" name-or-id))
4811 (setq buffer (marker-buffer id-loc)
4812 loc (marker-position id-loc))
4813 (move-marker id-loc nil)))
4814 (with-current-buffer buffer
4815 (save-excursion
4816 (save-restriction
4817 (widen)
4818 (goto-char loc)
4819 (forward-char 1)
4820 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4821 (not (match-beginning 1)))
4822 (error "Cannot find a table at NAME or ID %s" name-or-id))
4823 (setq tbeg (point-at-bol))
4824 (org-table-get-specials)
4825 (setq form (org-table-formula-substitute-names
4826 (org-table-formula-handle-first/last-rc form)))
4827 (if (and (string-match org-table-range-regexp form)
4828 (> (length (match-string 0 form)) 1))
4829 (save-match-data
4830 (org-table-get-range (match-string 0 form) tbeg 1))
4831 form)))))))))
4833 (provide 'org-table)
4835 ;;; org-table.el ends here