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