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