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