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